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
lib.rs
//! Rust friendly bindings to the various *nix system functions. //! //! Modules are structured according to the C header file that they would be //! defined in. #![crate_name = "nix"] #![cfg(unix)] #![allow(non_camel_case_types)] // latest bitflags triggers a rustc bug with cross-crate macro expansions causing dead_co...
} pub fn last() -> Error { Error::Sys(errno::Errno::last()) } pub fn invalid_argument() -> Error { Error::Sys(errno::EINVAL) } pub fn errno(&self) -> errno::Errno { match *self { Error::Sys(errno) => errno, Error::InvalidPath => errno::Errno::EI...
impl Error { pub fn from_errno(errno: errno::Errno) -> Error { Error::Sys(errno)
random_line_split
lib.rs
//! Rust friendly bindings to the various *nix system functions. //! //! Modules are structured according to the C header file that they would be //! defined in. #![crate_name = "nix"] #![cfg(unix)] #![allow(non_camel_case_types)] // latest bitflags triggers a rustc bug with cross-crate macro expansions causing dead_co...
(errno: errno::Errno) -> Error { Error::Sys(errno) } pub fn last() -> Error { Error::Sys(errno::Errno::last()) } pub fn invalid_argument() -> Error { Error::Sys(errno::EINVAL) } pub fn errno(&self) -> errno::Errno { match *self { Error::Sys(errno) =...
from_errno
identifier_name
lib.rs
//! Rust friendly bindings to the various *nix system functions. //! //! Modules are structured according to the C header file that they would be //! defined in. #![crate_name = "nix"] #![cfg(unix)] #![allow(non_camel_case_types)] // latest bitflags triggers a rustc bug with cross-crate macro expansions causing dead_co...
} impl NixPath for Path { fn len(&self) -> usize { self.as_os_str().as_bytes().len() } fn with_nix_path<T, F>(&self, f: F) -> Result<T> where F: FnOnce(&CStr) -> T { self.as_os_str().as_bytes().with_nix_path(f) } } impl NixPath for PathBuf { fn len(&self) -> usize { self....
{ // TODO: Extract this size as a const let mut buf = [0u8; 4096]; if self.len() >= 4096 { return Err(Error::InvalidPath); } match self.iter().position(|b| *b == 0) { Some(_) => Err(Error::InvalidPath), None => { unsafe { ...
identifier_body
noncebased.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
&mut self, buf: &[u8]) -> io::Result<usize> { if self.closed { return Err(io::Error::new( io::ErrorKind::InvalidInput, "write on closed writer", )); } let mut pos = 0; // read position in input plaintext (`buf`) loop { ...
rite(
identifier_name
noncebased.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
/// /// The scheme used for decrypting segments is specified by providing a /// [`SegmentDecrypter`] implementation. The implementation must align /// with the [`SegmentEncrypter`] used in the [`Writer`]. pub struct Reader { r: Box<dyn io::Read>, segment_decrypter: Box<dyn SegmentDecrypter>, decrypted_segme...
/// `Reader` facilitates the decryption of ciphertexts created using a [`Writer`].
random_line_split
noncebased.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
} /// `SegmentDecrypter` facilitates implementing various streaming AEAD encryption modes. pub trait SegmentDecrypter { fn decrypt_segment(&self, segment: &[u8], nonce: &[u8]) -> Result<Vec<u8>, TinkError>; } /// `Reader` facilitates the decryption of ciphertexts created using a [`Writer`]. /// /// The scheme use...
let _ = self.close(); }
identifier_body
noncebased.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
// Calculate the expected segment nonce and decrypt a segment. let nonce = generate_segment_nonce( self.nonce_size, &self.nonce_prefix, self.decrypted_segment_cnt, last_segment, )?; self.plaintext = self .segment_decrypter ...
last_segment = false; if (self.ciphertext_pos + n) < 1 { return Err(io::Error::new( io::ErrorKind::InvalidInput, "ciphertext segment too short", )); } segment = self.ciphertext_pos + n - 1; }...
conditional_block
lib.rs
//! Lettre is a mailer written in Rust. It provides a simple email builder and several transports. //! //! ## Architecture //! //! This mailer is divided into: //! //! * An `email` part: builds the email message //! * A `transport` part: contains the available transports for your emails. To be sendable, the emails have...
//! //! // Write to the local temp directory //! let mut sender = FileEmailTransport::new(temp_dir()); //! let email = EmailBuilder::new() //! .to("root@localhost") //! .from("user@localhost") //! .body("Hello World!") //! .subject("Hello") //! ...
//! use lettre::transport::file::FileEmailTransport; //! use lettre::transport::EmailTransport; //! use lettre::email::{EmailBuilder, SendableEmail};
random_line_split
api.rs
use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use std::sync::{Arc, Mutex}; use super::enums::Token; use super::req::ShioriRequest; use super::res::ShioriResponse; use pasta_di::shiori::*; /// SHIORI構造体 #[derive(Debug)] pub struct Shiori { dao: Arc<Mutex<HaveShioriAPI>>, hinst: usi...
ut self) -> Result<(), ShioriError> { trace!("Shiori::unload"); Ok(()) } fn request(&mut self, req_text: &str) -> Result<Cow<str>, ShioriError> { trace!("Shiori::request"); let res = self.request_impl(req_text); let rc = match res { Ok(value) => value, ...
Shiori::load"); self.load_dir = Path::new(dir).to_path_buf(); Ok(()) } fn unload(&m
identifier_body
api.rs
use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use std::sync::{Arc, Mutex}; use super::enums::Token; use super::req::ShioriRequest; use super::res::ShioriResponse; use pasta_di::shiori::*; /// SHIORI構造体 #[derive(Debug)] pub struct Shiori { dao: Arc<Mutex<HaveShioriAPI>>, hinst: usi...
"SHIORI/3.0 204 No Content\r\n", "Charset: UTF-8\r\n", "\r\n", ); let res = shiori.request(req).unwrap(); assert_eq!(check, res); } { let req = concat!( "GET SHIORI/3.0\r\n", "Charset: UTF-8\r\n", "Sender: SS...
"\r\n", ); let check = concat!(
random_line_split
api.rs
use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use std::sync::{Arc, Mutex}; use super::enums::Token; use super::req::ShioriRequest; use super::res::ShioriResponse; use pasta_di::shiori::*; /// SHIORI構造体 #[derive(Debug)] pub struct Shiori { dao: Arc<Mutex<HaveShioriAPI>>, hinst: usi...
c>(&mut self, req_text: &'b str) -> Result<Cow<'c, str>, &'c str> { match ShioriRequest::from_str(req_text) { Err(reason) => { let text = format!("{:?}", reason); return Ok(ShioriResponse::bad_request(&text)); } Ok(req) => { if...
t_impl<'b, '
identifier_name
api.rs
use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use std::sync::{Arc, Mutex}; use super::enums::Token; use super::req::ShioriRequest; use super::res::ShioriResponse; use pasta_di::shiori::*; /// SHIORI構造体 #[derive(Debug)] pub struct Shiori { dao: Arc<Mutex<HaveShioriAPI>>, hinst: usi...
} Ok(ShioriResponse::no_content()) } } impl Drop for Shiori { fn drop(&mut self) { trace!("Shiori::drop\n{:?}", self); } } impl ShioriAPI for Shiori { fn load<STR: AsRef<OsStr> +?Sized>(&mut self, dir: &STR) -> Result<(), ShioriError> { trace!("Shiori::load"); sel...
let talk = r"\1\s[10]\0\s[0]やあ、元気?\e"; return Ok(ShioriResponse::talk(talk)); } }
conditional_block
solver.rs
use z3_sys::*; use Context; use Solver; use Model; use Ast; use Z3_MUTEX; impl<'ctx> Solver<'ctx> { pub fn new(ctx: &Context) -> Solver { Solver { ctx: ctx, z3_slv: unsafe { let guard = Z3_MUTEX.lock().unwrap(); let s = Z3_mk_solver(ctx.z3_ctx); ...
(&self) -> Model<'ctx> { Model::of_solver(self) } } impl<'ctx> Drop for Solver<'ctx> { fn drop(&mut self) { unsafe { let guard = Z3_MUTEX.lock().unwrap(); Z3_solver_dec_ref(self.ctx.z3_ctx, self.z3_slv); } } }
get_model
identifier_name
solver.rs
use z3_sys::*; use Context; use Solver; use Model; use Ast; use Z3_MUTEX; impl<'ctx> Solver<'ctx> { pub fn new(ctx: &Context) -> Solver { Solver { ctx: ctx, z3_slv: unsafe { let guard = Z3_MUTEX.lock().unwrap(); let s = Z3_mk_solver(ctx.z3_ctx);
} } } pub fn assert(&self, ast: &Ast<'ctx>) { unsafe { let guard = Z3_MUTEX.lock().unwrap(); Z3_solver_assert(self.ctx.z3_ctx, self.z3_slv, ast.z3_ast); } } pub fn check(&self) -> bool...
Z3_solver_inc_ref(ctx.z3_ctx, s); s
random_line_split
solver.rs
use z3_sys::*; use Context; use Solver; use Model; use Ast; use Z3_MUTEX; impl<'ctx> Solver<'ctx> { pub fn new(ctx: &Context) -> Solver { Solver { ctx: ctx, z3_slv: unsafe { let guard = Z3_MUTEX.lock().unwrap(); let s = Z3_mk_solver(ctx.z3_ctx); ...
pub fn get_model(&self) -> Model<'ctx> { Model::of_solver(self) } } impl<'ctx> Drop for Solver<'ctx> { fn drop(&mut self) { unsafe { let guard = Z3_MUTEX.lock().unwrap(); Z3_solver_dec_ref(self.ctx.z3_ctx, self.z3_slv); } } }
{ unsafe { let guard = Z3_MUTEX.lock().unwrap(); Z3_solver_check(self.ctx.z3_ctx, self.z3_slv) == Z3_TRUE } }
identifier_body
mod.rs
mod fclass; mod fenum; mod find_cache; mod finterface; mod java_code; mod map_class_self_type; mod map_type; mod rust_code; use log::debug; use proc_macro2::{Span, TokenStream}; use quote::quote; use rustc_hash::{FxHashMap, FxHashSet}; use smol_str::SmolStr; use std::{fmt, io::Write, path::PathBuf}; use syn::{spanned:...
} false }) .map_err(DiagnosticError::map_any_err_to_our_err)?; } Ok(ret) } fn post_proccess_code( &self, _conv_map: &mut TypeMap, _pointer_target_width: usize, mut generated_code: Vec<u8>, ) -> Result<Ve...
{ return true; }
conditional_block
mod.rs
mod fclass; mod fenum; mod find_cache; mod finterface; mod java_code; mod map_class_self_type; mod map_type; mod rust_code; use log::debug; use proc_macro2::{Span, TokenStream}; use quote::quote; use rustc_hash::{FxHashMap, FxHashSet}; use smol_str::SmolStr; use std::{fmt, io::Write, path::PathBuf}; use syn::{spanned:...
(method: &ForeignMethod, f_method: &JniForeignMethodSignature) -> String { let need_conv = f_method.input.iter().any(|v: &JavaForeignTypeInfo| { v.java_converter .as_ref() .map(|x|!x.converter.is_empty()) .unwrap_or(false) }) || f_method .output .java_conve...
method_name
identifier_name
mod.rs
mod fclass; mod fenum; mod find_cache; mod finterface; mod java_code; mod map_class_self_type; mod map_type; mod rust_code; use log::debug; use proc_macro2::{Span, TokenStream}; use quote::quote; use rustc_hash::{FxHashMap, FxHashSet}; use smol_str::SmolStr; use std::{fmt, io::Write, path::PathBuf}; use syn::{spanned:...
traits.push(SMART_PTR_COPY_TRAIT); } let this_type: RustType = ctx.conv_map.find_or_alloc_rust_type_that_implements( &this_type_for_method, &traits, class.src_id, ); if class.smart_ptr_copy_derived() { ...
{ class .validate_class() .map_err(|err| DiagnosticError::new(class.src_id, class.span(), &err))?; if let Some(self_desc) = class.self_desc.as_ref() { let constructor_ret_type = &self_desc.constructor_ret_type; let this_type_for_method = if_ty_result_retur...
identifier_body
mod.rs
mod fclass; mod fenum; mod find_cache; mod finterface; mod java_code; mod map_class_self_type; mod map_type; mod rust_code; use log::debug; use proc_macro2::{Span, TokenStream}; use quote::quote; use rustc_hash::{FxHashMap, FxHashSet}; use smol_str::SmolStr; use std::{fmt, io::Write, path::PathBuf}; use syn::{spanned:...
let mut ctx = JavaContext { cfg: self, conv_map, pointer_target_width, rust_code: &mut ret, generated_foreign_files: &mut generated_foreign_files, java_type_to_jni_sig_map: rust_code::predefined_java_type_to_jni_sig(), class_ext...
let mut generated_foreign_files = FxHashSet::default();
random_line_split
slack.rs
use std::io::{Read}; use getopts; use hyper::{Client}; use hyper::status::{StatusCode}; use rustc_serialize::{json}; use super::{CreateServiceResult, Service, ServiceFactory, GetUsersResult, GetUsersError, User}; #[derive(RustcDecodable)] struct SlackUserListResponse { ok: bool, members: Vec<SlackUser>, }...
{ token: String, } impl Service for SlackService { fn get_users(&self) -> Result<GetUsersResult, GetUsersError> { let client = Client::new(); let mut response = client.get( &format!("https://slack.com/api/users.list?token={}", self.token) ).send().unwrap(); assert_...
SlackService
identifier_name
slack.rs
use std::io::{Read}; use getopts; use hyper::{Client}; use hyper::status::{StatusCode}; use rustc_serialize::{json}; use super::{CreateServiceResult, Service, ServiceFactory, GetUsersResult, GetUsersError, User}; #[derive(RustcDecodable)] struct SlackUserListResponse { ok: bool, members: Vec<SlackUser>, }...
User{ name: user.name.to_string(), email: Some(user.profile.email.clone().unwrap()), details: match (user.is_owner.unwrap(), user.is_admin.unwrap()) { (true, true) => Some("Owner/Admin".to_string()), (true, false) => Som...
random_line_split
no_0093_restore_ip_addresses.rs
struct Solution; impl Solution { pub fn restore_ip_addresses(s: String) -> Vec<String> { let s = s.as_bytes(); let n = s.len(); let mut ans = Vec::new(); if n < 4 || n > 12 { return ans; } // i 表示在哪个索引位置放置 `.` // 每个 for 遍历最多 4 次。注意不要超出 n 的范围。 ...
n <= 255 } fn to_str(s: &[u8], i1: usize, i2: usize, i3: usize) -> String { let mut ans = String::with_capacity(s.len() + 3); ans.extend((&s[0..i1]).iter().map(|u| *u as char)); ans.push('.'); ans.extend((&s[i1..i2]).iter().map(|u| *u as char)); ans.push('.'); ...
|n, c| n * 10 + (*c - '0' as u8) as u32);
conditional_block
no_0093_restore_ip_addresses.rs
struct Solution; impl Solution { pub fn restore_ip_addresses(s: String) -> Vec<String> { let s = s.as_bytes(); let n = s.len(); let mut ans = Vec::new(); if n < 4 || n > 12 { return ans; } // i 表示在哪个索引位置放置 `.` // 每个 for 遍历最多 4 次。注意不要超出 n 的范围。 ...
city(s.len() + 3); ans.extend((&s[0..i1]).iter().map(|u| *u as char)); ans.push('.'); ans.extend((&s[i1..i2]).iter().map(|u| *u as char)); ans.push('.'); ans.extend((&s[i2..i3]).iter().map(|u| *u as char)); ans.push('.'); ans.extend((&s[i3..]).iter().map(|u| *u as...
s.len() > 3 { return false; } // 只有一个 0 可以,但 00/01 是不行的。 if s[0] == '0' as u8 { return s.len() == 1; } let n = s .iter() .fold(0 as u32, |n, c| n * 10 + (*c - '0' as u8) as u32); n <= 255 } fn to_str(s: &[u8], i1: ...
identifier_body
no_0093_restore_ip_addresses.rs
struct Solution; impl Solution { pub fn restore_ip_addresses(s: String) -> Vec<String> { let s = s.as_bytes(); let n = s.len(); let mut ans = Vec::new(); if n < 4 || n > 12 { return ans; } // i 表示在哪个索引位置放置 `.` // 每个 for 遍历最多 4 次。注意不要超出 n 的范围。 ...
assert_eq!(res, want); } }
random_line_split
no_0093_restore_ip_addresses.rs
struct Solution; impl Solution { pub fn restore_ip_addresses(s: String) -> Vec<String> { let s = s.as_bytes(); let n = s.len(); let mut ans = Vec::new(); if n < 4 || n > 12 { return ans; } // i 表示在哪个索引位置放置 `.` // 每个 for 遍历最多 4 次。注意不要超出 n 的范围。 ...
if s.len() == 0 || s.len() > 3 { return false; } // 只有一个 0 可以,但 00/01 是不行的。 if s[0] == '0' as u8 { return s.len() == 1; } let n = s .iter() .fold(0 as u32, |n, c| n * 10 + (*c - '0' as u8) as u32); n <= 255 } fn to_s...
identifier_name
flags.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use translate::*; use value::FromValue; use value::FromValueOptional; use value::SetValue; use value::Value; use StaticType; use Type; bitflags! { pub struct Bi...
() -> Type { unsafe { from_glib(gobject_sys::g_binding_flags_get_type()) } } } impl<'a> FromValueOptional<'a> for BindingFlags { unsafe fn from_value_optional(value: &Value) -> Option<Self> { Some(FromValue::from_value(value)) } } impl<'a> FromValue<'a> for BindingFlags { unsafe fn fro...
static_type
identifier_name
flags.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use translate::*; use value::FromValue; use value::FromValueOptional; use value::SetValue; use value::Value; use StaticType; use Type; bitflags! { pub struct Bi...
type GlibType = gobject_sys::GParamFlags; fn to_glib(&self) -> gobject_sys::GParamFlags { self.bits() } } #[doc(hidden)] impl FromGlib<gobject_sys::GParamFlags> for ParamFlags { fn from_glib(value: gobject_sys::GParamFlags) -> ParamFlags { ParamFlags::from_bits_truncate(value) } } ...
} #[doc(hidden)] impl ToGlib for ParamFlags {
random_line_split
flags.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use translate::*; use value::FromValue; use value::FromValueOptional; use value::SetValue; use value::Value; use StaticType; use Type; bitflags! { pub struct Bi...
} #[doc(hidden)] impl FromGlib<gobject_sys::GSignalFlags> for SignalFlags { fn from_glib(value: gobject_sys::GSignalFlags) -> SignalFlags { SignalFlags::from_bits_truncate(value) } }
{ self.bits() }
identifier_body
lib.rs
#[derive(PartialEq, Debug)] pub struct Shoe { pub size: i32, pub style: String, } pub fn
(shoes: Vec<Shoe>, shoe_size: i32) -> Vec<Shoe> { shoes.into_iter().filter(|s| s.size == shoe_size).collect() } #[test] fn filters_by_size() { let shoes = vec![Shoe { size: 10, style: String::from("sneaker"), }, Shoe { ...
shoe_in_my_size
identifier_name
lib.rs
#[derive(PartialEq, Debug)] pub struct Shoe { pub size: i32, pub style: String, } pub fn shoe_in_my_size(shoes: Vec<Shoe>, shoe_size: i32) -> Vec<Shoe> { shoes.into_iter().filter(|s| s.size == shoe_size).collect() } #[test] fn filters_by_size() { let shoes = vec![Shoe { size: ...
else { None } } } #[test] fn calling_next_directly() { let mut counter = Counter::new(); assert_eq!(counter.next(), Some(1)); assert_eq!(counter.next(), Some(2)); assert_eq!(counter.next(), Some(3)); assert_eq!(counter.next(), Some(4)); assert_eq!(counter.next(), Some(...
{ Some(self.count) }
conditional_block
lib.rs
#[derive(PartialEq, Debug)] pub struct Shoe { pub size: i32, pub style: String, } pub fn shoe_in_my_size(shoes: Vec<Shoe>, shoe_size: i32) -> Vec<Shoe> { shoes.into_iter().filter(|s| s.size == shoe_size).collect() } #[test] fn filters_by_size() { let shoes = vec![Shoe { size: ...
#[derive(Debug)] pub struct Counter { pub count: u32, } impl Counter { pub fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option<Self::Item> { self.count += 1; if self.count < 6 { Some(self.cou...
}]); }
random_line_split
lint-exceeding-bitshifts.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 ...
let n = 1u16 >> 15; let n = 1u16 >> 16; //~ ERROR: attempt to shift right with overflow let n = 1u32 >> 31; let n = 1u32 >> 32; //~ ERROR: attempt to shift right with overflow let n = 1u64 >> 63; let n = 1u64 >> 64; //~ ERROR: attempt to shift right with overflow let n = 1i8 >>...
{ let n = 1u8 << 7; let n = 1u8 << 8; //~ ERROR: attempt to shift left with overflow let n = 1u16 << 15; let n = 1u16 << 16; //~ ERROR: attempt to shift left with overflow let n = 1u32 << 31; let n = 1u32 << 32; //~ ERROR: attempt to shift left with overflow let n = 1u64 << 6...
identifier_body
lint-exceeding-bitshifts.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 ...
let n = 1u8 << -8; //~ ERROR: attempt to shift left with overflow let n = 1i8<<(1isize+-1); }
let n = n << 7; let n = n << 8; //~ ERROR: attempt to shift left with overflow
random_line_split
lint-exceeding-bitshifts.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 ...
() { let n = 1u8 << 7; let n = 1u8 << 8; //~ ERROR: attempt to shift left with overflow let n = 1u16 << 15; let n = 1u16 << 16; //~ ERROR: attempt to shift left with overflow let n = 1u32 << 31; let n = 1u32 << 32; //~ ERROR: attempt to shift left with overflow let n = 1u64 <...
main
identifier_name
linked_list.rs
use core::alloc::{GlobalAlloc, Layout}; use core::ptr::{self, NonNull}; use linked_list_allocator::Heap; use spin::Mutex; use crate::paging::{ActivePageTable, TableKind}; static HEAP: Mutex<Option<Heap>> = Mutex::new(None); pub struct Allocator; impl Allocator { pub unsafe fn
(offset: usize, size: usize) { *HEAP.lock() = Some(Heap::new(offset, size)); } } unsafe impl GlobalAlloc for Allocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { while let Some(ref mut heap) = *HEAP.lock() { match heap.allocate_first_fit(layout) { Err(()) ...
init
identifier_name
linked_list.rs
use core::alloc::{GlobalAlloc, Layout}; use core::ptr::{self, NonNull}; use linked_list_allocator::Heap; use spin::Mutex; use crate::paging::{ActivePageTable, TableKind}; static HEAP: Mutex<Option<Heap>> = Mutex::new(None); pub struct Allocator; impl Allocator { pub unsafe fn init(offset: usize, size: usize) { ...
} panic!("__rust_allocate: heap not initialized"); } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { if let Some(ref mut heap) = *HEAP.lock() { heap.deallocate(NonNull::new_unchecked(ptr), layout) } else { panic!("__rust_deallocate: heap not init...
super::map_heap(&mut ActivePageTable::new(TableKind::Kernel), crate::KERNEL_HEAP_OFFSET + size, crate::KERNEL_HEAP_SIZE); heap.extend(crate::KERNEL_HEAP_SIZE); }, other => return other.ok().map_or(ptr::null_mut(), |allocation| allocation.as_ptr()),...
random_line_split
linked_list.rs
use core::alloc::{GlobalAlloc, Layout}; use core::ptr::{self, NonNull}; use linked_list_allocator::Heap; use spin::Mutex; use crate::paging::{ActivePageTable, TableKind}; static HEAP: Mutex<Option<Heap>> = Mutex::new(None); pub struct Allocator; impl Allocator { pub unsafe fn init(offset: usize, size: usize) { ...
, other => return other.ok().map_or(ptr::null_mut(), |allocation| allocation.as_ptr()), } } panic!("__rust_allocate: heap not initialized"); } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { if let Some(ref mut heap) = *HEAP.lock() { heap...
{ let size = heap.size(); super::map_heap(&mut ActivePageTable::new(TableKind::Kernel), crate::KERNEL_HEAP_OFFSET + size, crate::KERNEL_HEAP_SIZE); heap.extend(crate::KERNEL_HEAP_SIZE); }
conditional_block
nounwind.rs
// Copyright 2017 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 ...
() { nounwind::bar(); // CHECK: @foo() unnamed_addr #0 // CHECK: @bar() unnamed_addr #0 // CHECK: attributes #0 = { {{.*}}nounwind{{.*}} } }
foo
identifier_name
nounwind.rs
// Copyright 2017 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 ...
{ nounwind::bar(); // CHECK: @foo() unnamed_addr #0 // CHECK: @bar() unnamed_addr #0 // CHECK: attributes #0 = { {{.*}}nounwind{{.*}} } }
identifier_body
nounwind.rs
// Copyright 2017 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 ...
#[no_mangle] pub fn foo() { nounwind::bar(); // CHECK: @foo() unnamed_addr #0 // CHECK: @bar() unnamed_addr #0 // CHECK: attributes #0 = { {{.*}}nounwind{{.*}} } }
extern crate nounwind;
random_line_split
index_mut.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::ops::Index; use core::ops::IndexMut; struct Pixel<T> { r: T, g: T, b: T } impl Index<usize> for Pixel<T> { type Output = T; fn index<'a>(&'a self, index: usize) -> &'a Self::Output { match index { 0 => &self....
pixel[2] = 0x58; assert_eq!(pixel[0], 0x01); assert_eq!(pixel[1], 0x98); assert_eq!(pixel[2], 0x58); assert_eq!(pixel[3], 0x58); } }
random_line_split
index_mut.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::ops::Index; use core::ops::IndexMut; struct Pixel<T> { r: T, g: T, b: T } impl Index<usize> for Pixel<T> { type Output = T; fn index<'a>(&'a self, index: usize) -> &'a Self::Output { match index { 0 => &self....
<'a>(&'a mut self, index: usize) -> &'a mut Self::Output { match index { 0 => &mut self.r, 1 => &mut self.g, 2 | _ => &mut self.b } } } type T = u8; #[test] fn index_test1() { let mut pixel: Pixel<T> = Pixel { r: 0xff, g: 0x92, b: 0x24 }; pixel[0] = 0x01; pixel[1] = 0x98; ...
index_mut
identifier_name
pagerank.rs
// extern crate rand; // extern crate time; // extern crate columnar; // extern crate timely; // extern crate differential_dataflow; // // use std::mem; // // use std::hash::Hash; // use timely::example_shared::*; // use timely::example_shared::operators::*; // use timely::communication::ThreadCommunicator; // // use r...
// // // let mut sent = 0; // // let mut buffer = Vec::new(); // // let mut offset = nodes.read_u64::<LittleEndian>().unwrap(); // // assert!(offset == 0); // // for node in (0..60000000) { // // let read = nodes.read_u64::<LittleEndian>().unwr...
{ // // let start = time::precise_time_s(); // let start2 = start.clone(); // let mut computation = GraphRoot::new(ThreadCommunicator); // // let mut input = computation.subcomputation(|builder| { // // let (input, mut edges) = builder.new_input(); // // ...
identifier_body
pagerank.rs
// extern crate rand; // extern crate time; // extern crate columnar; // extern crate timely; // extern crate differential_dataflow; // // use std::mem; // // use std::hash::Hash; // use timely::example_shared::*; // use timely::example_shared::operators::*; // use timely::communication::ThreadCommunicator; // // use r...
// input.send_at(0, (0..next).map(|_| ((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes)), 1))); // computation.step(); // left -= next; // } // // println!("input ingested after {}", time::precise_time_s() - start); // // // ...
// // let mut left = edges; // while left > 0 { // let next = if left < 1000 { left } else { 1000 };
random_line_split
pagerank.rs
// extern crate rand; // extern crate time; // extern crate columnar; // extern crate timely; // extern crate differential_dataflow; // // use std::mem; // // use std::hash::Hash; // use timely::example_shared::*; // use timely::example_shared::operators::*; // use timely::communication::ThreadCommunicator; // // use r...
() { // // let start = time::precise_time_s(); // let start2 = start.clone(); // let mut computation = GraphRoot::new(ThreadCommunicator); // // let mut input = computation.subcomputation(|builder| { // // let (input, mut edges) = builder.new_input(); // /...
main
identifier_name
io.rs
//! SOLID-specific extensions to general I/O primitives #![deny(unsafe_op_in_unsafe_fn)] #![unstable(feature = "solid_ext", issue = "none")] use crate::net; use crate::sys; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; /// Raw file descriptors. pub type RawFd = i32; /// A trait to extract the raw SO...
} #[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")] impl FromRawFd for RawFd { #[inline] unsafe fn from_raw_fd(fd: RawFd) -> RawFd { fd } } macro_rules! impl_as_raw_fd { ($($t:ident)*) => {$( #[stable(feature = "rust1", since = "1.0.0")] impl AsRawFd for net::$t ...
{ self }
identifier_body
io.rs
//! SOLID-specific extensions to general I/O primitives #![deny(unsafe_op_in_unsafe_fn)] #![unstable(feature = "solid_ext", issue = "none")] use crate::net; use crate::sys; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; /// Raw file descriptors. pub type RawFd = i32; /// A trait to extract the raw SO...
} } #[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")] impl FromRawFd for RawFd { #[inline] unsafe fn from_raw_fd(fd: RawFd) -> RawFd { fd } } macro_rules! impl_as_raw_fd { ($($t:ident)*) => {$( #[stable(feature = "rust1", since = "1.0.0")] impl AsRawFd for net...
impl IntoRawFd for RawFd { #[inline] fn into_raw_fd(self) -> RawFd { self
random_line_split
io.rs
//! SOLID-specific extensions to general I/O primitives #![deny(unsafe_op_in_unsafe_fn)] #![unstable(feature = "solid_ext", issue = "none")] use crate::net; use crate::sys; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; /// Raw file descriptors. pub type RawFd = i32; /// A trait to extract the raw SO...
(&self) -> RawFd { *self } } #[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")] impl IntoRawFd for RawFd { #[inline] fn into_raw_fd(self) -> RawFd { self } } #[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")] impl FromRawFd for RawFd { #[inline] unsafe...
as_raw_fd
identifier_name
index.rs
extern crate iron; extern crate staticfile; extern crate mount; use iron::{status, Iron, Request, Response, IronResult, IronError}; use iron::mime::Mime; use staticfile::Static; use mount::Mount; use std::process::{Command, Output}; use std::error::Error; #[derive(Debug)] struct ServerError(String); impl ::std::fmt...
{ let mut root = Mount::new(); root.mount("/", Static::new("../")) .mount("/server", serve); Iron::new(root).http("localhost:8081").unwrap(); }
identifier_body
index.rs
extern crate iron; extern crate staticfile; extern crate mount; use iron::{status, Iron, Request, Response, IronResult, IronError}; use iron::mime::Mime; use staticfile::Static; use mount::Mount; use std::process::{Command, Output}; use std::error::Error; #[derive(Debug)] struct ServerError(String); impl ::std::fmt...
(s: &'static str) -> ServerError { ServerError(s.to_owned()) } } fn serve(req: &mut Request) -> IronResult<Response> { match req.url.query { Some(ref param) if param.starts_with("module=") => { let module = &param[7..]; match Command::new(format!("modules/shell_files/{}.sh", module)...
from
identifier_name
index.rs
extern crate iron; extern crate staticfile; extern crate mount; use iron::{status, Iron, Request, Response, IronResult, IronError}; use iron::mime::Mime; use staticfile::Static; use mount::Mount; use std::process::{Command, Output}; use std::error::Error; #[derive(Debug)] struct ServerError(String); impl ::std::fmt...
} fn serve(req: &mut Request) -> IronResult<Response> { match req.url.query { Some(ref param) if param.starts_with("module=") => { let module = &param[7..]; match Command::new(format!("modules/shell_files/{}.sh", module)).output() { Ok(Output { stdout,.. }) => Ok(Res...
fn from(s: &'static str) -> ServerError { ServerError(s.to_owned()) }
random_line_split
diff.rs
use ansi_term::{ANSIStrings, Style}; use ansi_term::Colour::{Green, Red}; use config::use_ansi; use diff; use std::borrow::Borrow; use std::cmp::max; use std::fmt::{Debug, Write}; use unicode_width::UnicodeWidthStr; /// Can be diffed pub trait Diffable<T:?Sized>: PartialEq<T> { fn diff(&self, to: &T) -> St...
<A:?Sized + Diffable<To>, To:?Sized>() {} _assert::<str, str>(); _assert::<String, str>(); _assert::<Vec<u8>, Vec<u8>>(); _assert::<Vec<u8>, Vec<u8>>(); _assert::<[u8; 4], [u8; 4]>(); _assert::<Vec<&str>, Vec<&str>>(); }
_assert
identifier_name
diff.rs
use ansi_term::{ANSIStrings, Style}; use ansi_term::Colour::{Green, Red}; use config::use_ansi; use diff; use std::borrow::Borrow; use std::cmp::max; use std::fmt::{Debug, Write}; use unicode_width::UnicodeWidthStr; /// Can be diffed pub trait Diffable<T:?Sized>: PartialEq<T> { fn diff(&self, to: &T) -> St...
} buf } impl Diffable<str> for str { fn diff(&self, to: &str) -> String { diff_str(self, to) } } impl Diffable<str> for String { fn diff(&self, to: &str) -> String { diff_str(self, to) } } impl<'a, 'b> Diffable<&'b str> for &'a str { fn diff(&self, to: &&str) -> String { diff_str(s...
}
random_line_split
diff.rs
use ansi_term::{ANSIStrings, Style}; use ansi_term::Colour::{Green, Red}; use config::use_ansi; use diff; use std::borrow::Borrow; use std::cmp::max; use std::fmt::{Debug, Write}; use unicode_width::UnicodeWidthStr; /// Can be diffed pub trait Diffable<T:?Sized>: PartialEq<T> { fn diff(&self, to: &T) -> St...
diff::Result::Both(..) => i += 1, diff::Result::Right(r) => { right_diffs.push((i, r)); i += 1; } } } let mut lmax = 3; let mut rmax = 8; let mut buf = String::new(); for (&(_, l), &(_, r)) in left_diffs.as_slice().iter().zip(right_diffs.as_slice().iter()) { write!(buf, "{:?...
{ left_diffs.push((i, l)); }
conditional_block
diff.rs
use ansi_term::{ANSIStrings, Style}; use ansi_term::Colour::{Green, Red}; use config::use_ansi; use diff; use std::borrow::Borrow; use std::cmp::max; use std::fmt::{Debug, Write}; use unicode_width::UnicodeWidthStr; /// Can be diffed pub trait Diffable<T:?Sized>: PartialEq<T> { fn diff(&self, to: &T) -> St...
} lazy_static!{ static ref DIFF_LEFT: Style = { if use_ansi() { Style::new().fg(Red) } else { Style::new() } }; static ref DIFF_RIGHT: Style = { if use_ansi() { Style::new().fg(Green) } else { Style:...
{ diff_str(self, to) }
identifier_body
main.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 ...
{ task::try(proc() { let _a = A; lib::callback(|| fail!()); 1i }); unsafe { assert!(lib::statik == 1); assert!(statik == 1); } }
identifier_body
main.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate lib; use std::task; static mut statik: int = 0; struct A; impl Drop for ...
// 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
random_line_split
main.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 ...
(&mut self) { unsafe { statik = 1; } } } fn main() { task::try(proc() { let _a = A; lib::callback(|| fail!()); 1i }); unsafe { assert!(lib::statik == 1); assert!(statik == 1); } }
drop
identifier_name
lib.rs
#![warn(rust_2018_idioms)] #[macro_use] extern crate tracing; use std::collections::hash_map::{Entry, HashMap}; use conduit::{box_error, Handler, HandlerResult, Method, RequestExt}; use route_recognizer::{Match, Params, Router}; #[derive(Default)] pub struct RouteBuilder { routers: HashMap<Method, Router<Wrappe...
} }; // We don't have `pub` access to the fields to destructure `Params`, so swap with an empty // value to avoid an allocation. let mut params = Params::new(); std::mem::swap(m.params_mut(), &mut params); let pattern = m.handler().pattern; debug!(p...
{ info!("{}", e); return Err(box_error(e)); }
conditional_block
lib.rs
#![warn(rust_2018_idioms)] #[macro_use] extern crate tracing; use std::collections::hash_map::{Entry, HashMap}; use conduit::{box_error, Handler, HandlerResult, Method, RequestExt}; use route_recognizer::{Match, Params, Router}; #[derive(Default)] pub struct RouteBuilder { routers: HashMap<Method, Router<Wrappe...
impl conduit::Handler for WrappedHandler { fn call(&self, request: &mut dyn RequestExt) -> HandlerResult { self.handler.call(request) } } #[derive(Debug, thiserror::Error)] pub enum RouterError { #[error("Invalid method")] UnknownMethod, #[error("Path not found")] PathNotFound, } impl...
struct WrappedHandler { pattern: RoutePattern, handler: Box<dyn Handler>, }
random_line_split
lib.rs
#![warn(rust_2018_idioms)] #[macro_use] extern crate tracing; use std::collections::hash_map::{Entry, HashMap}; use conduit::{box_error, Handler, HandlerResult, Method, RequestExt}; use route_recognizer::{Match, Params, Router}; #[derive(Default)] pub struct RouteBuilder { routers: HashMap<Method, Router<Wrappe...
<H: Handler>( &mut self, method: Method, pattern: &'static str, handler: H, ) -> &mut Self { { let router = match self.routers.entry(method) { Entry::Occupied(e) => e.into_mut(), Entry::Vacant(e) => e.insert(Router::new()), ...
map
identifier_name
buffer_tests.rs
//! Tests for `IBuffer`. use buffer::IBuffer; use std::io::Read; #[test] fn read_from_string() { let mut in_buf = IBuffer::from_str("Hello world"); let mut buf = [0u8; 6]; let res = in_buf.read(&mut buf); assert_eq!(6, res.expect("read must be ok")); assert_eq!([b'H', b'e', b'l', b'l', b'o', b' ...
() { let mut in_buf = IBuffer::from_str("Hello world"); let mut buf = [0u8; 6]; let _ = in_buf.read(&mut buf); let _ = in_buf.read(&mut buf); let res = in_buf.read(&mut buf); assert_eq!(0, res.expect("read must be ok")); }
read_from_string_eof
identifier_name
buffer_tests.rs
//! Tests for `IBuffer`. use buffer::IBuffer; use std::io::Read; #[test] fn read_from_string() { let mut in_buf = IBuffer::from_str("Hello world"); let mut buf = [0u8; 6]; let res = in_buf.read(&mut buf); assert_eq!(6, res.expect("read must be ok")); assert_eq!([b'H', b'e', b'l', b'l', b'o', b' ...
} #[test] fn read_from_string_eof() { let mut in_buf = IBuffer::from_str("Hello world"); let mut buf = [0u8; 6]; let _ = in_buf.read(&mut buf); let _ = in_buf.read(&mut buf); let res = in_buf.read(&mut buf); assert_eq!(0, res.expect("read must be ok")); }
assert_eq!(5, res.expect("read must be ok")); assert_eq!([b'w', b'o', b'r', b'l', b'd'], buf[0..5]);
random_line_split
buffer_tests.rs
//! Tests for `IBuffer`. use buffer::IBuffer; use std::io::Read; #[test] fn read_from_string()
#[test] fn read_from_string_overflow() { let mut in_buf = IBuffer::from_str("Hello world"); let mut buf = [0u8; 6]; let _ = in_buf.read(&mut buf); let res = in_buf.read(&mut buf); assert_eq!(5, res.expect("read must be ok")); assert_eq!([b'w', b'o', b'r', b'l', b'd'], buf[0..5]); } #[test] ...
{ let mut in_buf = IBuffer::from_str("Hello world"); let mut buf = [0u8; 6]; let res = in_buf.read(&mut buf); assert_eq!(6, res.expect("read must be ok")); assert_eq!([b'H', b'e', b'l', b'l', b'o', b' '], buf); }
identifier_body
no.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 base::prelude::*; use base::{error}; use {MemPool}; /// Heap without memory backing it /// /// = Remarks /// ///...
unsafe fn free(&mut self, _: *mut d8, _: usize, _: usize) { } unsafe fn realloc(&mut self, _: *mut d8, _: usize, _: usize, _: usize) -> Result<*mut d8> { Err(error::NoMemory) } }
{ Err(error::NoMemory) }
identifier_body
no.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 base::prelude::*; use base::{error}; use {MemPool}; /// Heap without memory backing it /// /// = Remarks /// ///...
(&mut self, _: usize, _: usize) -> Result<*mut d8> { Err(error::NoMemory) } unsafe fn free(&mut self, _: *mut d8, _: usize, _: usize) { } unsafe fn realloc(&mut self, _: *mut d8, _: usize, _: usize, _: usize) -> Result<*mut d8> { Err(error::NoMemory) } }
alloc
identifier_name
no.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 base::prelude::*; use base::{error}; use {MemPool}; /// Heap without memory backing it ///
/// memory is available. pub struct Dummy<'a>(PhantomData<&'a ()>); impl<'a> OutOf for Dummy<'a> { fn out_of(_: ()) -> Dummy<'a> { Dummy(PhantomData) } } impl<'a> MemPool for Dummy<'a> { unsafe fn alloc(&mut self, _: usize, _: usize) -> Result<*mut d8> { Err(error::NoMemory) } unsa...
/// = Remarks /// /// This allocator does not inspect the arguments passed to it and always returns that no
random_line_split
lib.rs
// Copyright 2013-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-MI...
} } /// Terminal color definitions pub mod color { /// Number for a terminal color pub type Color = u16; pub const BLACK: Color = 0; pub const RED: Color = 1; pub const GREEN: Color = 2; pub const YELLOW: Color = 3; pub const BLUE: Color = 4; pub const MAGENTA: Color ...
{ WinConsole::new(WriterWrapper { wrapped: box std::old_io::stderr() as Box<Writer + Send>, }) }
conditional_block
lib.rs
// Copyright 2013-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-MI...
{ wrapped: Box<Writer + Send>, } impl Writer for WriterWrapper { #[inline] fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.wrapped.write_all(buf) } #[inline] fn flush(&mut self) -> IoResult<()> { self.wrapped.flush() } } #[cfg(not(windows))] /// Return a Termin...
WriterWrapper
identifier_name
lib.rs
// Copyright 2013-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-MI...
pub const BRIGHT_GREEN: Color = 10; pub const BRIGHT_YELLOW: Color = 11; pub const BRIGHT_BLUE: Color = 12; pub const BRIGHT_MAGENTA: Color = 13; pub const BRIGHT_CYAN: Color = 14; pub const BRIGHT_WHITE: Color = 15; } /// Terminal attributes pub mod attr { pub use self::Attr::*;...
random_line_split
local.rs
//! UDP relay local server use std::{ io::{self, Cursor, ErrorKind, Read}, net::{IpAddr, Ipv4Addr, SocketAddr}, sync::{Arc, Mutex}, time::Duration, }; use futures::{self, Future, Stream}; use log::{debug, error, info}; use tokio::{self, net::UdpSocket, util::FutureExt}; use crate::{ config::{Serv...
Err(err) } else { Ok((cur, header.address)) } }) .and_then(|(mut cur, addr)| { let svr_cfg = svr_cfg_cloned_cloned; let mut payload = Vec::new(); cur.read_to_end(&mut payload)....
{ let socket = Arc::new(Mutex::new(l)); let mut balancer = RoundRobin::new(context.config()); PacketStream::new(socket.clone()).for_each(move |(pkt, src)| { let svr_cfg = balancer.pick_server(); let svr_cfg_cloned = svr_cfg.clone(); let svr_cfg_cloned_cloned = svr_cfg.clone(); ...
identifier_body
local.rs
//! UDP relay local server use std::{ io::{self, Cursor, ErrorKind, Read}, net::{IpAddr, Ipv4Addr, SocketAddr}, sync::{Arc, Mutex}, time::Duration, }; use futures::{self, Future, Stream}; use log::{debug, error, info}; use tokio::{self, net::UdpSocket, util::FutureExt}; use crate::{ config::{Serv...
let mut payload = Vec::new(); cur.read_to_end(&mut payload).unwrap(); resolve_server_addr(context, svr_cfg) .and_then(|remote_addr| { let local_addr = SocketAddr::new(IpAddr::from(Ipv4Addr::new(0, 0, 0, 0)), 0); ...
Ok((cur, header.address)) } }) .and_then(|(mut cur, addr)| { let svr_cfg = svr_cfg_cloned_cloned;
random_line_split
local.rs
//! UDP relay local server use std::{ io::{self, Cursor, ErrorKind, Read}, net::{IpAddr, Ipv4Addr, SocketAddr}, sync::{Arc, Mutex}, time::Duration, }; use futures::{self, Future, Stream}; use log::{debug, error, info}; use tokio::{self, net::UdpSocket, util::FutureExt}; use crate::{ config::{Serv...
( context: SharedContext, svr_cfg: Arc<ServerConfig>, ) -> impl Future<Item = SocketAddr, Error = io::Error> + Send { match *svr_cfg.addr() { // Return directly if it is a SocketAddr ServerAddr::SocketAddr(ref addr) => boxed_future(futures::finished(*addr)), // Resolve domain name to...
resolve_server_addr
identifier_name
match-static-const-lc.rs
// Copyright 2012-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-MI...
fn main () { f(); g(); h(); }
{ use self::n::OKAY as not_okay; let r = match (0,0) { (0, not_okay) => 0, //~^ ERROR static constant in pattern `not_okay` should have an uppercase name such as `NOT_OKAY` (x, y) => 1 + x + y, }; assert!(r == 1); }
identifier_body
match-static-const-lc.rs
// Copyright 2012-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-MI...
() { use self::m::aha; let r = match (0,0) { (0, aha) => 0, //~^ ERROR static constant in pattern `aha` should have an uppercase name such as `AHA` (x, y) => 1 + x + y, }; assert!(r == 1); } mod n { pub const OKAY : int = 8; } fn h() { use self::n::OKAY as not_okay; ...
g
identifier_name
match-static-const-lc.rs
// Copyright 2012-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-MI...
assert!(r == 1); } mod m { #[allow(non_uppercase_statics)] pub const aha : int = 7; } fn g() { use self::m::aha; let r = match (0,0) { (0, aha) => 0, //~^ ERROR static constant in pattern `aha` should have an uppercase name such as `AHA` (x, y) => 1 + x + y, }; as...
let r = match (0,0) { (0, a) => 0, //~^ ERROR static constant in pattern `a` should have an uppercase name such as `A` (x, y) => 1 + x + y, };
random_line_split
polygon.rs
use crate::Direction; use crate::{ fragment::{ marker_line::{Marker, MarkerLine}, Bounds, }, Cell, Point, }; use nalgebra::Point2; use ncollide2d::shape::{shape::Shape, Polyline}; use sauron::{ svg::{attributes::*, *}, Node, }; use std::{cmp::Ordering, fmt, ops::Deref}; #[derive(Deb...
(&self, other: &Self) -> Ordering { if self.points == other.points { Ordering::Equal } else { self.first() .cmp(&other.first()) .then(self.last().cmp(&other.last())) .then(self.is_filled.cmp(&other.is_filled)) .then(self...
cmp
identifier_name
polygon.rs
use crate::Direction; use crate::{ fragment::{ marker_line::{Marker, MarkerLine}, Bounds, }, Cell, Point, }; use nalgebra::Point2; use ncollide2d::shape::{shape::Shape, Polyline}; use sauron::{ svg::{attributes::*, *}, Node, }; use std::{cmp::Ordering, fmt, ops::Deref}; #[derive(Deb...
impl PartialEq for Polygon { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } }
random_line_split
polygon.rs
use crate::Direction; use crate::{ fragment::{ marker_line::{Marker, MarkerLine}, Bounds, }, Cell, Point, }; use nalgebra::Point2; use ncollide2d::shape::{shape::Shape, Polyline}; use sauron::{ svg::{attributes::*, *}, Node, }; use std::{cmp::Ordering, fmt, ops::Deref}; #[derive(Deb...
} impl Polygon { pub(in crate) fn new(points: Vec<Point>, is_filled: bool, tags: Vec<PolygonTag>) -> Self { Polygon { points, is_filled, tags, } } pub(in crate) fn absolute_position(&self, cell: Cell) -> Self { let points: Vec<Point> = self ...
{ if let Some(direction) = self.direction() { direction == arg } else { // DiamondBullet just match any direction true } }
identifier_body
fatdbmut.rs
// Copyright 2015, 2016 Ethcore (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 later version....
(&mut self, key: &[u8]) -> super::Result<()> { let hash = key.sha3(); self.raw.db_mut().remove(&Self::to_aux_key(&hash)); self.raw.remove(&hash) } } #[test] fn fatdb_to_trie() { use memorydb::MemoryDB; use super::TrieDB; use super::Trie; let mut memdb = MemoryDB::new(); let mut root = H256::default(); { ...
remove
identifier_name
fatdbmut.rs
// Copyright 2015, 2016 Ethcore (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 later version....
fn insert(&mut self, key: &[u8], value: &[u8]) -> super::Result<()> { let hash = key.sha3(); try!(self.raw.insert(&hash, value)); let db = self.raw.db_mut(); db.emplace(Self::to_aux_key(&hash), DBValue::from_slice(key)); Ok(()) } fn remove(&mut self, key: &[u8]) -> super::Result<()> { let hash = key.s...
{ self.raw.get(&key.sha3()) }
identifier_body
fatdbmut.rs
// 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 later version. // Parity is distributed in the hope that it will be useful, // but WITH...
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity.
random_line_split
min_max.rs
extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::MinMaxResult::{self, NoElements, OneElement, MinMax}; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Optio...
#![feature(core)]
random_line_split
min_max.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::MinMaxResult::{self, NoElements, OneElement, MinMax}; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&...
() { let a: A<T> = A { begin: 3, end: 9 }; let min_max: MinMaxResult<Item> = a.min_max(); assert_eq!(min_max, MinMax::<Item>(3, 8)); } }
min_max_test3
identifier_name
create.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 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 ...
fn create_id_from_clispec(create: &ArgMatches, diaryname: &str, timed_type: Timed) -> DiaryId { use std::str::FromStr; let get_hourly_id = |create: &ArgMatches| -> DiaryId { let time = DiaryId::now(String::from(diaryname)); let hr = create .value_of("hour") .map(|v| { debu...
random_line_split
create.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 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 ...
else { debug!("Editing new diary entry"); entry.edit_content(rt) .chain_err(|| DEK::DiaryEditError) }; if let Err(e) = res { trace_error_exit(&e, 1); } else { info!("Ok!"); } } fn create_entry<'a>(diary: &'a Store, diaryname: &str, rt: &Runtime) -> FileLockE...
{ debug!("Not editing new diary entry"); Ok(()) }
conditional_block
create.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 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 ...
(rt: &Runtime) { let diaryname = get_diary_name(rt) .unwrap_or_else( || warn_exit("No diary selected. Use either the configuration file or the commandline option", 1)); let mut entry = create_entry(rt.store(), &diaryname, rt); let res = if rt.cli().subcommand_matches("create").unwrap().is_present("...
create
identifier_name
create.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 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 ...
let id = create_id_from_clispec(&create, &diaryname, timed); diary.retrieve(id).chain_err(|| DEK::StoreReadError) }, None => { debug!("Creating non-timed entry"); diary.new_entry_today(diaryname) } }; match entry { Err(e) => trace...
{ use util::parse_timed_string; let create = rt.cli().subcommand_matches("create").unwrap(); let create_timed = create.value_of("timed") .map(|t| parse_timed_string(t, diaryname).map_err_trace_exit_unwrap(1)) .map(Some) .unwrap_or_else(|| match get_diary_timed_config(rt, diaryname)...
identifier_body
lib.rs
use blocking::unblock; use futures::lock::Mutex; use futures::{Future, TryStreamExt}; use futures_timer::Delay; use log::trace; use mobc::{async_trait, Manager}; use reql::cmd::connect::Options; use reql::cmd::run::{self, Arg}; use reql::types::{Change, ServerStatus}; use reql::{r, Command, Connection, Driver, Error, R...
fn to_reql(error: mobc::Error<Error>) -> Error { match error { mobc::Error::Inner(error) => error, mobc::Error::Timeout => io::Error::from(io::ErrorKind::TimedOut).into(), mobc::Error::BadConn => Driver::ConnectionBroken.into(), } }
{ if res != msg { return Err(Driver::ConnectionBroken.into()); } Ok(()) }
identifier_body
lib.rs
use blocking::unblock; use futures::lock::Mutex; use futures::{Future, TryStreamExt}; use futures_timer::Delay; use log::trace; use mobc::{async_trait, Manager}; use reql::cmd::connect::Options; use reql::cmd::run::{self, Arg}; use reql::types::{Change, ServerStatus}; use reql::{r, Command, Connection, Driver, Error, R...
type Connection = reql::Session; type Error = Error; async fn connect(&self) -> Result<Self::Connection> { let opts = &self.opts; let servers = &self.servers.lock().await; if servers.is_empty() { trace!( "no discovered servers; host: {}, port: {}", ...
random_line_split
lib.rs
use blocking::unblock; use futures::lock::Mutex; use futures::{Future, TryStreamExt}; use futures_timer::Delay; use log::trace; use mobc::{async_trait, Manager}; use reql::cmd::connect::Options; use reql::cmd::run::{self, Arg}; use reql::types::{Change, ServerStatus}; use reql::{r, Command, Connection, Driver, Error, R...
(&self) -> Result<Session> { Ok(Session { conn: self.get().await.map_err(to_reql)?, }) } } pub struct Session { conn: mobc::Connection<SessionManager>, } impl Deref for Session { type Target = reql::Session; fn deref(&self) -> &Self::Target { &self.conn } } im...
session
identifier_name
grain.rs
/* * Copyright (C) 2012 The Android Open Source Project * * 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 app...
p.a = 0xff; *out = p; }
random_line_split
error.rs
use std::{self, io, net, str}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { Io(io::Error), Utf8(str::Utf8Error), Addr(net::AddrParseError), /// `224.0.0.0` ~ `239.255.255.255` /// // `ff00::/8` IpIsMulticast, /// `0.0.0.0` IpIsUnspecified, ...
} impl From<str::Utf8Error> for Error { fn from(e: str::Utf8Error) -> Self { Error::Utf8(e) } } impl From<net::AddrParseError> for Error { fn from(e: net::AddrParseError) -> Self { Error::Addr(e) } }
{ Error::Io(e) }
identifier_body
error.rs
use std::{self, io, net, str}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { Io(io::Error), Utf8(str::Utf8Error), Addr(net::AddrParseError), /// `224.0.0.0` ~ `239.255.255.255` /// // `ff00::/8` IpIsMulticast, /// `0.0.0.0` IpIsUnspecified, ...
NotFound, } impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::Io(e) } } impl From<str::Utf8Error> for Error { fn from(e: str::Utf8Error) -> Self { Error::Utf8(e) } } impl From<net::AddrParseError> for Error { fn from(e: net::AddrParseError) -> Self { ...
///3. `192.168.0.0/16` IpIsPrivate, /// Unsupport Ipv6 Now UnsupportIpv6,
random_line_split
error.rs
use std::{self, io, net, str}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { Io(io::Error), Utf8(str::Utf8Error), Addr(net::AddrParseError), /// `224.0.0.0` ~ `239.255.255.255` /// // `ff00::/8` IpIsMulticast, /// `0.0.0.0` IpIsUnspecified, ...
(e: io::Error) -> Self { Error::Io(e) } } impl From<str::Utf8Error> for Error { fn from(e: str::Utf8Error) -> Self { Error::Utf8(e) } } impl From<net::AddrParseError> for Error { fn from(e: net::AddrParseError) -> Self { Error::Addr(e) } }
from
identifier_name
errors.rs
//! The rpeek library. //! //! # License //! //! Copyright (c) 2015 by Stacy Prowell. All rights reserved. //! //! Licensed under the BSD 2-Clause license. See the file LICENSE //! that is part of this distribution. This file may not be copied, //! modified, or distributed except according to those terms. use std; ...
} /// Define the kind of errors that can occur when parsing. pub type ParseResult<T> = std::result::Result<T, ParseError>;
Stalled, /// A general IO error happened. IOError(std::io::Error), /// Some other error happened. OtherError(Box<std::error::Error>),
random_line_split
errors.rs
//! The rpeek library. //! //! # License //! //! Copyright (c) 2015 by Stacy Prowell. All rights reserved. //! //! Licensed under the BSD 2-Clause license. See the file LICENSE //! that is part of this distribution. This file may not be copied, //! modified, or distributed except according to those terms. use std; ...
{ /// Lookahead value specified is too large. This occurs when the user asks to peek ahead /// too far. LookaheadTooLarge, /// Reading seems to have stalled at the end of file. StalledAtEof, /// Reading has stalled with no forward progress. Stalled, /// A general IO error happened. ...
ParseError
identifier_name
main.rs
extern crate rand; extern crate time; use std::io; use std::f64; use std::io::prelude::*; fn trapezoids_v1<F>(data: (f64, f64, i64), f: F) -> f64 where F: Fn(f64) -> f64 { let (a, b, n) = data; let mut sum: f64 = 0.0; let h = (b - a) / n as f64; let xk = |k: i64| a + k as f64 * h; for i in 0..n...
fn simpson<F>(data: (f64, f64), f: F) -> f64 where F: Fn(f64) -> f64 { let (a, b) = data; ((b - a) / 6.0) * (f(a) + 4.0 * f(0.5 * (a + b)) + f(b)) } fn simpson_kosates<F>(data: (f64, f64, i64), f: F) -> f64 where F: Fn(f64) -> f64 { let (a, b, n) = data; let h = (b - a) / n as f64; let xk...
{ let (mut s_left, mut s_middle, mut s_right) = (0.0, 0.0, 0.0); let rectangle_left = |x0: f64, x1: f64| f(x0) * (x1 - x0); let rectangle_middle = |x0: f64, x1: f64| f(0.5 * (x0 + x1)) * (x1 - x0); let rectangle_right = |x0: f64, x1: f64| f(x0) * (x0 - x1); let (a, b, n) = data; let h = (b - a) ...
identifier_body
main.rs
extern crate rand; extern crate time; use std::io; use std::f64; use std::io::prelude::*; fn trapezoids_v1<F>(data: (f64, f64, i64), f: F) -> f64 where F: Fn(f64) -> f64 { let (a, b, n) = data; let mut sum: f64 = 0.0; let h = (b - a) / n as f64; let xk = |k: i64| a + k as f64 * h; for i in 0..n...
<F>(data: (f64, f64, i64), f: F) -> f64 where F: Fn(f64) -> f64 { use rand::distributions::{IndependentSample, Range}; use rand::thread_rng; let (a, b, n) = data; let between = Range::new(a, b); let mut rng = rand::thread_rng(); let mut sum = 0.0; for _ in 0..n { let x = between....
monte_carlo
identifier_name
main.rs
extern crate rand; extern crate time; use std::io; use std::f64; use std::io::prelude::*; fn trapezoids_v1<F>(data: (f64, f64, i64), f: F) -> f64 where F: Fn(f64) -> f64 { let (a, b, n) = data; let mut sum: f64 = 0.0; let h = (b - a) / n as f64; let xk = |k: i64| a + k as f64 * h; for i in 0..n...
let (a, b) = (0.0, 1.0); let mut buffer = String::new(); print!("Enter iteration count: "); io::stdout() .flush() .expect("Couldn't flush to stdout!"); io::stdin() .read_line(&mut buffer) .expect("Couldn't read line!"); let n = match buffer.trim().parse() { Ok...
fn main() {
random_line_split