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
bit.rs
use std::fmt; #[derive(Clone, Copy, PartialEq)] pub(crate) struct Pack { mask: usize, shift: u32, } impl Pack { /// Value is packed in the `width` least-significant bits. pub(crate) const fn least_significant(width: u32) -> Pack
/// Value is packed in the `width` more-significant bits. pub(crate) const fn then(&self, width: u32) -> Pack { let shift = pointer_width() - self.mask.leading_zeros(); let mask = mask_for(width) << shift; Pack { mask, shift } } /// Width, in bits, dedicated to storing the va...
{ let mask = mask_for(width); Pack { mask, shift: 0 } }
identifier_body
bit.rs
use std::fmt; #[derive(Clone, Copy, PartialEq)] pub(crate) struct Pack { mask: usize, shift: u32, } impl Pack { /// Value is packed in the `width` least-significant bits. pub(crate) const fn least_significant(width: u32) -> Pack { let mask = mask_for(width); Pack { mask, shift: 0 } ...
/// Unpacks a value using a mask & shift. pub(crate) const fn unpack(src: usize, mask: usize, shift: u32) -> usize { (src & mask) >> shift }
pub(crate) const fn mask_for(n: u32) -> usize { let shift = 1usize.wrapping_shl(n - 1); shift | (shift - 1) }
random_line_split
bit.rs
use std::fmt; #[derive(Clone, Copy, PartialEq)] pub(crate) struct Pack { mask: usize, shift: u32, } impl Pack { /// Value is packed in the `width` least-significant bits. pub(crate) const fn least_significant(width: u32) -> Pack { let mask = mask_for(width); Pack { mask, shift: 0 } ...
(&self, value: usize, base: usize) -> usize { self.pack(value & self.max_value(), base) } pub(crate) fn unpack(&self, src: usize) -> usize { unpack(src, self.mask, self.shift) } } impl fmt::Debug for Pack { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!( ...
pack_lossy
identifier_name
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum CliError { CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkd...
{ let mut args = vec!["+nightly".as_ref(), path.as_os_str()]; if context.check { args.push("--check".as_ref()); } let success = exec(context, "rustfmt", std::env::current_dir()?, &args)?; if !success { eprintln!("rustfmt failed on {}", path.display()); } Ok(success) }
identifier_body
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum CliError { CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkd...
let context = FmtContext { check, verbose }; let result = try_run(&context); let code = match result { Ok(true) => 0, Ok(false) => { eprintln!(); eprintln!("Formatting check failed."); eprintln!("Run `cargo dev fmt` to update formatting."); 1 ...
}
random_line_split
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum
{ CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkdir::Error), RaSetupActive, } impl From<io::Error> for CliError { fn from(error: io::Error) -> Self { Self::IoError(error) } } impl From<walkdir::Error> for CliError { fn from(error: wal...
CliError
identifier_name
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum CliError { CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkd...
Ok(success) }
{ eprintln!("rustfmt failed on {}", path.display()); }
conditional_block
scgi.rs
extern crate collections; use std::io::{BufferedReader, TcpListener, Listener, Acceptor}; use std::io::net::ip::{SocketAddr}; use std::from_str::{from_str}; use std::to_str::{ToStr}; use std::str::from_utf8; use collections::hashmap::HashMap; pub type Headers = HashMap<~str, ~str>; pub type SCGIMessage = (Headers, ~[...
reader.read_until(58).map(|b| from_str::<uint>(from_utf8(b.init()).expect("Unable to parse headers' length")).expect("Unable to parse headers' length")).unwrap(); let mut headers_read = 0; let mut headers = HashMap::new(); loop { i...
// XXX: ohgodwhat let headers_length =
random_line_split
scgi.rs
extern crate collections; use std::io::{BufferedReader, TcpListener, Listener, Acceptor}; use std::io::net::ip::{SocketAddr}; use std::from_str::{from_str}; use std::to_str::{ToStr}; use std::str::from_utf8; use collections::hashmap::HashMap; pub type Headers = HashMap<~str, ~str>; pub type SCGIMessage = (Headers, ~[...
(addr: SocketAddr, handler: Sender<(Headers, ~[u8], Sender<SCGIMessage>)>) -> SCGIServer { SCGIServer { listen_address: addr, handler: handler } } pub fn start(&self) { let mut listener = match TcpListener::bind(self.listen_address) { Ok(listener) =>...
new
identifier_name
issue-573-layout-test-failures.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Outer { pub i: u8, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct AutoIdVector { pub ar: Outer, } #[test] fn bindgen_test_layout_Auto...
stringify!(ar) ) ); } #[test] fn __bindgen_test_layout_Outer_open0_int_close0_instantiation() { assert_eq!( ::std::mem::size_of::<Outer>(), 1usize, concat!("Size of template specialization: ", stringify!(Outer)) ); assert_eq!( ::std::mem::align_of::<O...
{ assert_eq!( ::std::mem::size_of::<AutoIdVector>(), 1usize, concat!("Size of: ", stringify!(AutoIdVector)) ); assert_eq!( ::std::mem::align_of::<AutoIdVector>(), 1usize, concat!("Alignment of ", stringify!(AutoIdVector)) ); assert_eq!( unsafe ...
identifier_body
issue-573-layout-test-failures.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Outer { pub i: u8, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct AutoIdVector { pub ar: Outer, } #[test] fn bindgen_test_layout_Auto...
assert_eq!( ::std::mem::align_of::<AutoIdVector>(), 1usize, concat!("Alignment of ", stringify!(AutoIdVector)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<AutoIdVector>())).ar as *const _ as usize }, 0usize, concat!( "Offset ...
1usize, concat!("Size of: ", stringify!(AutoIdVector)) );
random_line_split
issue-573-layout-test-failures.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Outer { pub i: u8, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct
{ pub ar: Outer, } #[test] fn bindgen_test_layout_AutoIdVector() { assert_eq!( ::std::mem::size_of::<AutoIdVector>(), 1usize, concat!("Size of: ", stringify!(AutoIdVector)) ); assert_eq!( ::std::mem::align_of::<AutoIdVector>(), 1usize, concat!("Alignment ...
AutoIdVector
identifier_name
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use digest::{Digest, FixedOutput}; use sha2::Sha256; use std::error::Error; use std::fmt; use std::io::{self, Write}; use hex; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Cop...
0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, ]), Fingerprint([0xab; 32]) ); } #[test] fn from_hex_string() { assert_eq!( Fingerprint::from_hex_string( "0123456789abcdefFEDCBA98765432100000000000000000ffFFfFfFFfFfFFff", )...
0xab,
random_line_split
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use digest::{Digest, FixedOutput}; use sha2::Sha256; use std::error::Error; use std::fmt; use std::io::{self, Write}; use hex; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Cop...
() { assert_eq!( Fingerprint::from_bytes_unsafe(&vec![ 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, ...
from_bytes_unsafe
identifier_name
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use digest::{Digest, FixedOutput}; use sha2::Sha256; use std::error::Error; use std::fmt; use std::io::{self, Write}; use hex; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Cop...
let mut fingerprint = [0; FINGERPRINT_SIZE]; fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]); Fingerprint(fingerprint) } pub fn from_hex_string(hex_string: &str) -> Result<Fingerprint, String> { <[u8; FINGERPRINT_SIZE] as hex::FromHex>::from_hex(hex_string) .map(|v| Fingerprint(v))...
{ panic!( "Input value was not a fingerprint; had length: {}", bytes.len() ); }
conditional_block
browsingcontext.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::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; use js::glue::{GetProxyPrivate, SetProxyExtr...
use dom::bindings::cell::DOMRefCell; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject}; use dom::bindings::js::{JS, Root, RootedReference}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, Reflector};
random_line_split
browsingcontext.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::cell::DOMRefCell; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};...
(document: &Document) -> SessionHistoryEntry { SessionHistoryEntry { document: JS::from_ref(document), children: vec![], } } } #[allow(unsafe_code)] unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: HandleObject, i...
new
identifier_name
browsingcontext.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::cell::DOMRefCell; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};...
pub fn frame_element(&self) -> Option<&Element> { self.frame_element.r() } pub fn window_proxy(&self) -> *mut JSObject { let window_proxy = self.reflector.get_jsobject(); assert!(!window_proxy.get().is_null()); window_proxy.get() } } // This isn't a DOM struct, just a...
{ Root::from_ref(self.active_document().window()) }
identifier_body
browsingcontext.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::cell::DOMRefCell; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};...
*bp = found; true } #[allow(unsafe_code)] unsafe extern "C" fn get(cx: *mut JSContext, proxy: HandleObject, receiver: HandleObject, id: HandleId, vp: MutableHandleValue) -> bool { ...
{ return false; }
conditional_block
hextobase64.rs
extern crate matasano; use self::matasano::common::{base64, err}; fn test_hex_to_base64(input: &str, output: &str) { let r: Result<String, err::Error> = base64::hex_to_base64(input); let base64 = match r { Ok(v) => v, Err(e) => { println!("{}", e); String::from("N.A.") } }; assert_eq!(base64, ...
#[test] fn test_more() { test_hex_to_base64("00", "AA=="); test_hex_to_base64("00FF", "AP8="); test_hex_to_base64("00FFed", "AP/t"); test_hex_to_base64("00F3ed45", "APPtRQ=="); test_hex_to_base64("00F3ed455727efd982a8b340", "APPtRVcn79mCqLNA"); test_hex_to_base64("", ""); }
{ let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"; test_hex_to_base64(input, output); }
identifier_body
hextobase64.rs
extern crate matasano; use self::matasano::common::{base64, err}; fn test_hex_to_base64(input: &str, output: &str) { let r: Result<String, err::Error> = base64::hex_to_base64(input); let base64 = match r { Ok(v) => v, Err(e) => { println!("{}", e); String::from("N.A.") } }; assert_eq!(base64, ...
() { let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"; test_hex_to_base64(input, output); } #[test] fn test_more() { test_hex_to_base64("00", "AA=="); test_hex_to_base64(...
test_cryptopals_case
identifier_name
hextobase64.rs
extern crate matasano; use self::matasano::common::{base64, err}; fn test_hex_to_base64(input: &str, output: &str) { let r: Result<String, err::Error> = base64::hex_to_base64(input); let base64 = match r { Ok(v) => v, Err(e) => { println!("{}", e); String::from("N.A.") } };
#[test] fn test_cryptopals_case() { let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"; test_hex_to_base64(input, output); } #[test] fn test_more() { test_hex_to_base64("00"...
assert_eq!(base64, output); }
random_line_split
mod.rs
use crate::flowgger::config::Config; use openssl::bn::BigNum; use openssl::dh::Dh; use openssl::ssl::*; use std::path::{Path, PathBuf}; pub mod tls_input; #[cfg(feature = "coroutines")] pub mod tlsco_input; pub use super::Input; const DEFAULT_CERT: &str = "flowgger.pem"; const DEFAULT_CIPHERS: &str = "ECDHE-ECDS...
}) .to_owned(); let ciphers = config .lookup("input.tls_ciphers") .map_or(DEFAULT_CIPHERS, |x| { x.as_str() .expect("input.tls_ciphers must be a string with a cipher suite") }) .to_owned(); let tls_modern = match config .lookup("inpu...
{ let listen = config .lookup("input.listen") .map_or(DEFAULT_LISTEN, |x| { x.as_str().expect("input.listen must be an ip:port string") }) .to_owned(); let threads = get_default_threads(config); let cert = config .lookup("input.tls_cert") .map_or(D...
identifier_body
mod.rs
use crate::flowgger::config::Config; use openssl::bn::BigNum; use openssl::dh::Dh; use openssl::ssl::*; use std::path::{Path, PathBuf}; pub mod tls_input; #[cfg(feature = "coroutines")] pub mod tlsco_input; pub use super::Input; const DEFAULT_CERT: &str = "flowgger.pem"; const DEFAULT_CIPHERS: &str = "ECDHE-ECDS...
const DEFAULT_COMPRESSION: bool = false; const DEFAULT_FRAMING: &str = "line"; const DEFAULT_KEY: &str = "flowgger.pem"; const DEFAULT_LISTEN: &str = "0.0.0.0:6514"; #[cfg(feature = "coroutines")] const DEFAULT_THREADS: usize = 1; const DEFAULT_TIMEOUT: u64 = 3600; const DEFAULT_TLS_COMPATIBILITY_LEVEL: &str = "default...
!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA";
random_line_split
mod.rs
use crate::flowgger::config::Config; use openssl::bn::BigNum; use openssl::dh::Dh; use openssl::ssl::*; use std::path::{Path, PathBuf}; pub mod tls_input; #[cfg(feature = "coroutines")] pub mod tlsco_input; pub use super::Input; const DEFAULT_CERT: &str = "flowgger.pem"; const DEFAULT_CIPHERS: &str = "ECDHE-ECDS...
{ framing: String, threads: usize, acceptor: SslAcceptor, } fn set_fs(ctx: &mut SslContextBuilder) { let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4...
TlsConfig
identifier_name
mod.rs
use crate::flowgger::config::Config; use openssl::bn::BigNum; use openssl::dh::Dh; use openssl::ssl::*; use std::path::{Path, PathBuf}; pub mod tls_input; #[cfg(feature = "coroutines")] pub mod tlsco_input; pub use super::Input; const DEFAULT_CERT: &str = "flowgger.pem"; const DEFAULT_CIPHERS: &str = "ECDHE-ECDS...
else { SslAcceptor::mozilla_intermediate(SslMethod::tls()) }) .unwrap(); { let mut ctx = &mut acceptor_builder; if let Some(ca_file) = ca_file { ctx.set_ca_file(&ca_file) .expect("Unable to read the trusted CA file"); } if!verify_peer { ...
{ SslAcceptor::mozilla_modern(SslMethod::tls()) }
conditional_block
local_rate_limit.rs
/* * Copyright 2020 Google LLC * * 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 applicable law or agreed to i...
t.run_server_with_config(server_config); let (mut recv_chan, socket) = t.open_socket_and_recv_multiple_packets().await; let server_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), server_port); for _ in 0..3 { socket.send_to(b"hello", &server_addr).await.unwrap(); } fo...
{ let mut t = TestHelper::default(); let yaml = " max_packets: 2 period: 1 "; let echo = t.run_echo_server().await; let server_port = 12346; let server_config = ConfigBuilder::empty() .with_port(server_port) .with_static( vec![Filter { name: local_rate_l...
identifier_body
local_rate_limit.rs
/* * Copyright 2020 Google LLC * * 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 applicable law or agreed to i...
() { let mut t = TestHelper::default(); let yaml = " max_packets: 2 period: 1 "; let echo = t.run_echo_server().await; let server_port = 12346; let server_config = ConfigBuilder::empty() .with_port(server_port) .with_static( vec![Filter { name: local_rate_...
local_rate_limit_filter
identifier_name
local_rate_limit.rs
/* * Copyright 2020 Google LLC * * 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 applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language govern...
*
random_line_split
cssmediarule.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 cssparser::Parser; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding; use dom::bindings::codegen::Bind...
fn Media(&self) -> Root<MediaList> { self.medialist() } }
impl CSSMediaRuleMethods for CSSMediaRule { // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media
random_line_split
cssmediarule.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 cssparser::Parser; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding; use dom::bindings::codegen::Bind...
self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.mediarule.read_with(&guard).to_css_string(&guard).into() } } impl CSSMediaRuleMethods for CSSMediaRule { // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media fn Media(&self) -> Root<MediaList> { ...
t_css(&
identifier_name
logical_ast.rs
use query::Occur; use schema::Field; use schema::Term; use schema::Type; use std::fmt; use std::ops::Bound; #[derive(Clone)] pub enum LogicalLiteral { Term(Term), Phrase(Vec<(usize, Term)>), Range { field: Field, value_type: Type, lower: Bound<Term>, upper: Bound<Term>, ...
} impl From<LogicalLiteral> for LogicalAST { fn from(literal: LogicalLiteral) -> LogicalAST { LogicalAST::Leaf(Box::new(literal)) } } impl fmt::Debug for LogicalLiteral { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { LogicalLiteral::Te...
{ match *self { LogicalAST::Clause(ref clause) => { if clause.is_empty() { write!(formatter, "<emptyclause>")?; } else { let (ref occur, ref subquery) = clause[0]; write!(formatter, "({}{:?}", occur_letter(*o...
identifier_body
logical_ast.rs
use query::Occur; use schema::Field; use schema::Term; use schema::Type; use std::fmt; use std::ops::Bound; #[derive(Clone)] pub enum LogicalLiteral { Term(Term), Phrase(Vec<(usize, Term)>), Range { field: Field, value_type: Type, lower: Bound<Term>, upper: Bound<Term>, ...
LogicalAST::Leaf(ref literal) => write!(formatter, "{:?}", literal), } } } impl From<LogicalLiteral> for LogicalAST { fn from(literal: LogicalLiteral) -> LogicalAST { LogicalAST::Leaf(Box::new(literal)) } } impl fmt::Debug for LogicalLiteral { fn fmt(&self, formatter: &mut...
{ if clause.is_empty() { write!(formatter, "<emptyclause>")?; } else { let (ref occur, ref subquery) = clause[0]; write!(formatter, "({}{:?}", occur_letter(*occur), subquery)?; for &(ref occur, ref subquery) ...
conditional_block
logical_ast.rs
use query::Occur; use schema::Field; use schema::Term; use schema::Type; use std::fmt; use std::ops::Bound; #[derive(Clone)] pub enum LogicalLiteral { Term(Term), Phrase(Vec<(usize, Term)>), Range { field: Field, value_type: Type, lower: Bound<Term>, upper: Bound<Term>, ...
Clause(Vec<(Occur, LogicalAST)>), Leaf(Box<LogicalLiteral>), } fn occur_letter(occur: Occur) -> &'static str { match occur { Occur::Must => "+", Occur::MustNot => "-", Occur::Should => "", } } impl fmt::Debug for LogicalAST { fn fmt(&self, formatter: &mut fmt::Formatter) ->...
} #[derive(Clone)] pub enum LogicalAST {
random_line_split
logical_ast.rs
use query::Occur; use schema::Field; use schema::Term; use schema::Type; use std::fmt; use std::ops::Bound; #[derive(Clone)] pub enum
{ Term(Term), Phrase(Vec<(usize, Term)>), Range { field: Field, value_type: Type, lower: Bound<Term>, upper: Bound<Term>, }, All, } #[derive(Clone)] pub enum LogicalAST { Clause(Vec<(Occur, LogicalAST)>), Leaf(Box<LogicalLiteral>), } fn occur_letter(occur: ...
LogicalLiteral
identifier_name
deferred.rs
use std::ops; use std::str; use std::fmt; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Deferred<T> { StaticStr(&'static str), Actual(T), } impl<T> Deferred<T> where T: From<&'static str> { pub(crate) fn into_actual(self) -> T
pub(crate) fn actual(&mut self) -> &mut T { if let Deferred::StaticStr(value) = *self { *self = Deferred::Actual(value.into()); } match *self { Deferred::StaticStr(_) => panic!("unexpected static storage"), Deferred::Actual(ref mut value) => value, ...
{ match self { Deferred::StaticStr(value) => value.into(), Deferred::Actual(value) => value, } }
identifier_body
deferred.rs
use std::ops; use std::str; use std::fmt; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Deferred<T> { StaticStr(&'static str),
} impl<T> Deferred<T> where T: From<&'static str> { pub(crate) fn into_actual(self) -> T { match self { Deferred::StaticStr(value) => value.into(), Deferred::Actual(value) => value, } } pub(crate) fn actual(&mut self) -> &mut T { if let Deferred::StaticStr(...
Actual(T),
random_line_split
deferred.rs
use std::ops; use std::str; use std::fmt; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Deferred<T> { StaticStr(&'static str), Actual(T), } impl<T> Deferred<T> where T: From<&'static str> { pub(crate) fn into_actual(self) -> T { match self { Deferred::StaticStr(value) => val...
(&mut self) -> &mut T { if let Deferred::StaticStr(value) = *self { *self = Deferred::Actual(value.into()); } match *self { Deferred::StaticStr(_) => panic!("unexpected static storage"), Deferred::Actual(ref mut value) => value, } } } impl<T> fmt:...
actual
identifier_name
implementations.rs
//! Implementations of `Header` and `ToHeader` for various types. use std::str; use std::fmt; use super::{Header, ToHeader}; impl ToHeader for usize { fn parse(raw: &[u8]) -> Option<usize> { str::from_utf8(raw).ok().and_then(|s| s.parse().ok()) } } impl Header for usize { fn fmt(&self, f: &mut f...
} }
bad::<usize>(b"1234567890123467901245790"); bad::<usize>(b"1,000");
random_line_split
implementations.rs
//! Implementations of `Header` and `ToHeader` for various types. use std::str; use std::fmt; use super::{Header, ToHeader}; impl ToHeader for usize { fn parse(raw: &[u8]) -> Option<usize>
} impl Header for usize { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", *self) } } #[cfg(test)] mod tests { use std::fmt; use headers::{Header, ToHeader, HeaderDisplayAdapter}; fn eq<H: Header + ToHeader + Eq + fmt::Debug>(raw: &[u8], typed: H) { assert_e...
{ str::from_utf8(raw).ok().and_then(|s| s.parse().ok()) }
identifier_body
implementations.rs
//! Implementations of `Header` and `ToHeader` for various types. use std::str; use std::fmt; use super::{Header, ToHeader}; impl ToHeader for usize { fn parse(raw: &[u8]) -> Option<usize> { str::from_utf8(raw).ok().and_then(|s| s.parse().ok()) } } impl Header for usize { fn fmt(&self, f: &mut f...
() { eq(b"0", 0usize); eq(b"1", 1usize); eq(b"123456789", 123456789usize); bad::<usize>(b"-1"); bad::<usize>(b"0xdeadbeef"); bad::<usize>(b"deadbeef"); bad::<usize>(b"1234567890123467901245790"); bad::<usize>(b"1,000"); } }
test_usize
identifier_name
thread.rs
// Copyright 2014 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 ...
{ handle: Handle } impl Thread { pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>) -> io::Result<Thread> { let p = box p; // FIXME On UNIX, we guard against stack sizes that are too small but // that's because pthreads enforces that stacks are at leas...
Thread
identifier_name
thread.rs
// Copyright 2014 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 ...
0 } } pub fn set_name(_name: &str) { // Windows threads are nameless // The names in MSVC debugger are obtained using a "magic" exception, // which requires a use of MS C++ extensions. // See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx } p...
unsafe { start_thread(main); }
random_line_split
thread.rs
// Copyright 2014 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 ...
else { mem::forget(p); // ownership passed to CreateThread Ok(Thread { handle: Handle::new(ret) }) }; #[no_stack_check] extern "system" fn thread_start(main: *mut libc::c_void) -> DWORD { unsafe { start_thread(main); } 0 } } pub ...
{ Err(io::Error::last_os_error()) }
conditional_block
change_set.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::ledger_counters::LedgerCounterBumps; use diem_types::transaction::Version; use schemadb::SchemaBatch; use std::collections::HashMap; /// Structure that collects changes to be made to the DB in one transaction. /// /// To be ...
pub(crate) struct SealedChangeSet { /// A batch of db alternations. pub batch: SchemaBatch, }
/// This is a wrapper type just to make sure `ChangeSet` to be committed is sealed properly.
random_line_split
change_set.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::ledger_counters::LedgerCounterBumps; use diem_types::transaction::Version; use schemadb::SchemaBatch; use std::collections::HashMap; /// Structure that collects changes to be made to the DB in one transaction. /// /// To be ...
{ /// A batch of db alternations. pub batch: SchemaBatch, }
SealedChangeSet
identifier_name
change_set.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::ledger_counters::LedgerCounterBumps; use diem_types::transaction::Version; use schemadb::SchemaBatch; use std::collections::HashMap; /// Structure that collects changes to be made to the DB in one transaction. /// /// To be ...
pub fn counter_bumps(&mut self, version: Version) -> &mut LedgerCounterBumps { self.counter_bumps .entry(version) .or_insert_with(LedgerCounterBumps::new) } #[cfg(test)] pub fn new_with_bumps(counter_bumps: HashMap<Version, LedgerCounterBumps>) -> Self { Self { ...
{ Self { batch: SchemaBatch::new(), counter_bumps: HashMap::new(), } }
identifier_body
main.rs
extern crate chrono; #[macro_use] extern crate clap; extern crate cursive; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use std::cmp; use std::panic; use chrono::prelude::*; use cursive::Cursive; use cursive::direction::*; use cursive::event::*; use cursi...
() { let matches = clap_app!(lit_af_rs => (version: "0.1.0") (author: "Trey Del Bonis <j.delbonis.3@gmail.com>") (about: "CLI client for Lit") (@arg a: +takes_value "Address to connect to. Default: localhost") (@arg p: +takes_value "Port to connect to lit to. Default: idk ...
main
identifier_name
main.rs
extern crate chrono; #[macro_use] extern crate clap; extern crate cursive; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use std::cmp; use std::panic; use chrono::prelude::*; use cursive::Cursive; use cursive::direction::*; use cursive::event::*; use cursi...
let dt: DateTime<Utc> = DateTime::from_utc(ndt, chrono::Utc); let mut data = LinearLayout::new(Orientation::Vertical); data.add_child(TextView::new(format!("Channel # {}", chan.CIdx))); data.add_child(TextView::new(format!("Outpoint: {}", chan.OutPoint))); data.add_child(TextView::new(format!("Peer...
random_line_split
main.rs
extern crate chrono; #[macro_use] extern crate clap; extern crate cursive; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use std::cmp; use std::panic; use chrono::prelude::*; use cursive::Cursive; use cursive::direction::*; use cursive::event::*; use cursi...
c.call_on_id("chans", |cpan: &mut Panel<LinearLayout>| { let mut c_view = LinearLayout::new(Orientation::Vertical); c_view.add_child(TextView::new("Channels")); chans.into_iter() .map(generate_view_for_chan) .for_each(|e| c_view.add_child(e)); ...
{ use std::mem; let clp: *mut litrpc::LitRpcClient = unsafe { mem::transmute(cl) }; move |c: &mut Cursive| { let clrc: &mut litrpc::LitRpcClient = unsafe { mem::transmute(clp) }; // Channels. let chans: Vec<litrpc::ChanInfo> = match clrc.call_chan_list(0) { Ok(clr) =...
identifier_body
main.rs
extern crate chrono; #[macro_use] extern crate clap; extern crate cursive; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use std::cmp; use std::panic; use chrono::prelude::*; use cursive::Cursive; use cursive::direction::*; use cursive::event::*; use cursi...
, Err(err) => panic!("{:?}", err) }; c.call_on_id("bals", |balpan: &mut Panel<LinearLayout>| { let mut bal_view = LinearLayout::new(Orientation::Vertical); bal_view.add_child(TextView::new("Balances")); bal_view.add_child(DummyView); bals.int...
{ let mut addrs: Vec<(u32, String)> = ar.CoinTypes.into_iter() .zip(ar.WitAddresses.into_iter()) .collect(); addrs.sort_by(|a, b| match cmp::Ord::cmp(&a.0, &b.0) { cmp::Ordering::Equal => cmp::Ord::cmp(&a.1, &b.1), ...
conditional_block
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use consensus_types::block::Block; use diem_crypto::HashValue; use diem_types::transaction::Transaction; mod execution_correctness; mod execution_correctness_manager; mod local; mod process; mod remote_service;...
(block: &Block) -> (HashValue, Vec<Transaction>) { let id = block.id(); let mut transactions = vec![Transaction::BlockMetadata(block.into())]; transactions.extend( block .payload() .unwrap_or(&vec![]) .iter() .map(|txn| Transaction::UserTransaction(txn.clo...
id_and_transactions_from_block
identifier_name
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use consensus_types::block::Block; use diem_crypto::HashValue; use diem_types::transaction::Transaction; mod execution_correctness; mod execution_correctness_manager; mod local; mod process; mod remote_service;...
{ let id = block.id(); let mut transactions = vec![Transaction::BlockMetadata(block.into())]; transactions.extend( block .payload() .unwrap_or(&vec![]) .iter() .map(|txn| Transaction::UserTransaction(txn.clone())), ); (id, transactions) }
identifier_body
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use consensus_types::block::Block; use diem_crypto::HashValue; use diem_types::transaction::Transaction;
mod remote_service; mod serializer; mod thread; pub use crate::{ execution_correctness::ExecutionCorrectness, execution_correctness_manager::ExecutionCorrectnessManager, process::Process, }; #[cfg(test)] mod tests; fn id_and_transactions_from_block(block: &Block) -> (HashValue, Vec<Transaction>) { let id...
mod execution_correctness; mod execution_correctness_manager; mod local; mod process;
random_line_split
closures.rs
// build-fail // compile-flags:-Zpolymorphize=on #![feature(generic_const_exprs, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete // This test checks that the polymorphization analysis correctly detects unused const // parameters in closures. // Function doesn't have any generic parameters to b...
// Function has an unused generic parameter in closure, but not in parent. #[rustc_polymorphize_error] pub fn used_parent<const T: usize>() -> usize { let x: usize = T; let add_one = |x: usize| x + 1; //~^ ERROR item has unused generic parameters x + add_one(3) } // Function uses generic parameter in...
{ //~^ ERROR item has unused generic parameters let add_one = |x: usize| x + 1; //~^ ERROR item has unused generic parameters add_one(3) }
identifier_body
closures.rs
// build-fail // compile-flags:-Zpolymorphize=on #![feature(generic_const_exprs, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete // This test checks that the polymorphization analysis correctly detects unused const // parameters in closures. // Function doesn't have any generic parameters to b...
//~^ ERROR item has unused generic parameters add_one(3) } // Function has an unused generic parameter in closure, but not in parent. #[rustc_polymorphize_error] pub fn used_parent<const T: usize>() -> usize { let x: usize = T; let add_one = |x: usize| x + 1; //~^ ERROR item has unused generic para...
// Function has an unused generic parameter in parent and closure. #[rustc_polymorphize_error] pub fn unused<const T: usize>() -> usize { //~^ ERROR item has unused generic parameters let add_one = |x: usize| x + 1;
random_line_split
closures.rs
// build-fail // compile-flags:-Zpolymorphize=on #![feature(generic_const_exprs, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete // This test checks that the polymorphization analysis correctly detects unused const // parameters in closures. // Function doesn't have any generic parameters to b...
<const T: usize>() -> usize { //~^ ERROR item has unused generic parameters let add_one = |x: usize| x + 1; //~^ ERROR item has unused generic parameters add_one(3) } // Function has an unused generic parameter in closure, but not in parent. #[rustc_polymorphize_error] pub fn used_parent<const T: usize...
unused
identifier_name
kill-setuid.rs
extern crate libc; extern crate seccomp_sys; fn main()
assert!(seccomp_sys::seccomp_load(context) == 0); assert!(libc::setuid(1000) == 0); /* process would be killed here */ } }
{ unsafe { let context = seccomp_sys::seccomp_init(seccomp_sys::SCMP_ACT_ALLOW); let comparator = seccomp_sys::scmp_arg_cmp { arg: 0, op: seccomp_sys::scmp_compare::SCMP_CMP_EQ, datum_a: 1000, datum_b: 0, }; /* arg[0] equals 1000 */ le...
identifier_body
kill-setuid.rs
extern crate libc; extern crate seccomp_sys; fn
() { unsafe { let context = seccomp_sys::seccomp_init(seccomp_sys::SCMP_ACT_ALLOW); let comparator = seccomp_sys::scmp_arg_cmp { arg: 0, op: seccomp_sys::scmp_compare::SCMP_CMP_EQ, datum_a: 1000, datum_b: 0, }; /* arg[0] equals 1000 */ ...
main
identifier_name
kill-setuid.rs
extern crate libc; extern crate seccomp_sys; fn main() { unsafe {
let comparator = seccomp_sys::scmp_arg_cmp { arg: 0, op: seccomp_sys::scmp_compare::SCMP_CMP_EQ, datum_a: 1000, datum_b: 0, }; /* arg[0] equals 1000 */ let syscall_number = 105; /* setuid on x86_64 */ assert!( seccomp_sys::secc...
let context = seccomp_sys::seccomp_init(seccomp_sys::SCMP_ACT_ALLOW);
random_line_split
lib.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...
} fn version() -> &'static str { env!("CARGO_PKG_VERSION") } } fn add(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("add").unwrap(); // safed by main() let mut ids = rt .ids::<crate::ui::PathProvider>() .context("No StoreId supplied")? .ok_or_els...
fn description() -> &'static str { "Add annotations to entries"
random_line_split
lib.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...
Ok(()) } fn remove(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("remove").unwrap(); // safed by main() let annotation_name = scmd.value_of("annotation_name").unwrap(); // safed by clap let delete = scmd.is_present("delete-annotation"); rt.ids::<crate::...
{ debug!("No entries to annotate"); }
conditional_block
lib.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...
fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> { ui::build_ui(app) } fn name() -> &'static str { env!("CARGO_PKG_NAME") } fn description() -> &'static str { "Add annotations to entries" } fn version() -> &'static str { env!("CARGO_PKG_VERSION") } }...
{ match rt.cli().subcommand_name().ok_or_else(|| anyhow!("No command called"))? { "add" => add(&rt), "remove" => remove(&rt), "list" => list(&rt), other => { debug!("Unknown command"); if rt.handle_unknown_subcommand("imag-a...
identifier_body
lib.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...
() -> &'static str { "Add annotations to entries" } fn version() -> &'static str { env!("CARGO_PKG_VERSION") } } fn add(rt: &Runtime) -> Result<()> { let scmd = rt.cli().subcommand_matches("add").unwrap(); // safed by main() let mut ids = rt .ids::<crate::ui::PathProvider>()...
description
identifier_name
lib.rs
// The code below is a stub. Just enough to satisfy the compiler. // In order to pass the tests you can add-to or change any of this code. use Direction::*; #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum Direction { North, East, South, West, } pub struct Robot { x: isize, y: isize, ...
pub fn instructions(self, instructions: &str) -> Self { instructions.chars().fold(self, |accu, c| { match c { 'A' => accu.advance(), 'L' => accu.turn_left(), 'R' => accu.turn_right(), _ => unreachable!(), } }) ...
{ let (new_x, new_y) = match self.direction { North => (self.x, self.y + 1), East => (self.x + 1, self.y), South => (self.x, self.y - 1), West => (self.x - 1, self.y), }; Robot::new(new_x, new_y, self.direction) }
identifier_body
lib.rs
// The code below is a stub. Just enough to satisfy the compiler. // In order to pass the tests you can add-to or change any of this code. use Direction::*; #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum Direction { North, East, South, West, } pub struct Robot { x: isize, y: isize, ...
'A' => accu.advance(), 'L' => accu.turn_left(), 'R' => accu.turn_right(), _ => unreachable!(), } }) } pub fn position(&self) -> (isize, isize) { (self.x, self.y) } pub fn direction(&self) -> &Direction { ...
} pub fn instructions(self, instructions: &str) -> Self { instructions.chars().fold(self, |accu, c| { match c {
random_line_split
lib.rs
// The code below is a stub. Just enough to satisfy the compiler. // In order to pass the tests you can add-to or change any of this code. use Direction::*; #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum Direction { North, East, South, West, } pub struct
{ x: isize, y: isize, direction: Direction, } impl Robot { pub fn new(x: isize, y: isize, d: Direction) -> Self { Robot { x: x, y: y, direction: d, } } pub fn turn_right(self) -> Self { let new_direction = match self.direction { ...
Robot
identifier_name
mod.rs
use super::database::{id_to_class,class_to_type}; use self::parse_ebml_number::parse_ebml_number; use self::parse_ebml_number::Result as EbmlParseNumberResult; use self::parse_ebml_number::Mode as EbmlParseNumberMode; use std::vec::Vec; use std::string::String; use std::fmt; mod parse_ebml_number; #[cfg(test)] mo...
} } fn try_parse_element_data<'a, E : EventsHandler+?Sized>(&mut self, buf:&'a [u8], len:usize, typ : super::Type, cb: &mut E) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::{NoMoreData,KeepGoing,Error}; use self::Event::{Data}; use self::SimpleCont...
{ let (_, trail) = buf.split_at(1); KeepGoing(trail) }
conditional_block
mod.rs
use super::database::{id_to_class,class_to_type}; use self::parse_ebml_number::parse_ebml_number; use self::parse_ebml_number::Result as EbmlParseNumberResult; use self::parse_ebml_number::Mode as EbmlParseNumberMode; use std::vec::Vec; use std::string::String; use std::fmt; mod parse_ebml_number; #[cfg(test)] mo...
} impl ParserState { fn try_resync<'a>(&mut self, buf:&'a [u8]) -> ResultOfTryParseSomething<'a> { use self::ResultOfTryParseSomething::*; if buf.len() < 4 { return NoMoreData; } let (fourbytes, _) = buf.split_at(4); let id : u32 = (fourbytes[0] as u32)*0x100000...
random_line_split
mod.rs
use super::database::{id_to_class,class_to_type}; use self::parse_ebml_number::parse_ebml_number; use self::parse_ebml_number::Result as EbmlParseNumberResult; use self::parse_ebml_number::Mode as EbmlParseNumberMode; use std::vec::Vec; use std::string::String; use std::fmt; mod parse_ebml_number; #[cfg(test)] mo...
() -> ParserState { self::Parser::new() } ////////////////////////////// impl fmt::Debug for Info { fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let cl = super::database::id_to_class(self.id); let typ = super::database::class_to_type(cl); let cldesc = match cl { ...
new
identifier_name
mod.rs
use super::database::{id_to_class,class_to_type}; use self::parse_ebml_number::parse_ebml_number; use self::parse_ebml_number::Result as EbmlParseNumberResult; use self::parse_ebml_number::Mode as EbmlParseNumberMode; use std::vec::Vec; use std::string::String; use std::fmt; mod parse_ebml_number; #[cfg(test)] mo...
//cb.log( format!("feed_bytes3 len={}", self.accumulator.len()).as_str()); } fn force_resync(&mut self) { self.mode = self::ParserMode::Resync; } }
{ use self::ResultOfTryParseSomething::*; use self::ParserMode::*; //cb.log(format!("feed_bytes {} len={}", bytes[0], self.accumulator.len()).as_str() ); self.accumulator.extend_from_slice(bytes); let tmpvector = self.accumulator.to_vec(); { ...
identifier_body
lib.rs
//! This crate defines a macro for creating iterators which implement //! recurrence relations. /* This is an implementation detail, but it *also* needs to be visible at the *expansion* site of the `recurrence` macro (*i.e.* in another crate). Thus, we need to publically export this macro. That said, we don't want i...
&self.slice[real_index.0] } } impl Iterator for Recurrence { type Item = $sty; #[inline] fn next(&mut self) -> Option<$sty> { if self.pos < MEM_SIZE { let nex...
let offset = Wrapping(self.offset); let window = Wrapping(MEM_SIZE); let real_index = index - offset + window;
random_line_split
main.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/. */ //! A Takuzu (a.k.a. Binairo) solver. //! //! # Usage //! //! ```shell //! takuzu [FILE]... //! takuzu {--help | ...
match $result { Ok(ok) => print_solutions(&ok.0, &ok.1, None), Err(err) => eprintln!("error: {}", causes_fold(&err)), } }; ($result:expr, $filename:expr) => { match $result { Ok(ok) => print_solutions(&ok.0, &ok.1, Some($filename)), Err(err...
random_line_split
main.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/. */ //! A Takuzu (a.k.a. Binairo) solver. //! //! # Usage //! //! ```shell //! takuzu [FILE]... //! takuzu {--help | ...
/// Prints a grid's solution(s) to `stdout`. /// /// If there is more than one solution, the grids are separated an empty line. /// If `stdout` is a terminal, prints the grids with colors and preceded by /// a numbered label. Optionnally, prints the filename before the solutions. fn print_solutions(grid: &Grid, solut...
{ let grid = match filename { "-" => stdin().source()?, _ => ::std::fs::File::open(filename)?.source()?, }; let solutions = grid.solve()?; Ok((grid, solutions)) }
identifier_body
main.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/. */ //! A Takuzu (a.k.a. Binairo) solver. //! //! # Usage //! //! ```shell //! takuzu [FILE]... //! takuzu {--help | ...
(error: &Error) -> String { error .causes() .skip(1) .fold(error.to_string(), |mut buffer, cause| { write!(&mut buffer, ": {}", cause).unwrap(); buffer }) } /// Returns `true` if `stdout` is a terminal. fn isatty_stdout() -> bool { match unsafe { libc::isatt...
causes_fold
identifier_name
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn
( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, is_forward: bool, ) -> anyhow::Result<()> { let empty_list = Vec::new(); for (module, _) in graph.iter() { // (breadth-first) search and gather the modules in `graph` which are reachable from `module`. let mut dot_src: String ...
generate_diagram_per_module
identifier_name
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn generate_diagram_per_module( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, ...
for (module, _) in graph.iter() { // (breadth-first) search and gather the modules in `graph` which are reachable from `module`. let mut dot_src: String = String::new(); let mut visited: BTreeSet<String> = BTreeSet::new(); let mut queue: VecDeque<String> = VecDeque::new(); ...
let empty_list = Vec::new();
random_line_split
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn generate_diagram_per_module( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, ...
{ let (inp_dir, out_dir) = locate_inp_out_dir(); let err = generate(inp_dir.as_path(), out_dir.as_path()); if let Err(err) = err { println!("Error: {:?}", err); } }
identifier_body
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn generate_diagram_per_module( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, ...
let module_name = caps.unwrap()[1].to_string(); if let Entry::Vacant(e) = dep_graph_inverse.entry(module_name.clone()) { e.insert(vec![]); } let mut dep_list: Vec<String> = Vec::new(); // TODO: This is not 100% correct because modules can be used with full qualifica...
{ // skip due to no module declaration found. continue; }
conditional_block
doc.rs
// Copyright 2012 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 ...
In this example, the closure bound is not explicit. At compile time, we will create a region variable (let's call it `V0`) to represent the closure bound. The primary difficulty arises during the constraint propagation phase. Imagine there is some variable with incoming edges from `'c` and `'d`. This means that the va...
}
random_line_split
partial_cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl PartialOrd for str { // #[inline] // fn partial_cmp(&self, other: &str) -> Option<Ordering> { // Some(self.cmp(other)) // } // ...
test] fn partial_cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Equal)); } #[test] fn partial_cmp_test4() { let x: &str = "人口"; let other: &str = "人"; let result: Option<Ordering> = x.partial_cmp(oth...
et x: &str = "天"; // '\u{5929}' let other: &str = "地"; // '\u{5730}' let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Greater)); } #[
identifier_body
partial_cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl PartialOrd for str { // #[inline] // fn partial_cmp(&self, other: &str) -> Option<Ordering> { // Some(self.cmp(other)) // } // ...
let x: &str = "天"; // '\u{5929}' let other: &str = "地"; // '\u{5730}' let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Greater)); } #[test] fn partial_cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Option<Ordering> = x.partial_cmp(other); ...
ial_cmp_test2() {
identifier_name
partial_cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl PartialOrd for str { // #[inline] // fn partial_cmp(&self, other: &str) -> Option<Ordering> { // Some(self.cmp(other)) // } // ...
assert_eq!(result, Some::<Ordering>(Greater)); } #[test] fn partial_cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Equal)); } #[test] fn partial_cmp_test4() { let x: &str = "人口"; let other: ...
let other: &str = "地"; // '\u{5730}' let result: Option<Ordering> = x.partial_cmp(other);
random_line_split
errors.rs
use serde::ser::Serialize; use serde_json::Value; use api::rpc::Error; pub fn parse_error() -> Error { Error { message: "parse error".to_owned(), code: -32700, data: None, } } pub fn invalid_request() -> Error { Error { message: "invalid request".to_owned(), code: ...
pub fn method_not_found() -> Error { Error { message: "method not found".to_owned(), code: -32601, data: None, } } // pub fn invalid_params(params: Value) -> Error { // Error { // code: -32602, // message: "invalid params".to_owned(), // data: params, // ...
{ Error { code: -32600, message: "unsupported JSON-RPC protocol version".to_owned(), data: None, } }
identifier_body
errors.rs
use serde::ser::Serialize; use serde_json::Value; use api::rpc::Error; pub fn parse_error() -> Error { Error { message: "parse error".to_owned(), code: -32700, data: None, } } pub fn
() -> Error { Error { message: "invalid request".to_owned(), code: -32600, data: None, } } pub fn invalid_version() -> Error { Error { code: -32600, message: "unsupported JSON-RPC protocol version".to_owned(), data: None, } } pub fn method_not_found() ->...
invalid_request
identifier_name
errors.rs
use serde::ser::Serialize; use serde_json::Value; use api::rpc::Error; pub fn parse_error() -> Error { Error { message: "parse error".to_owned(), code: -32700, data: None, } } pub fn invalid_request() -> Error { Error { message: "invalid request".to_owned(), code: ...
} pub fn method_not_found() -> Error { Error { message: "method not found".to_owned(), code: -32601, data: None, } } // pub fn invalid_params(params: Value) -> Error { // Error { // code: -32602, // message: "invalid params".to_owned(), // data: params, // ...
Error { code: -32600, message: "unsupported JSON-RPC protocol version".to_owned(), data: None, }
random_line_split
kshiftrd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K7)), operand2: Some(Direct(...
{ run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K5)), operand2: Some(Direct(K7)), operand3: Some(Literal8(99)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 239, 99], OperandSize::Qword) }
identifier_body
kshiftrd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K7)), operand2: Some(Direct(...
() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K5)), operand2: Some(Direct(K7)), operand3: Some(Literal8(99)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 239, 99], OperandSize::Qword) }
kshiftrd_2
identifier_name
kshiftrd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*;
fn kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Literal8(51)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 254, 51], OperandSize::Dwo...
use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*;
random_line_split
i386_apple_ios.rs
// Copyright 2014 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 ...
() -> Target { Target { data_layout: "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\ -i32:32:32-i64:32:64\ -f32:32:32-f64:32:64-v64:64:64\ -v128:128:128-a:0:64-f80:128:128\ -n8:16:32".to_string(), llvm_target: "i386-apple...
target
identifier_name
i386_apple_ios.rs
// Copyright 2014 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 ...
{ Target { data_layout: "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\ -i32:32:32-i64:32:64\ -f32:32:32-f64:32:64-v64:64:64\ -v128:128:128-a:0:64-f80:128:128\ -n8:16:32".to_string(), llvm_target: "i386-apple-ios".to_stri...
identifier_body
i386_apple_ios.rs
// Copyright 2014 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 ...
arch: "x86".to_string(), target_os: "ios".to_string(), target_env: "".to_string(), options: opts(Arch::I386) } }
random_line_split
debug_utils.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 std::slice; fn hexdump_slice(buf: &[u8]) { let mut stderr = io::stderr(); stderr.write_all(b" ").unwrap(); for (i, &v) in buf.iter().enumerate() { let output = format!("{:02X} ", v); stderr.write_all(output.as_bytes()).unwrap(); match i % 16 { 15 => { stderr.write...
use std::io::{self, Write}; use std::mem; use std::mem::size_of;
random_line_split
debug_utils.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 std::io::{self, Write}; use std::mem; use std::mem::size_of; use std::slice; fn hexdump_slice(buf: &[u8]) { ...
{ unsafe { let buf: *const u8 = mem::transmute(obj); debug!("dumping at {:p}", buf); let from_buf = slice::from_raw_parts(buf, size_of::<T>()); hexdump_slice(from_buf); } }
identifier_body
debug_utils.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 std::io::{self, Write}; use std::mem; use std::mem::size_of; use std::slice; fn
(buf: &[u8]) { let mut stderr = io::stderr(); stderr.write_all(b" ").unwrap(); for (i, &v) in buf.iter().enumerate() { let output = format!("{:02X} ", v); stderr.write_all(output.as_bytes()).unwrap(); match i % 16 { 15 => { stderr.write_all(b"\n ").unwrap(); }, ...
hexdump_slice
identifier_name
vm.rs
', not 'find'). This is a half-measure, but does provide some // perf improvement. // // AFAIK, the DFA/NFA approach is implemented in RE2/C++ but *not* in RE2/Go. // // [1] - http://swtch.com/~rsc/regex/regex3.html pub use self::MatchKind::*; pub use self::StepState::*; use std::cmp; use std::cmp::Ordering::{self, L...
fn add(&mut self, pc: uint, groups: &[Option<uint>], empty: bool) { let t = &mut self.queue[self.size]; t.pc = pc; match (empty, self.which) { (_, Exists) | (true, _) => {}, (false, Location) => { t.groups[0] = groups[0]; t.groups[1] = ...
random_line_split
vm.rs
', not 'find'). This is a half-measure, but does provide some // perf improvement. // // AFAIK, the DFA/NFA approach is implemented in RE2/C++ but *not* in RE2/Go. // // [1] - http://swtch.com/~rsc/regex/regex3.html pub use self::MatchKind::*; pub use self::StepState::*; use std::cmp; use std::cmp::Ordering::{self, L...
{ which: MatchKind, queue: Vec<Thread>, sparse: Vec<uint>, size: uint, } impl Threads { // This is using a wicked neat trick to provide constant time lookup // for threads in the queue using a sparse set. A queue of threads is // allocated once with maximal size when the VM initializes and...
Threads
identifier_name
vm.rs
', not 'find'). This is a half-measure, but does provide some // perf improvement. // // AFAIK, the DFA/NFA approach is implemented in RE2/C++ but *not* in RE2/Go. // // [1] - http://swtch.com/~rsc/regex/regex3.html pub use self::MatchKind::*; pub use self::StepState::*; use std::cmp; use std::cmp::Ordering::{self, L...
} // This simulates a preceding '.*?' for every regex by adding // a state starting at the current position in the input for the // beginning of the program only if we don't already have a match. if clist.size == 0 || (!prefix_anchor &&!matched) { ...
{ let needle = self.prog.prefix.as_bytes(); let haystack = &self.input.as_bytes()[self.ic..]; match find_prefix(needle, haystack) { None => break, Some(i) => { self.ic += i; ...
conditional_block
vm.rs
', not 'find'). This is a half-measure, but does provide some // perf improvement. // // AFAIK, the DFA/NFA approach is implemented in RE2/C++ but *not* in RE2/Go. // // [1] - http://swtch.com/~rsc/regex/regex3.html pub use self::MatchKind::*; pub use self::StepState::*; use std::cmp; use std::cmp::Ordering::{self, L...
/// Returns true if and only if the current position is a word boundary. /// (Ignoring the range of the input to search.) pub fn is_word_boundary(&self) -> bool { if self.is_begin() { return is_word(self.cur) } if self.is_end() { return is_word(self.prev) ...
{ self.cur.is_none() }
identifier_body
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (ca...
} impl<'a, S: 'a + EventStopable> Dispatchable<S> for EventDispatcher<'a, EventListener> { fn dispatch(&self, event_name: &str, event: &mut S) { if let Some(listeners) = self.listeners.get(event_name) { for listener in listeners { listener.call(event_name, event); ...
{ if self.listeners.contains_key(event_name) { if let Some(mut listeners) = self.listeners.get_mut(event_name) { match listeners.iter().position(|x| *x == listener) { Some(index) => { listeners.remove(index); }, ...
identifier_body