file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
usart3.rs
//! Test the USART3 instance //! //! Connect the TX and RX pins to run this test #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0"
use blue_pill::{Serial, stm32f103xx}; use blue_pill::time::Hertz; use hal::prelude::*; use nb::Error; use rtfm::{P0, T0, TMax}; // CONFIGURATION pub const BAUD_RATE: Hertz = Hertz(115_200); // RESOURCES peripherals!(stm32f103xx, { AFIO: Peripheral { ceiling: C0, }, GPIOB: Peripheral { cei...
#[macro_use] extern crate cortex_m_rtfm as rtfm; extern crate nb;
random_line_split
usart3.rs
//! Test the USART3 instance //! //! Connect the TX and RX pins to run this test #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; extern ...
Err(Error::Other(e)) => panic!("{:?}", e), Err(Error::WouldBlock) => continue, } } panic!("Timeout") } // IDLE LOOP fn idle(_prio: P0, _thr: T0) ->! { // OK rtfm::bkpt(); // Sleep loop { rtfm::wfi(); } } // TASKS tasks!(stm32f103xx, {});
{ assert_eq!(byte, BYTE); return; }
conditional_block
errors.rs
use self::WhichLine::*; use std::fmt; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::Path; use std::str::FromStr; use lazy_static::lazy_static; use regex::Regex; use tracing::*;
#[derive(Clone, Debug, PartialEq)] pub enum ErrorKind { Help, Error, Note, Suggestion, Warning, } impl FromStr for ErrorKind { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { let s = s.to_uppercase(); let part0: &str = s.split(':').next().unwrap(); ...
random_line_split
errors.rs
use self::WhichLine::*; use std::fmt; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::Path; use std::str::FromStr; use lazy_static::lazy_static; use regex::Regex; use tracing::*; #[derive(Clone, Debug, PartialEq)] pub enum ErrorKind { Help, Error, Note, Suggestion, ...
(testfile: &Path, cfg: Option<&str>) -> Vec<Error> { let rdr = BufReader::new(File::open(testfile).unwrap()); // `last_nonfollow_error` tracks the most recently seen // line with an error template that did not use the // follow-syntax, "//~|...". // // (pnkfelix could not find an easy way to co...
load_errors
identifier_name
errors.rs
use self::WhichLine::*; use std::fmt; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::Path; use std::str::FromStr; use lazy_static::lazy_static; use regex::Regex; use tracing::*; #[derive(Clone, Debug, PartialEq)] pub enum ErrorKind { Help, Error, Note, Suggestion, ...
(None, Some(_)) => panic!("Only tests with revisions should use `//[X]~`"), // If an error has no list of revisions, it applies to all revisions. (Some(_), None) | (None, None) => {} } let (follow, adjusts) = match &captures["adjust"] { "|" => (true, 0), circumflexes =>...
{ // Matches comments like: // //~ // //~| // //~^ // //~^^^^^ // //[cfg1]~ // //[cfg1,cfg2]~^^ lazy_static! { static ref RE: Regex = Regex::new(r"//(?:\[(?P<cfgs>[\w,]+)])?~(?P<adjust>\||\^*)").unwrap(); } let captures = RE.captures(l...
identifier_body
errors.rs
use self::WhichLine::*; use std::fmt; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::Path; use std::str::FromStr; use lazy_static::lazy_static; use regex::Regex; use tracing::*; #[derive(Clone, Debug, PartialEq)] pub enum ErrorKind { Help, Error, Note, Suggestion, ...
else { ThisLine }; let line_num = line_num - adjusts; (which, line_num) }; debug!( "line={} tag={:?} which={:?} kind={:?} msg={:?}", line_num, whole_match.as_str(), which, kind, msg ); Some((which, Error { line_num, kind, msg })) }
{ AdjustBackward(adjusts) }
conditional_block
time.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate time as std_time; use energy::read_energy_uj; use ipc_channel::ipc::IpcSender; use self::std_time::p...
let end_time = precise_time_ns(); let end_energy = read_energy_uj(); if opts::get().signpost { signpost::end(category as u32, &[0, 0, 0, (category as usize) >> 4]); } send_profile_data(category, meta, profiler_chan, start_tim...
let val = callback();
random_line_split
time.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate time as std_time; use energy::read_energy_uj; use ipc_channel::ipc::IpcSender; use self::std_time::p...
(pub IpcSender<ProfilerMsg>); impl ProfilerChan { pub fn send(&self, msg: ProfilerMsg) { if let Err(e) = self.0.send(msg) { warn!("Error communicating with the time profiler thread: {}", e); } } } #[derive(Clone, Deserialize, Serialize)] pub enum ProfilerMsg { /// Normal messag...
ProfilerChan
identifier_name
time.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate time as std_time; use energy::read_energy_uj; use ipc_channel::ipc::IpcSender; use self::std_time::p...
send_profile_data(category, meta, profiler_chan, start_time, end_time, start_energy, end_energy); val } pub fn send_profile_data(category: ProfilerCategory, ...
{ signpost::end(category as u32, &[0, 0, 0, (category as usize) >> 4]); }
conditional_block
config.rs
use std::io::{Read}; use std::rc::Rc; use std::fs::File; use std::path::{PathBuf, Path, Component}; use std::collections::BTreeMap; use rustc_serialize::{Decoder}; use quire::{Options, Include, Error, ErrorCollector, Pos, parse_config}; use quire::validate as V; use quire::parser::{parse as parse_yaml}; use quire::as...
<'a>() -> V::Structure<'a> { V::Structure::new() .member("minimum_vagga", MinimumVagga::new() .optional() .current_version(env!("VAGGA_VERSION").to_string())) .member("containers", V::Mapping::new( V::Scalar::new(), containers::container_validator())) .member("commands", V::Ma...
config_validator
identifier_name
config.rs
use std::io::{Read}; use std::rc::Rc; use std::fs::File; use std::path::{PathBuf, Path, Component}; use std::collections::BTreeMap; use rustc_serialize::{Decoder}; use quire::{Options, Include, Error, ErrorCollector, Pos, parse_config}; use quire::validate as V; use quire::parser::{parse as parse_yaml}; use quire::as...
.map_err(|e| err.add_error(Error::OpenError(path.clone(), e))).ok() .and_then(|_| { parse_yaml(Rc::new(path.display().to_string()), &body, |doc| { process_ast(&options, doc, err) }, ).map_err(|e| err.add_error(e)).ok() }) ....
{ let mut path = PathBuf::from(&*pos.filename); path.pop(); // pop original filename for component in Path::new(filename).components() { match component { Component::Normal(x) => path.push(x), _ => { err....
conditional_block
config.rs
use std::io::{Read}; use std::rc::Rc; use std::fs::File; use std::path::{PathBuf, Path, Component}; use std::collections::BTreeMap; use rustc_serialize::{Decoder}; use quire::{Options, Include, Error, ErrorCollector, Pos, parse_config}; use quire::validate as V; use quire::parser::{parse as parse_yaml}; use quire::as...
warn!("There is vagga.yml file in the {:?}, \ possibly it is a typo. \ Correct configuration file name is vagga.yaml", dir); } }
} fn maybe_print_typo_warning(dir: &Path) { if dir.join("vagga.yml").exists() {
random_line_split
config.rs
use std::io::{Read}; use std::rc::Rc; use std::fs::File; use std::path::{PathBuf, Path, Component}; use std::collections::BTreeMap; use rustc_serialize::{Decoder}; use quire::{Options, Include, Error, ErrorCollector, Pos, parse_config}; use quire::validate as V; use quire::parser::{parse as parse_yaml}; use quire::as...
{ if dir.join("vagga.yml").exists() { warn!("There is vagga.yml file in the {:?}, \ possibly it is a typo. \ Correct configuration file name is vagga.yaml", dir); } }
identifier_body
oscsictrl.rs
#[doc = "Register `OSCSICTRL` reader"] pub struct R(crate::R<OSCSICTRL_SPEC>); impl core::ops::Deref for R { type Target = crate::R<OSCSICTRL_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<OSCSICTRL_SPEC>> for R { #[inline(always)] fn from(read...
(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<OSCSICTRL_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<OSCSICTRL_SPEC>) -> Self { W(wri...
deref
identifier_name
oscsictrl.rs
#[doc = "Register `OSCSICTRL` reader"] pub struct R(crate::R<OSCSICTRL_SPEC>); impl core::ops::Deref for R { type Target = crate::R<OSCSICTRL_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<OSCSICTRL_SPEC>> for R { #[inline(always)] fn from(read...
} #[doc = "Field `PWD` writer - Turn OFF the fOSI Clock Source"] pub struct PWD_W<'a> { w: &'a mut W, } impl<'a> PWD_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWD_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Enabled"] ...
{ &self.0 }
identifier_body
oscsictrl.rs
#[doc = "Register `OSCSICTRL` reader"] pub struct R(crate::R<OSCSICTRL_SPEC>); impl core::ops::Deref for R { type Target = crate::R<OSCSICTRL_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target {
#[inline(always)] fn from(reader: crate::R<OSCSICTRL_SPEC>) -> Self { R(reader) } } #[doc = "Register `OSCSICTRL` writer"] pub struct W(crate::W<OSCSICTRL_SPEC>); impl core::ops::Deref for W { type Target = crate::W<OSCSICTRL_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { ...
&self.0 } } impl From<crate::R<OSCSICTRL_SPEC>> for R {
random_line_split
pl030.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use base::{warn, Event}; use std::convert::TryFrom; use std::time::{SystemTime, UNIX_EPOCH}; use crate::{BusAccessInfo, BusDevice}; // Register offse...
#[test] fn test_match_register() { let mut device = Pl030::new(Event::new().unwrap()); let mut register = [0, 0, 0, 0]; device.write(pl030_bus_address(RTCMR), &[1, 2, 3, 4]); device.read(pl030_bus_address(RTCMR), &mut register); assert_eq!(register, [1, 2, 3, 4]); ...
{ let event = Event::new().unwrap(); let mut device = Pl030::new(event.try_clone().unwrap()); let mut register = [0, 0, 0, 0]; // set interrupt device.write(pl030_bus_address(RTCEOI), &[1, 0, 0, 0]); device.read(pl030_bus_address(RTCSTAT), &mut register); assert_...
identifier_body
pl030.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use base::{warn, Event}; use std::convert::TryFrom; use std::time::{SystemTime, UNIX_EPOCH}; use crate::{BusAccessInfo, BusDevice}; // Register offse...
pub struct Pl030 { // Event to be used to interrupt the guest for an alarm event alarm_evt: Event, // This is the delta we subtract from current time to get the // counter value counter_delta_time: u32, // This is the value that triggers an alarm interrupt when it // matches with the rtc t...
random_line_split
pl030.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use base::{warn, Event}; use std::convert::TryFrom; use std::time::{SystemTime, UNIX_EPOCH}; use crate::{BusAccessInfo, BusDevice}; // Register offse...
{ // Event to be used to interrupt the guest for an alarm event alarm_evt: Event, // This is the delta we subtract from current time to get the // counter value counter_delta_time: u32, // This is the value that triggers an alarm interrupt when it // matches with the rtc time match_va...
Pl030
identifier_name
pl030.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use base::{warn, Event}; use std::convert::TryFrom; use std::time::{SystemTime, UNIX_EPOCH}; use crate::{BusAccessInfo, BusDevice}; // Register offse...
o => panic!("pl030: bad write {}", o), } } fn read(&mut self, info: BusAccessInfo, data: &mut [u8]) { let data_array = match <&mut [u8; 4]>::try_from(data) { Ok(array) => array, _ => { warn!("bad write size for pl030"); return...
{ self.counter_delta_time = get_epoch_time(); }
conditional_block
test_multicast.rs
use mio::*; use mio::deprecated::{EventLoop, Handler}; use mio::udp::*; use bytes::{Buf, MutBuf, RingBuf, SliceBuf}; use std::str; use std::net::{SocketAddr, Ipv4Addr}; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, ms...
} #[test] pub fn test_multicast() { debug!("Starting TEST_UDP_CONNECTIONLESS"); let mut event_loop = EventLoop::new().unwrap(); let addr = localhost(); let any = "0.0.0.0:0".parse().unwrap(); let tx = UdpSocket::bind(&any).unwrap(); let rx = UdpSocket::bind(&addr).unwrap(); info!("Joini...
{ if events.is_readable() { self.handle_read(event_loop, token, events); } if events.is_writable() { self.handle_write(event_loop, token, events); } }
identifier_body
test_multicast.rs
use mio::*; use mio::deprecated::{EventLoop, Handler}; use mio::udp::*; use bytes::{Buf, MutBuf, RingBuf, SliceBuf}; use std::str; use std::net::{SocketAddr, Ipv4Addr}; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, ms...
fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: Ready) { if events.is_readable() { self.handle_read(event_loop, token, events); } if events.is_writable() { self.handle_write(event_loop, token, events); } } } #[test] pub...
type Message = ();
random_line_split
test_multicast.rs
use mio::*; use mio::deprecated::{EventLoop, Handler}; use mio::udp::*; use bytes::{Buf, MutBuf, RingBuf, SliceBuf}; use std::str; use std::net::{SocketAddr, Ipv4Addr}; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, ms...
} } #[test] pub fn test_multicast() { debug!("Starting TEST_UDP_CONNECTIONLESS"); let mut event_loop = EventLoop::new().unwrap(); let addr = localhost(); let any = "0.0.0.0:0".parse().unwrap(); let tx = UdpSocket::bind(&any).unwrap(); let rx = UdpSocket::bind(&addr).unwrap(); info!(...
{ self.handle_write(event_loop, token, events); }
conditional_block
test_multicast.rs
use mio::*; use mio::deprecated::{EventLoop, Handler}; use mio::udp::*; use bytes::{Buf, MutBuf, RingBuf, SliceBuf}; use std::str; use std::net::{SocketAddr, Ipv4Addr}; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, ms...
() { debug!("Starting TEST_UDP_CONNECTIONLESS"); let mut event_loop = EventLoop::new().unwrap(); let addr = localhost(); let any = "0.0.0.0:0".parse().unwrap(); let tx = UdpSocket::bind(&any).unwrap(); let rx = UdpSocket::bind(&addr).unwrap(); info!("Joining group 227.1.1.100"); let a...
test_multicast
identifier_name
types.rs
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnis...
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang // // Permission is hereby granted, free of charge, to any person obtaining a copy
random_line_split
types.rs
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, c...
{ pub x: f64, pub y: f64 } pub struct NSSize { pub width: f64, pub height: f64 }
NSPoint
identifier_name
plugins.rs
use std::collections::{BTreeMap, HashMap}; use std::string::FromUtf8Error; use svgbob::Render; use thiserror::Error; use url_path::UrlPath; /// Plugin info, format: /// [<selector>] <plugin_name>[@version][://<URI>] /// example: /// #table1 csv://data_file.csv #[allow(dead_code)] pub struct PluginInfo { selector: ...
else { false } } /// handle the embed of the file with the supplied content #[cfg(feature = "file")] pub fn embed_handler( url: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, ) -> Result<String, PluginError> { if let Some(embed_files) = embed_files { let url_path = UrlPath::new...
{ true }
conditional_block
plugins.rs
use std::collections::{BTreeMap, HashMap}; use std::string::FromUtf8Error; use svgbob::Render; use thiserror::Error; use url_path::UrlPath; /// Plugin info, format: /// [<selector>] <plugin_name>[@version][://<URI>] /// example: /// #table1 csv://data_file.csv #[allow(dead_code)] pub struct PluginInfo { selector: ...
buff.push_str(&format!("<th>{}</th>", h)); } buff.push_str("</tr>"); } buff.push_str("</thead>"); buff.push_str("</thead>"); buff.push_str("<tbody>"); for record in rdr.records() { buff.push_str("<tr>"); if let Ok(record) = record { for value i...
for h in header {
random_line_split
plugins.rs
use std::collections::{BTreeMap, HashMap}; use std::string::FromUtf8Error; use svgbob::Render; use thiserror::Error; use url_path::UrlPath; /// Plugin info, format: /// [<selector>] <plugin_name>[@version][://<URI>] /// example: /// #table1 csv://data_file.csv #[allow(dead_code)] pub struct
{ selector: Option<String>, plugin_name: String, version: Option<String>, uri: Option<String>, } #[derive(Error, Debug)] pub enum PluginError { #[error("Embeded file is not supplied")] EmbededFilesNotSupplied, #[error("Embeded file not found: `{0}`")] EmbedFileNotFound(String), #[e...
PluginInfo
identifier_name
eq.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(cx: &mut ExtCtxt, span: Span, mitem: Gc<MetaItem>, item: Gc<Item>, push: |Gc<Item>|) { // structures are equal if all fields are equal, and non equal, if // any fields are not equal or if the enum variants a...
expand_deriving_eq
identifier_name
eq.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
methods: vec!( md!("eq", cs_eq), md!("ne", cs_ne) ) }; trait_def.expand(cx, mitem, item, push) }
attributes: Vec::new(), path: Path::new(vec!("std", "cmp", "PartialEq")), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(),
random_line_split
eq.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
args: vec!(borrowed_self()), ret_ty: Literal(Path::new(vec!("bool"))), attributes: attrs, const_nonmatching: true, combine_substructure: combine_substructure(|a, b, c| { $f(a, b, c) }) } ...
{ // structures are equal if all fields are equal, and non equal, if // any fields are not equal or if the enum variants are different fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> Gc<Expr> { cs_and(|cx, span, _, _| cx.expr_bool(span, false), cx, s...
identifier_body
storage.rs
use api::{Bool, Id}; request_ref! { #[derive(Eq, Copy)] struct Get for ["storage.get"](v => 5.44) -> String { sized { user_id: Id = () => {}, global: bool = () => {bool}, } unsized { key: str = ("") => {=}, keys: str = ("") => {=}, ...
#[derive(Eq, Copy)] struct GetKeys for ["storage.getKeys"](v => 5.44) -> Vec<String> { user_id: Id = () => {}, global: bool = () => {bool}, offset: usize = (0) => {}, count: usize = (100) => {}, } }
random_line_split
regs.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::mem; use su...
} fn read_u64(gm: &GuestMemoryMmap, offset: u64) -> u64 { let read_addr = GuestAddress(offset as u64); gm.read_obj(read_addr).unwrap() } fn validate_segments_and_sregs(gm: &GuestMemoryMmap, sregs: &kvm_sregs) { assert_eq!(0x0, read_u64(&gm, BOOT_GDT_OFFSET)); assert_eq...
{ vm_memory::test_utils::create_guest_memory_unguarded( &[(GuestAddress(0), mem_size)], false, ) .unwrap() }
conditional_block
regs.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::mem; use su...
(gm: &GuestMemoryMmap, sregs: &kvm_sregs) { assert_eq!(0xa003, read_u64(&gm, PML4_START)); assert_eq!(0xb003, read_u64(&gm, PDPTE_START)); for i in 0..512 { assert_eq!((i << 21) + 0x83u64, read_u64(&gm, PDE_START + (i * 8))); } assert_eq!(PML4_START as u64, sregs.cr3...
validate_page_tables
identifier_name
regs.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::mem; use su...
assert!(vcpu.set_sregs(&Default::default()).is_ok()); setup_sregs(&gm, &vcpu).unwrap(); let mut sregs: kvm_sregs = vcpu.get_sregs().unwrap(); // for AMD KVM_GET_SREGS returns g = 0 for each kvm_segment. // We set it to 1, otherwise the test will fail. sregs.gs.g = 1; ...
let kvm = Kvm::new().unwrap(); let vm = kvm.create_vm().unwrap(); let vcpu = vm.create_vcpu(0).unwrap(); let gm = create_guest_mem(None);
random_line_split
regs.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::mem; use su...
/// Configures the segment registers and system page tables for a given CPU. /// /// # Arguments /// /// * `mem` - The memory that will be passed to the guest. /// * `vcpu` - Structure for the VCPU that holds the VCPU's fd. pub fn setup_sregs(mem: &GuestMemoryMmap, vcpu: &VcpuFd) -> Result<()> { let mut sregs: kv...
{ let regs: kvm_regs = kvm_regs { rflags: 0x0000_0000_0000_0002u64, rip: boot_ip, // Frame pointer. It gets a snapshot of the stack pointer (rsp) so that when adjustments are // made to rsp (i.e. reserving space for local variables or pushing values on to the stack), // local...
identifier_body
main.rs
#![deny(warnings)] #![feature(plugin)] #![plugin(regex_macros)] extern crate regex; extern crate term; extern crate binunit; use std::io::prelude::*; fn main() { let binunit = binunit::BinUnit::new(&std::env::current_dir().unwrap()); match binunit.run() { Ok(mut output) => print(&mut ou...
} fn print_result_colorized(output: &String) { let mut term = term::stdout().unwrap(); for capture in regex!(r"(?m)(.*: )(ok|failed)(.*)|.*").captures_iter(output) { match capture.at(2).unwrap_or("") { "ok" => { write!(term, "{}", capture.at(1).unwrap()).unwrap(); ...
{ let summary = output.iter() .fold((0, 0, 0), |a, b| increment_summary(a, b)); output.sort(); println!(""); for item in output.iter().filter(|item| item.contains(": ok")) { print_result_colorized(&item.trim().to_owned()); } println!("\n"); for item in output.iter().fil...
identifier_body
main.rs
#![deny(warnings)] #![feature(plugin)] #![plugin(regex_macros)] extern crate regex; extern crate term; extern crate binunit; use std::io::prelude::*; fn main() { let binunit = binunit::BinUnit::new(&std::env::current_dir().unwrap()); match binunit.run() { Ok(mut output) => print(&mut ou...
(output: &mut Vec<String>) { let summary = output.iter() .fold((0, 0, 0), |a, b| increment_summary(a, b)); output.sort(); println!(""); for item in output.iter().filter(|item| item.contains(": ok")) { print_result_colorized(&item.trim().to_owned()); } println!("\n"); for...
print
identifier_name
main.rs
#![deny(warnings)] #![feature(plugin)] #![plugin(regex_macros)] extern crate regex; extern crate term; extern crate binunit; use std::io::prelude::*; fn main() { let binunit = binunit::BinUnit::new(&std::env::current_dir().unwrap()); match binunit.run() { Ok(mut output) => print(&mut ou...
} fn print_summary(&(_, pass, fail): &(i32, i32, i32)) { let mut term = term::stdout().unwrap(); write!(term, "\n\n\t").unwrap(); match fail { 0 => { term.fg(term::color::BRIGHT_GREEN).unwrap(); write!(term, "ok").unwrap() }, _ => { term.fg(ter...
{ (total, pass, fail) }
conditional_block
main.rs
#![deny(warnings)] #![feature(plugin)] #![plugin(regex_macros)] extern crate regex; extern crate term; extern crate binunit; use std::io::prelude::*; fn main() { let binunit = binunit::BinUnit::new(&std::env::current_dir().unwrap()); match binunit.run() { Ok(mut output) => print(&mut ou...
fn print_result_colorized(output: &String) { let mut term = term::stdout().unwrap(); for capture in regex!(r"(?m)(.*: )(ok|failed)(.*)|.*").captures_iter(output) { match capture.at(2).unwrap_or("") { "ok" => { write!(term, "{}", capture.at(1).unwrap()).unwrap(); ...
}
random_line_split
origin.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use servo_rand; use std::cell::RefCell; use std::rc::Rc; use url::{Host, Origin}; use url_serde; use uuid::Uuid; ...
(&self, other: &MutableOrigin) -> bool { self == other.immutable() } pub fn same_origin_domain(&self, other: &MutableOrigin) -> bool { !other.has_domain() && self == other.immutable() } /// Creates a new opaque origin that is only equal to itself. pub fn new_opaque() -> ImmutableOri...
same_origin
identifier_name
origin.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use servo_rand; use std::cell::RefCell; use std::rc::Rc; use url::{Host, Origin}; use url_serde; use uuid::Uuid; ...
/// <https://html.spec.whatwg.org/multipage/#ascii-serialisation-of-an-origin> pub fn ascii_serialization(&self) -> String { self.clone().into_url_origin().ascii_serialization() } /// <https://html.spec.whatwg.org/multipage/#unicode-serialisation-of-an-origin> pub fn unicode_serialization...
{ match *self { ImmutableOrigin::Opaque(..) => false, ImmutableOrigin::Tuple(..) => true, } }
identifier_body
origin.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use servo_rand; use std::cell::RefCell; use std::rc::Rc; use url::{Host, Origin}; use url_serde; use uuid::Uuid; ...
ImmutableOrigin::Tuple(_, ref host, _) => Some(host), } } pub fn port(&self) -> Option<u16> { match *self { ImmutableOrigin::Opaque(_) => None, ImmutableOrigin::Tuple(_, _, port) => Some(port), } } pub fn into_url_origin(self) -> Origin { ...
} pub fn host(&self) -> Option<&Host> { match *self { ImmutableOrigin::Opaque(_) => None,
random_line_split
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
let n = x.leading_zeros(); mem::size_of::<usize>() as u32 * 8 - n } /// Bloom operations. pub trait Bloomable: Sized + Default + DerefMut<Target = [u8]> { /// When interpreting self as a bloom output, augment (bit-wise OR) with the a bloomed version of `b`. fn shift_bloomed<'a, T>(&'a mut self, b: &T...
{ return 0; }
conditional_block
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
T: Bloomable; /// Check to see whether this hash, interpreted as a bloom, contains the value `b` when bloomed. fn contains_bloomed<T>(&self, b: &T) -> bool where T: Bloomable; } macro_rules! impl_bloomable_for_hash { ($name: ident, $size: expr) => { impl Bloomable for $name { fn shif...
fn bloom_part<T>(&self, m: usize) -> T where
random_line_split
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// Construct new instance equal to the bloomed value of `b`. fn from_bloomed<T>(b: &T) -> Self where T: Bloomable; /// Bloom the current value using the bloom parameter `m`. fn bloom_part<T>(&self, m: usize) -> T where T: Bloomable; /// Check to see whether this hash, in...
{ self.shift_bloomed(b); self }
identifier_body
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
<T>(mut self, b: &T) -> Self where T: Bloomable, { self.shift_bloomed(b); self } /// Construct new instance equal to the bloomed value of `b`. fn from_bloomed<T>(b: &T) -> Self where T: Bloomable; /// Bloom the current value using the bloom parameter `m`. ...
with_bloomed
identifier_name
main.rs
extern crate num; use num::{BigInt, Signed}; // Dumbest iterative approach fn big_pow(base: &BigInt, exp: BigInt) -> BigInt
// 5^4^3^2 fn main() { // Exponent is small enough to not use BigInt let exp = BigInt::from(num::pow(4, num::pow(3, 2))); let result = big_pow(&BigInt::from(5), exp).to_string(); let num_length = result.len(); println!("{}", result); println!("Number has {} digits.", num_length); assert!...
{ if exp.is_negative() { panic!("Negative exponent won't compute!") } let mut tmp = base.clone(); for _ in num::range(BigInt::from(1), exp) { tmp *= base; } tmp }
identifier_body
main.rs
extern crate num; use num::{BigInt, Signed}; // Dumbest iterative approach fn big_pow(base: &BigInt, exp: BigInt) -> BigInt { if exp.is_negative()
let mut tmp = base.clone(); for _ in num::range(BigInt::from(1), exp) { tmp *= base; } tmp } // 5^4^3^2 fn main() { // Exponent is small enough to not use BigInt let exp = BigInt::from(num::pow(4, num::pow(3, 2))); let result = big_pow(&BigInt::from(5), exp).to_string(); let n...
{ panic!("Negative exponent won't compute!") }
conditional_block
main.rs
extern crate num; use num::{BigInt, Signed}; // Dumbest iterative approach fn big_pow(base: &BigInt, exp: BigInt) -> BigInt { if exp.is_negative() { panic!("Negative exponent won't compute!") } let mut tmp = base.clone(); for _ in num::range(BigInt::from(1), exp) { tmp *= base; } ...
() { assert_eq!( big_pow(&BigInt::from(100), BigInt::from(100)).to_string(), "10000000000000000000000000000000000000000000000000000000000000\ 000000000000000000000000000000000000000000000000000000000000000\ 0000000000000000000000000000000000000000000000000000000...
big_powas
identifier_name
main.rs
extern crate num; use num::{BigInt, Signed}; // Dumbest iterative approach fn big_pow(base: &BigInt, exp: BigInt) -> BigInt { if exp.is_negative() { panic!("Negative exponent won't compute!") } let mut tmp = base.clone(); for _ in num::range(BigInt::from(1), exp) { tmp *= base; } ...
#[test] fn big_powas() { assert_eq!( big_pow(&BigInt::from(100), BigInt::from(100)).to_string(), "10000000000000000000000000000000000000000000000000000000000000\ 000000000000000000000000000000000000000000000000000000000000000\ 00000000000000000000000000...
let exp = BigInt::from(-100); big_pow(&num, exp); }
random_line_split
domexception.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DOMExceptionBinding; use dom::bindings::codegen::Bindings::DOMExceptionBindi...
(code: DOMErrorName) -> DOMException { DOMException { reflector_: Reflector::new(), code: code, } } pub fn new(global: GlobalRef, code: DOMErrorName) -> Root<DOMException> { reflect_dom_object(box DOMException::new_inherited(code), global, DOMExceptionBinding::Wr...
new_inherited
identifier_name
domexception.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DOMExceptionBinding; use dom::bindings::codegen::Bindings::DOMExceptionBindi...
// https://heycam.github.io/webidl/#idl-DOMException-error-names fn Name(&self) -> DOMString { DOMString(format!("{:?}", self.code)) } // https://heycam.github.io/webidl/#error-names fn Message(&self) -> DOMString { let message = match self.code { DOMErrorName::IndexSi...
{ match self.code { // https://heycam.github.io/webidl/#dfn-throw DOMErrorName::EncodingError => 0, code => code as u16 } }
identifier_body
domexception.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DOMExceptionBinding; use dom::bindings::codegen::Bindings::DOMExceptionBindi...
URLMismatchError = DOMExceptionConstants::URL_MISMATCH_ERR, TypeMismatchError = DOMExceptionConstants::TYPE_MISMATCH_ERR, QuotaExceededError = DOMExceptionConstants::QUOTA_EXCEEDED_ERR, TimeoutError = DOMExceptionConstants::TIMEOUT_ERR, InvalidNodeTypeError = DOMExceptionConstants::INVALID_NODE_TYPE...
SecurityError = DOMExceptionConstants::SECURITY_ERR, NetworkError = DOMExceptionConstants::NETWORK_ERR, AbortError = DOMExceptionConstants::ABORT_ERR,
random_line_split
minimal_versions.rs
//! Tests for minimal-version resolution. //! //! Note: Some tests are located in the resolver-tests package. use cargo_test_support::project; use cargo_test_support::registry::Package; // Ensure that the "-Z minimal-versions" CLI option works and the minimal // version of a dependency ends up in the lock file. #[car...
() { Package::new("dep", "1.0.0").publish(); Package::new("dep", "1.1.0").publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" authors = [] version = "0.0.1" [dependencies...
minimal_version_cli
identifier_name
minimal_versions.rs
//! Tests for minimal-version resolution. //! //! Note: Some tests are located in the resolver-tests package. use cargo_test_support::project; use cargo_test_support::registry::Package; // Ensure that the "-Z minimal-versions" CLI option works and the minimal // version of a dependency ends up in the lock file. #[car...
.masquerade_as_nightly_cargo() .run(); let lock = p.read_lockfile(); assert!(!lock.contains("1.1.0")); }
.build(); p.cargo("generate-lockfile -Zminimal-versions")
random_line_split
minimal_versions.rs
//! Tests for minimal-version resolution. //! //! Note: Some tests are located in the resolver-tests package. use cargo_test_support::project; use cargo_test_support::registry::Package; // Ensure that the "-Z minimal-versions" CLI option works and the minimal // version of a dependency ends up in the lock file. #[car...
p.cargo("generate-lockfile -Zminimal-versions") .masquerade_as_nightly_cargo() .run(); let lock = p.read_lockfile(); assert!(!lock.contains("1.1.0")); }
{ Package::new("dep", "1.0.0").publish(); Package::new("dep", "1.1.0").publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" authors = [] version = "0.0.1" [dependencies] ...
identifier_body
mouse.rs
use std::rc::Rc; use nalgebra::{Vector2}; use ncollide_geometry::shape::{Cuboid, ShapeHandle2}; use glium::glutin::MouseButton; use game::object::Object; use engine::Engine; use engine::entity::component::*; use engine::event::{Event, InputState}; pub struct Mouse { world: WorldComp<Object>, ev: EventComp<Obj...
(&mut self, e: Rc<Event>) { match *e { Event::Spawn => { println!("Mouse spawned!"); self.ev.subscribe(Event::MouseMove((0.0, 0.0))); self.ev.subscribe(Event::MouseInput(InputState::Released, MouseButton::Left)); } Event::MouseM...
handle_event
identifier_name
mouse.rs
use std::rc::Rc; use nalgebra::{Vector2}; use ncollide_geometry::shape::{Cuboid, ShapeHandle2}; use glium::glutin::MouseButton; use game::object::Object; use engine::Engine; use engine::entity::component::*; use engine::event::{Event, InputState}; pub struct Mouse { world: WorldComp<Object>,
impl Mouse { pub fn new(engine: &Engine<Object>) -> Object { let w = WorldCompBuilder::new(engine).build(); let e = EventComp::new(w.id, engine.events.clone()); let p = PhysicsComp::new(w.id, 0, Vector2::new(0.0, 0.0), ...
ev: EventComp<Object>, phys: PhysicsComp, pos: (f32, f32), }
random_line_split
mouse.rs
use std::rc::Rc; use nalgebra::{Vector2}; use ncollide_geometry::shape::{Cuboid, ShapeHandle2}; use glium::glutin::MouseButton; use game::object::Object; use engine::Engine; use engine::entity::component::*; use engine::event::{Event, InputState}; pub struct Mouse { world: WorldComp<Object>, ev: EventComp<Obj...
}
{ self.world.id }
identifier_body
mouse.rs
use std::rc::Rc; use nalgebra::{Vector2}; use ncollide_geometry::shape::{Cuboid, ShapeHandle2}; use glium::glutin::MouseButton; use game::object::Object; use engine::Engine; use engine::entity::component::*; use engine::event::{Event, InputState}; pub struct Mouse { world: WorldComp<Object>, ev: EventComp<Obj...
}; } pub fn id(&self) -> usize { self.world.id } }
{}
conditional_block
main.rs
extern crate byteorder; extern crate elf; use std::path::PathBuf; use std::fs::{File, OpenOptions}; use std::io::*; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::process::Command; static BOOT_FILE_BLOCK_SIZE :u32 = 512; static BOOT_FILE_HEADER_LENGTH :u32 = 20; macro_rules! try_IO { ($file_...
() { let linker_path = match std::env::var("LD") { Ok(value) => value, Err(_) => { println!("Could not find linker"); return; }, }; let args: Vec<_> = std::env::args().collect(); if args.len() < 5 { println!("Usage: LD = [linker] build_tool [virtua...
main
identifier_name
main.rs
extern crate byteorder; extern crate elf; use std::path::PathBuf; use std::fs::{File, OpenOptions}; use std::io::*; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::process::Command; static BOOT_FILE_BLOCK_SIZE :u32 = 512; static BOOT_FILE_HEADER_LENGTH :u32 = 20; macro_rules! try_IO { ($file_...
, elf::types::Class(_) => { println!("{:?} is of unknown architecture size", in_file_path); return; }, }; } let binary_file_path = PathBuf::from(target); let mut binary_file = try_IO!(binary_file_path, OpenOptions::new().read(true).write(true)...
{ if in_file.ehdr.machine != elf::types::EM_AARCH64 { println!("{:?} is of wrong machine architecture", in_file_path); return; } object_files[1].push(in_file_path); }
conditional_block
main.rs
extern crate byteorder; extern crate elf; use std::path::PathBuf; use std::fs::{File, OpenOptions}; use std::io::*; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::process::Command; static BOOT_FILE_BLOCK_SIZE :u32 = 512; static BOOT_FILE_HEADER_LENGTH :u32 = 20; macro_rules! try_IO { ($file_...
if needs_trailing_zeros { try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset+payload_length as u64-1))); try_IO!(binary_file_path, binary_file.write(&[0u8])); } try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset))); for _ in 0..payload_len...
(&mut boot_file_header[16..20]).write_u32::<LittleEndian>(payload_length).unwrap(); try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset))); try_IO!(binary_file_path, binary_file.write(&boot_file_header));
random_line_split
main.rs
extern crate byteorder; extern crate elf; use std::path::PathBuf; use std::fs::{File, OpenOptions}; use std::io::*; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::process::Command; static BOOT_FILE_BLOCK_SIZE :u32 = 512; static BOOT_FILE_HEADER_LENGTH :u32 = 20; macro_rules! try_IO { ($file_...
} let mut object_files :[Vec<PathBuf>; 2] = [Vec::new(), Vec::new()]; for in_file_path_str in &args[4..] { let in_file_path = PathBuf::from(in_file_path_str); let in_file = try_IO!(in_file_path, elf::File::open_path(&in_file_path)); if in_file.ehdr.osabi!= elf::types::ELFOSABI_NONE...
{ let linker_path = match std::env::var("LD") { Ok(value) => value, Err(_) => { println!("Could not find linker"); return; }, }; let args: Vec<_> = std::env::args().collect(); if args.len() < 5 { println!("Usage: LD = [linker] build_tool [virtual_o...
identifier_body
args.rs
//! The Windows command line is just a string //! <https://docs.microsoft.com/en-us/archive/blogs/larryosterman/the-windows-command-line-is-just-a-string> //! //! This module implements the parsing necessary to turn that string into a list of arguments. #[cfg(test)] mod tests; use crate::ffi::OsString; use crate::fmt...
(lpwstr: *const u16) -> Option<Self> { Some(Self { lpwstr: NonNull::new(lpwstr as _)?, lifetime: PhantomData }) } fn peek(&self) -> Option<NonZeroU16> { // SAFETY: It's always safe to read the current item because we don't // ever move out of the array's bounds. unsafe { NonZeroU...
new
identifier_name
args.rs
//! The Windows command line is just a string //! <https://docs.microsoft.com/en-us/archive/blogs/larryosterman/the-windows-command-line-is-just-a-string> //! //! This module implements the parsing necessary to turn that string into a list of arguments. #[cfg(test)] mod tests; use crate::ffi::OsString; use crate::fmt...
// A quote mark always toggles `in_quotes` no matter what because // there are no escape characters when parsing the executable name. QUOTE => in_quotes =!in_quotes, // If not `in_quotes` then whitespace ends argv[0]. SPACE | TAB if!in_quotes => break, ...
{ const BACKSLASH: NonZeroU16 = NonZeroU16::new(b'\\' as u16).unwrap(); const QUOTE: NonZeroU16 = NonZeroU16::new(b'"' as u16).unwrap(); const TAB: NonZeroU16 = NonZeroU16::new(b'\t' as u16).unwrap(); const SPACE: NonZeroU16 = NonZeroU16::new(b' ' as u16).unwrap(); let mut ret_val = Vec::new(); ...
identifier_body
args.rs
//! The Windows command line is just a string //! <https://docs.microsoft.com/en-us/archive/blogs/larryosterman/the-windows-command-line-is-just-a-string> //! //! This module implements the parsing necessary to turn that string into a list of arguments. #[cfg(test)] mod tests; use crate::ffi::OsString; use crate::fmt...
}, // If not `in_quotes` and not BACKSLASH escaped (see above) then a quote sets `in_quote`. QUOTE => in_quotes = true, // Everything else is always taken literally. _ => cur.push(w.get()), } } // Push the final argument, if any. if!cur.is_...
Some(_) => in_quotes = false, // The end of the command line. // Push `cur` even if empty, which we do by breaking while `in_quotes` is still set. None => break,
random_line_split
ifchanged_block.rs
use std::io::Write; use liquid_core::error::{ResultLiquidExt, ResultLiquidReplaceExt}; use liquid_core::Language; use liquid_core::Renderable; use liquid_core::Result; use liquid_core::Runtime; use liquid_core::Template; use liquid_core::{BlockReflection, ParseBlock, TagBlock, TagTokenIter}; #[derive(Copy, Clone, Deb...
} impl BlockReflection for IfChangedBlock { fn start_tag(&self) -> &str { "ifchanged" } fn end_tag(&self) -> &str { "endifchanged" } fn description(&self) -> &str { "" } } impl ParseBlock for IfChangedBlock { fn parse( &self, mut arguments: TagTok...
{ Self::default() }
identifier_body
ifchanged_block.rs
use std::io::Write; use liquid_core::error::{ResultLiquidExt, ResultLiquidReplaceExt}; use liquid_core::Language; use liquid_core::Renderable; use liquid_core::Result; use liquid_core::Runtime; use liquid_core::Template; use liquid_core::{BlockReflection, ParseBlock, TagBlock, TagTokenIter}; #[derive(Copy, Clone, Deb...
let has_changed = if let Some(last_rendered) = &self.last_rendered { last_rendered!= rendered } else { true }; self.last_rendered = Some(rendered.to_owned()); has_changed } } #[cfg(test)] mod test { use super::*; use liquid_core::parser; ...
impl ChangedRegister { /// Checks whether or not a new rendered `&str` is different from /// `last_rendered` and updates `last_rendered` value to the new value. fn has_changed(&mut self, rendered: &str) -> bool {
random_line_split
ifchanged_block.rs
use std::io::Write; use liquid_core::error::{ResultLiquidExt, ResultLiquidReplaceExt}; use liquid_core::Language; use liquid_core::Renderable; use liquid_core::Result; use liquid_core::Runtime; use liquid_core::Template; use liquid_core::{BlockReflection, ParseBlock, TagBlock, TagTokenIter}; #[derive(Copy, Clone, Deb...
() -> Language { let mut options = Language::default(); options .blocks .register("ifchanged".to_string(), IfChangedBlock.into()); options .blocks .register("for".to_string(), stdlib::ForBlock.into()); options .blocks .reg...
options
identifier_name
ifchanged_block.rs
use std::io::Write; use liquid_core::error::{ResultLiquidExt, ResultLiquidReplaceExt}; use liquid_core::Language; use liquid_core::Renderable; use liquid_core::Result; use liquid_core::Runtime; use liquid_core::Template; use liquid_core::{BlockReflection, ParseBlock, TagBlock, TagTokenIter}; #[derive(Copy, Clone, Deb...
; self.last_rendered = Some(rendered.to_owned()); has_changed } } #[cfg(test)] mod test { use super::*; use liquid_core::parser; use liquid_core::runtime; use liquid_core::runtime::RuntimeBuilder; use crate::stdlib; fn options() -> Language { let mut options = La...
{ true }
conditional_block
attr.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::AttrInfo; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBind...
#[inline] unsafe fn value_ref_forever(&self) -> &'static str { &**self.value_forever() } #[inline] unsafe fn value_atom_forever(&self) -> Option<Atom> { let value = (*self.unsafe_get()).value.borrow_for_layout(); match *value { AttrValue::Atom(ref val) => Some(va...
random_line_split
attr.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::AttrInfo; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBind...
// https://dom.spec.whatwg.org/#dom-attr-nodename fn NodeName(&self) -> DOMString { self.Name() } // https://dom.spec.whatwg.org/#dom-attr-namespaceuri fn GetNamespaceURI(&self) -> Option<DOMString> { match self.identifier.namespace { ns!() => None, ref url...
{ // FIXME(ajeffrey): convert directly from LocalName to DOMString DOMString::from(&*self.identifier.name) }
identifier_body
attr.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::AttrInfo; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBind...
(&self) -> &AttrIdentifier { &self.identifier } pub fn value(&self) -> Ref<AttrValue> { self.value.borrow() } pub fn local_name(&self) -> &LocalName { &self.identifier.local_name } /// Sets the owner element. Should be called after the attribute is added /// or rem...
identifier
identifier_name
p114.rs
//! [Problem 114](https://projecteuler.net/problem=114) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(range_inclusive)] #[macro_use(problem)] extern crate common; use std::iter; use std::collections::HashMap; fn get...
} } sum += 1; // all black block let _ = map.insert((n, m), sum); sum } fn solve() -> String { let mut map = HashMap::new(); get_cnt((50, 3), &mut map).to_string() } problem!("16475640049", solve); #[cfg(test)] mod tests { use std::collections::HashMap; use super::get_cnt; ...
{ sum += 1; }
conditional_block
p114.rs
//! [Problem 114](https://projecteuler.net/problem=114) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(range_inclusive)] #[macro_use(problem)] extern crate common; use std::iter; use std::collections::HashMap; fn get...
() -> String { let mut map = HashMap::new(); get_cnt((50, 3), &mut map).to_string() } problem!("16475640049", solve); #[cfg(test)] mod tests { use std::collections::HashMap; use super::get_cnt; #[test] fn small_len() { let mut map = HashMap::new(); assert_eq!(1, get_cnt((1, 3)...
solve
identifier_name
p114.rs
//! [Problem 114](https://projecteuler.net/problem=114) solver.
unused_qualifications, unused_results)] #![feature(range_inclusive)] #[macro_use(problem)] extern crate common; use std::iter; use std::collections::HashMap; fn get_cnt((n, m): (u32, u32), map: &mut HashMap<(u32, u32), u64>) -> u64 { if let Some(&x) = map.get(&(n, m)) { return x } if n ...
#![warn(bad_style, unused, unused_extern_crates, unused_import_braces,
random_line_split
p114.rs
//! [Problem 114](https://projecteuler.net/problem=114) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(range_inclusive)] #[macro_use(problem)] extern crate common; use std::iter; use std::collections::HashMap; fn get...
problem!("16475640049", solve); #[cfg(test)] mod tests { use std::collections::HashMap; use super::get_cnt; #[test] fn small_len() { let mut map = HashMap::new(); assert_eq!(1, get_cnt((1, 3), &mut map)); assert_eq!(1, get_cnt((2, 3), &mut map)); assert_eq!(2, get_cnt...
{ let mut map = HashMap::new(); get_cnt((50, 3), &mut map).to_string() }
identifier_body
tweeter.rs
use futures::prelude::*; use irc::client::prelude::*; use std::time::Duration; // NOTE: you can find an asynchronous version of this example with `IrcReactor` in `tooter.rs`. #[tokio::main] async fn
() -> irc::error::Result<()> { let config = Config { nickname: Some("pickles".to_owned()), server: Some("irc.mozilla.org".to_owned()), channels: vec!["#rust-spam".to_owned()], ..Default::default() }; let mut client = Client::from_config(config).await?; client.identify()?;...
main
identifier_name
tweeter.rs
use futures::prelude::*; use irc::client::prelude::*; use std::time::Duration; // NOTE: you can find an asynchronous version of this example with `IrcReactor` in `tooter.rs`. #[tokio::main] async fn main() -> irc::error::Result<()> {
}; let mut client = Client::from_config(config).await?; client.identify()?; let mut stream = client.stream()?; let mut interval = tokio::time::interval(Duration::from_secs(10)).fuse(); loop { futures::select! { m = stream.select_next_some() => { println!("{...
let config = Config { nickname: Some("pickles".to_owned()), server: Some("irc.mozilla.org".to_owned()), channels: vec!["#rust-spam".to_owned()], ..Default::default()
random_line_split
tweeter.rs
use futures::prelude::*; use irc::client::prelude::*; use std::time::Duration; // NOTE: you can find an asynchronous version of this example with `IrcReactor` in `tooter.rs`. #[tokio::main] async fn main() -> irc::error::Result<()>
client.send_privmsg("#rust-spam", "TWEET TWEET")?; } } } }
{ let config = Config { nickname: Some("pickles".to_owned()), server: Some("irc.mozilla.org".to_owned()), channels: vec!["#rust-spam".to_owned()], ..Default::default() }; let mut client = Client::from_config(config).await?; client.identify()?; let mut stream = clien...
identifier_body
main.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicab...
Err(e) => { use std::io::{stderr, Write}; writeln!(&mut stderr(), "{}", e).unwrap(); std::process::exit(1); } } }
{}
conditional_block
main.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicab...
matches .value_of("loglevel") .map(|s| fractaldata::parse_arg::<log::LevelFilter>("loglevel", s)) .unwrap() .unwrap(), ) .with_module_level("gfx_device_gl", log::LevelFilter::Warn) .init() .unwrap(); let result = f...
{ // Command line arguments specification let mut app = clap::App::new("fractal") .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about("Renders fractals in another window."); app = fractaldata::add_subcommands(app); app = app.arg( clap::Arg::with...
identifier_body
main.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub mod fractaldata; pub mod pistonrendering; pub mod work_multiplexer; fn main() { // Command line arguments specification let m...
// Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
main.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicab...
() { // Command line arguments specification let mut app = clap::App::new("fractal") .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about("Renders fractals in another window."); app = fractaldata::add_subcommands(app); app = app.arg( clap::Arg::with...
main
identifier_name
store.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
hidden: Option<NaiveDateTime>, due: Option<NaiveDateTime>, prio: Option<Priority>, check_sanity: bool) -> Result<FileLockEntry<'a>>; fn get_todo_by_uuid(&'a self, uuid: &Uuid) -> Result<Option<FileLockEntry<'a>>>; fn get_todos(&self) ...
scheduled: Option<NaiveDateTime>,
random_line_split
store.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
/// Create a new todo entry /// /// # Warning /// /// If check_sanity is set to false, this does not sanity-check the scheduled/hidden/due dates. /// This might result in unintended behaviour (hidden after due date, scheduled before hidden /// date... etc) /// /// An user of this f...
{ TodoBuilder::new() }
identifier_body
store.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
} if let (Some(sched), Some(due)) = (scheduled.as_ref(), due.as_ref()) { if sched > due { return Err(format!("Scheduled date after due date: {s}, {d}", s = sched, d = due)) } } Ok(()) }
{ return Err(format!("Hidden date after due date: {h}, {d}", h = hid, d = due)) }
conditional_block
store.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
(&'a self, status: Status, scheduled: Option<NaiveDateTime>, hidden: Option<NaiveDateTime>, due: Option<NaiveDateTime>, prio: Option<Priority>, check_sanity: bool) -> Result<FileLockEntry<'a>> { ...
create_todo
identifier_name
finally.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} #[test] fn test_owned() { fn spawn_with_finalizer(f: ~fn()) { do spawn { do f.finally { } } } let owned: ~fn() = || { }; spawn_with_finalizer(owned); }
fn do_some_fallible_work() {} fn but_always_run_this_function() { } do_some_fallible_work.finally( but_always_run_this_function);
random_line_split
finally.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, dtor: &fn()) -> T { let _d = Finallyalizer { dtor: dtor }; (*self)() } } finally_fn!(~fn() -> T) finally_fn!(extern "Rust" fn() -> T) struct Finallyalizer<'self> { dtor: &'self fn() } #[unsafe_destructor] impl<'self> Drop for Finallyalizer<'self> { fn drop(&mu...
finally
identifier_name
finally.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[test] fn test_retval() { let closure: &fn() -> int = || 10; let i = do closure.finally { }; assert_eq!(i, 10); } #[test] fn test_compact() { fn do_some_fallible_work() {} fn but_always_run_this_function() { } do_some_fallible_work.finally( but_always_run_this_function); } #[test] f...
{ let mut i = 0; do (|| { i = 10; fail2!(); }).finally { assert!(failing()); assert_eq!(i, 10); } }
identifier_body
mod.rs
extern crate udt; pub mod crypto; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use core::ops::DerefMut; use std::fmt; use std::io::Cursor; use std::net::{UdpSocket, SocketAddr, IpAddr}; use std::str; use std::sync::{Arc, Mutex}; use udt::{UdtSocket, UdtError, UdtOpts, SocketType, SocketFamily}; // TOD...
} } fn recv(sock: &UdtSocket, crypto: &mut crypto::Handler, buf: &mut [u8]) -> Result<usize, UdtError> { let mut len_buf = vec![0u8; 4]; try!(sock.recv_exact(&mut len_buf, 4)); // u32 let mut rdr = Cursor::new(len_buf); let len = rdr.read_u32::<LittleEndian>().unwrap() as usize; try!(sock.recv...
err_code: -1, err_msg: "encryption failure".into(), })
random_line_split
mod.rs
extern crate udt; pub mod crypto; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use core::ops::DerefMut; use std::fmt; use std::io::Cursor; use std::net::{UdpSocket, SocketAddr, IpAddr}; use std::str; use std::sync::{Arc, Mutex}; use udt::{UdtSocket, UdtError, UdtOpts, SocketType, SocketFamily}; // TOD...
pub fn new(ip_addr: IpAddr, port: u16, key: &[u8]) -> Server { let sock = new_udt_socket(); sock.bind(SocketAddr::new(ip_addr, port)).unwrap(); Server { sock: sock, ip_addr: ip_addr, port: port, crypto: Arc::new(Mutex::new(crypto::Handler::ne...
{ for p in range.start..range.end { if let Ok(_) = UdpSocket::bind(&format!("0.0.0.0:{}", p)[..]) { return Ok(p); } } Err(()) }
identifier_body
mod.rs
extern crate udt; pub mod crypto; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use core::ops::DerefMut; use std::fmt; use std::io::Cursor; use std::net::{UdpSocket, SocketAddr, IpAddr}; use std::str; use std::sync::{Arc, Mutex}; use udt::{UdtSocket, UdtError, UdtOpts, SocketType, SocketFamily}; // TOD...
} Err(()) } pub fn new(ip_addr: IpAddr, port: u16, key: &[u8]) -> Server { let sock = new_udt_socket(); sock.bind(SocketAddr::new(ip_addr, port)).unwrap(); Server { sock: sock, ip_addr: ip_addr, port: port, crypto: Arc::ne...
{ return Ok(p); }
conditional_block
mod.rs
extern crate udt; pub mod crypto; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use core::ops::DerefMut; use std::fmt; use std::io::Cursor; use std::net::{UdpSocket, SocketAddr, IpAddr}; use std::str; use std::sync::{Arc, Mutex}; use udt::{UdtSocket, UdtError, UdtOpts, SocketType, SocketFamily}; // TOD...
(sock: &UdtSocket, crypto: &mut crypto::Handler, buf: &mut [u8]) -> Result<usize, UdtError> { let mut len_buf = vec![0u8; 4]; try!(sock.recv_exact(&mut len_buf, 4)); // u32 let mut rdr = Cursor::new(len_buf); let len = rdr.read_u32::<LittleEndian>().unwrap() as usize; try!(sock.recv_exact(buf, len)...
recv
identifier_name
load_distr_uniform.rs
extern crate rand; use self::rand::distributions::{IndependentSample, Range}; #[derive(Clone, Debug)] pub struct LoadDistrUniform < T > { _buf: Vec< T >, } impl < T > Default for LoadDistrUniform < T > { fn default() -> Self
} impl < T > LoadDistrUniform < T > { pub fn load( & mut self, t: T ) -> Result< (), &'static str > { self._buf.push( t ); Ok( () ) } pub fn apply< F >( & mut self, mut f: F ) -> Result< (), &'static str > where F: FnMut( & T ) -> bool { if self._buf.len() > 0 { ...
{ Self { _buf: vec![], } }
identifier_body
load_distr_uniform.rs
extern crate rand; use self::rand::distributions::{IndependentSample, Range};
pub struct LoadDistrUniform < T > { _buf: Vec< T >, } impl < T > Default for LoadDistrUniform < T > { fn default() -> Self { Self { _buf: vec![], } } } impl < T > LoadDistrUniform < T > { pub fn load( & mut self, t: T ) -> Result< (), &'static str > { self._buf.pus...
#[derive(Clone, Debug)]
random_line_split