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
hunter.rs
// // Copyright 2021 The Project Oak 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 o...
#[no_mangle] pub extern "C" fn create_context(ro_ptr: cptr, rw_ptr: cptr) -> *const Context { Context::new_unowned(ro_ptr, rw_ptr) } #[no_mangle] pub extern "C" fn update_context(ctx: &mut Context, ro_ptr: cptr, rw_ptr: cptr) { ctx.update(ro_ptr, rw_ptr); } #[no_mangle] pub extern "C" fn init(ctx: &mut Cont...
{ let vec: Vec<u8> = Vec::with_capacity(size); let ptr = vec.as_ptr(); std::mem::forget(vec); // Leak the vector ptr as cptr }
identifier_body
hunter.rs
// // Copyright 2021 The Project Oak 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 o...
let dx: i32 = r.x as i32 - ctx.hunter.x as i32; let dy: i32 = r.y as i32 - ctx.hunter.y as i32; let dist = dx * dx + dy * dy; if dist < min_dist { min_dx = dx; min_dy = dy; min_dist = dist; } } move_by(&ctx.grid, &mut ctx.hunter.x, &mu...
{ continue; }
conditional_block
hunter.rs
// // Copyright 2021 The Project Oak 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 o...
(size: usize) -> cptr { let vec: Vec<u8> = Vec::with_capacity(size); let ptr = vec.as_ptr(); std::mem::forget(vec); // Leak the vector ptr as cptr } #[no_mangle] pub extern "C" fn create_context(ro_ptr: cptr, rw_ptr: cptr) -> *const Context { Context::new_unowned(ro_ptr, rw_ptr) } #[no_mangle] pub...
malloc_
identifier_name
shift-near-oflo.rs
// run-pass // compile-flags: -C debug-assertions // Check that we do *not* overflow on a number of edge cases. // (compare with test/run-fail/overflowing-{lsh,rsh}*.rs) fn main() { test_left_shift(); test_right_shift(); } pub static mut HACK: i32 = 0; // Work around constant-evaluation // The point of this...
() { // negative rhs can panic, but values in [0,N-1] are okay for iN macro_rules! tests { ($iN:ty, $uN:ty, $max_rhs:expr, $expect_i:expr, $expect_u:expr) => { { let x = (1 as $iN) << id(0); assert_eq!(x, 1); let x = (1 as $uN) << id(0); assert_eq!(x, 1);...
test_left_shift
identifier_name
shift-near-oflo.rs
// run-pass // compile-flags: -C debug-assertions // Check that we do *not* overflow on a number of edge cases. // (compare with test/run-fail/overflowing-{lsh,rsh}*.rs) fn main() { test_left_shift(); test_right_shift(); } pub static mut HACK: i32 = 0; // Work around constant-evaluation // The point of this...
assert_eq!(x, 1); let x = (1 as $iN) << id($max_rhs); assert_eq!(x, $expect_i); let x = (1 as $uN) << id($max_rhs); assert_eq!(x, $expect_u); // high-order bits on LHS are silently discarded without panic. let x = (3 as $iN) << id($max_...
random_line_split
shift-near-oflo.rs
// run-pass // compile-flags: -C debug-assertions // Check that we do *not* overflow on a number of edge cases. // (compare with test/run-fail/overflowing-{lsh,rsh}*.rs) fn main() { test_left_shift(); test_right_shift(); } pub static mut HACK: i32 = 0; // Work around constant-evaluation // The point of this...
assert_eq!(x, 1); let x = ($highbit_u + 1) >> id($max_rhs); assert_eq!(x, 1); let x = ($signbit_i + 1) >> id($max_rhs); assert_eq!(x, -1); } } } tests!(i8, u8, 7, i8::MIN, 0x40_i8, 0x80_u8); tests!(i16, u16, 15, i16::MIN, 0x4000_u16, 0x800...
{ // negative rhs can panic, but values in [0,N-1] are okay for iN macro_rules! tests { ($iN:ty, $uN:ty, $max_rhs:expr, $signbit_i:expr, $highbit_i:expr, $highbit_u:expr) => { { let x = (1 as $iN) >> id(0); assert_eq!(x, 1); let x = (1 as $uN) >> id(...
identifier_body
packet_recv_server.rs
#![no_main] #[macro_use] extern crate libfuzzer_sys; #[macro_use] extern crate lazy_static; use std::net::SocketAddr; use std::sync::Mutex;
.unwrap_or_else(|_| "fuzz/cert.key".to_string()); let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap(); config.load_cert_chain_from_pem_file(&crt_path).unwrap(); config.load_priv_key_from_pem_file(&key_path).unwrap(); config .set_application_prot...
lazy_static! { static ref CONFIG: Mutex<quiche::Config> = { let crt_path = std::env::var("QUICHE_FUZZ_CRT") .unwrap_or_else(|_| "fuzz/cert.crt".to_string()); let key_path = std::env::var("QUICHE_FUZZ_KEY")
random_line_split
lib.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 ...
/// Decompress a buffer, without parsing any sort of header on the input. pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> { inflate_bytes_internal(bytes, 0) } /// Decompress a buffer that starts with a zlib header. pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> { inflate_bytes_internal(by...
{ unsafe { let mut outsz : size_t = 0; let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _, bytes.len() as size_t, &mut outsz, flags); if...
identifier_body
lib.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 ...
() { let bytes = vec!(1, 2, 3, 4, 5); let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed"); let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed"); assert_eq!(inflated.as_slice(), bytes.as_slice()); } }
test_zlib_flate
identifier_name
lib.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Simple [DEFLAT...
// http://rust-lang.org/COPYRIGHT. //
random_line_split
lib.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 ...
} } /// Decompress a buffer, without parsing any sort of header on the input. pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> { inflate_bytes_internal(bytes, 0) } /// Decompress a buffer that starts with a zlib header. pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> { inflate_bytes_int...
{ None }
conditional_block
io.rs
use buf::{Buf, MutBuf}; use error::MioResult; use self::NonBlock::{Ready, WouldBlock}; use error::MioErrorKind as mek; use os; pub use os::IoDesc; /// The result of a non-blocking operation. #[derive(Debug)] pub enum NonBlock<T> { Ready(T), WouldBlock } impl<T> NonBlock<T> { pub fn would_block(&self) -> ...
///reads the length of the supplied slice from the socket into the slice #[inline] pub fn read_slice<I: IoHandle>(io: & I, buf: &mut [u8]) -> MioResult<NonBlock<usize>> { match os::read(io.desc(), buf) { Ok(cnt) => { Ok(Ready(cnt)) } Err(e) => { match e.kind { ...
{ let res = write_slice(io, buf.bytes()); match res { Ok(Ready(cnt)) => buf.advance(cnt), _ => {} } res }
identifier_body
io.rs
use buf::{Buf, MutBuf}; use error::MioResult; use self::NonBlock::{Ready, WouldBlock}; use error::MioErrorKind as mek; use os; pub use os::IoDesc; /// The result of a non-blocking operation. #[derive(Debug)] pub enum NonBlock<T> { Ready(T), WouldBlock } impl<T> NonBlock<T> { pub fn would_block(&self) -> ...
pub trait IoWriter { fn write<B: Buf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>>; fn write_slice(&self, buf: &[u8]) -> MioResult<NonBlock<usize>>; } pub trait IoAcceptor { type Output; fn accept(&mut self) -> MioResult<NonBlock<Self::Output>>; } pub fn pipe() -> MioResult<(PipeReader, PipeWrite...
fn read<B: MutBuf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>>; fn read_slice(&self, buf: &mut [u8]) -> MioResult<NonBlock<usize>>; }
random_line_split
io.rs
use buf::{Buf, MutBuf}; use error::MioResult; use self::NonBlock::{Ready, WouldBlock}; use error::MioErrorKind as mek; use os; pub use os::IoDesc; /// The result of a non-blocking operation. #[derive(Debug)] pub enum NonBlock<T> { Ready(T), WouldBlock } impl<T> NonBlock<T> { pub fn would_block(&self) -> ...
{ desc: os::IoDesc } impl IoHandle for PipeWriter { fn desc(&self) -> &os::IoDesc { &self.desc } } impl FromIoDesc for PipeWriter { fn from_desc(desc: IoDesc) -> Self { PipeWriter { desc: desc } } } impl IoReader for PipeReader { fn read<B: MutBuf>(&self, buf: &mut B) -> MioR...
PipeWriter
identifier_name
futures_unordered.rs
use future::{Future, IntoFuture}; use stream::Stream; use poll::Poll; use Async; use stack::{Stack, Drain}; use std::sync::Arc; use task::{self, UnparkEvent}; use std::prelude::v1::*; /// An adaptor for a stream of futures to execute the futures concurrently, if /// possible, delivering results as they become availab...
return Some(ret) } None } } impl<F> Stream for FuturesUnordered<F> where F: Future { type Item = F::Item; type Error = F::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { if self.active == 0 { return Ok(Async::Ready(None)) ...
{ while let Some(id) = drain.next() { // If this future was already done just skip the notification if self.futures[id].is_none() { continue } let event = UnparkEvent::new(self.stack.clone(), id); let ret = match task::with_unpark_event...
identifier_body
futures_unordered.rs
use future::{Future, IntoFuture}; use stream::Stream; use poll::Poll; use Async; use stack::{Stack, Drain}; use std::sync::Arc; use task::{self, UnparkEvent}; use std::prelude::v1::*; /// An adaptor for a stream of futures to execute the futures concurrently, if /// possible, delivering results as they become availab...
(&mut self) -> Poll<Option<Self::Item>, Self::Error> { if self.active == 0 { return Ok(Async::Ready(None)) } if let Some(drain) = self.pending.take() { if let Some(ret) = self.poll_pending(drain) { return ret } } let drain = sel...
poll
identifier_name
futures_unordered.rs
use future::{Future, IntoFuture}; use stream::Stream; use poll::Poll; use Async; use stack::{Stack, Drain}; use std::sync::Arc; use task::{self, UnparkEvent}; use std::prelude::v1::*; /// An adaptor for a stream of futures to execute the futures concurrently, if /// possible, delivering results as they become availab...
{ futures: Vec<Option<F>>, stack: Arc<Stack<usize>>, pending: Option<Drain<usize>>, active: usize, } /// Converts a list of futures into a `Stream` of results from the futures. /// /// This function will take an list of futures (e.g. a vector, an iterator, /// etc), and return a stream. The stream will...
where F: Future
random_line_split
camera.rs
extern crate mithril; use std::f64; use std::num::Float; use self::mithril::math::{ Vector, Quaternion }; pub struct Camera { position: Vector, focus_point: Vector, up: Vector, field_of_view: f64, aspect_ratio: f64, far: f64, near: f64, anchor_point: Option<[f64; 2]>, control_point...
(position: Vector, focus_point: Vector, up: Vector) -> Camera { Camera{ position: position, focus_point: focus_point, up: up.normalize(), field_of_view: (90.0 * f64::consts::PI / 180.0), aspect_ratio: 640.0/480.0, far: 100.0, ne...
new
identifier_name
camera.rs
extern crate mithril; use std::f64; use std::num::Float; use self::mithril::math::{ Vector, Quaternion }; pub struct Camera { position: Vector, focus_point: Vector, up: Vector, field_of_view: f64, aspect_ratio: f64, far: f64, near: f64, anchor_point: Option<[f64; 2]>, control_point...
x_view[0] = new_u_quat[1]; x_view[1] = new_u_quat[2]; x_view[2] = new_u_quat[3]; y_view[0] = new_v_quat[1]; y_view[1] = new_v_quat[2]; y_view[2] = new_v_quat[3]; z_view[0] = new_...
{ let diff = [ (self.control_point[1] - anchor_point[1]) as f32, (anchor_point[0] - self.control_point[0]) as f32, ]; let diff_sq = (diff[0] * diff[0] + diff[1] * diff[1]).sqrt(); if diff_sq > 0.0001 { ...
conditional_block
camera.rs
extern crate mithril; use std::f64; use std::num::Float; use self::mithril::math::{ Vector, Quaternion }; pub struct Camera { position: Vector, focus_point: Vector, up: Vector, field_of_view: f64, aspect_ratio: f64, far: f64, near: f64, anchor_point: Option<[f64; 2]>, control_point...
pub fn release_controls(&mut self) { self.anchor_point = None; } pub fn is_controlled(&self) -> bool { self.anchor_point!= None } pub fn view_matrix(&self) -> [f32; 16] { let mut z_view = (self.position - self.focus_point).normalize(); let mut x_view = self.up.cro...
{ self.control_point[0] = x; self.control_point[1] = y; }
identifier_body
camera.rs
extern crate mithril; use std::f64; use std::num::Float; use self::mithril::math::{ Vector, Quaternion }; pub struct Camera { position: Vector, focus_point: Vector, up: Vector, field_of_view: f64, aspect_ratio: f64, far: f64, near: f64, anchor_point: Option<[f64; 2]>, control_point...
self.focus_point } pub fn go_to(&mut self, position: Vector) { self.position = position; } pub fn update(&mut self) { } pub fn start_control(&mut self, x: f64, y: f64) { self.anchor_point = Some([x, y]); self.control_point[0] = x; self.control_point[1] ...
} pub fn focus_point(&self) -> Vector {
random_line_split
generic-temporary.rs
// Copyright 2012-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...
() { let produce: fn() -> isize = mk; let consume: fn(v: isize) = chk; apply::<isize>(produce, consume); }
main
identifier_name
generic-temporary.rs
// Copyright 2012-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...
fn chk(a: isize) { println!("{}", a); assert_eq!(a, 1); } fn apply<T>(produce: fn() -> T, consume: fn(T)) { consume(produce()); } pub fn main() { let produce: fn() -> isize = mk; let consume: fn(v: isize) = chk; apply::<isize>(produce, consume); }
{ return 1; }
identifier_body
generic-temporary.rs
// Copyright 2012-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...
fn apply<T>(produce: fn() -> T, consume: fn(T)) { consume(produce()); } pub fn main() { let produce: fn() -> isize = mk; let consume: fn(v: isize) = chk; apply::<isize>(produce, consume); }
fn chk(a: isize) { println!("{}", a); assert_eq!(a, 1); }
random_line_split
main.rs
//! Initium is a modern bootloader with no legacy components. #![no_std] #![no_main] #![feature(asm)] #![feature(try_trait)] #![feature(abi_efiapi)] #![feature(global_asm)] #![feature(const_mut_refs)] #![feature(num_as_ne_bytes)] #![feature(in_band_lifetimes)] #![feature(panic_info_message)] #![feature(alloc_error_han...
{ if let Some(location) = info.location() { error!( "Panic in {} at ({}, {}):", location.file(), location.line(), location.column() ); if let Some(message) = info.message() { error!("{}", message); } } // TODO: halt...
identifier_body
main.rs
//! Initium is a modern bootloader with no legacy components. #![no_std] #![no_main] #![feature(asm)] #![feature(try_trait)] #![feature(abi_efiapi)] #![feature(global_asm)] #![feature(const_mut_refs)] #![feature(num_as_ne_bytes)] #![feature(in_band_lifetimes)] #![feature(panic_info_message)] #![feature(alloc_error_han...
#[no_mangle] pub fn loader_main() { use crate::alloc::string::ToString; // init console get_console_out().init(); device::init(); register_commands(); // TODO: this is a simple test is to be removed on the future let mut window = ListWindow::new("Boot Menu".to_string(), false); // c...
random_line_split
main.rs
//! Initium is a modern bootloader with no legacy components. #![no_std] #![no_main] #![feature(asm)] #![feature(try_trait)] #![feature(abi_efiapi)] #![feature(global_asm)] #![feature(const_mut_refs)] #![feature(num_as_ne_bytes)] #![feature(in_band_lifetimes)] #![feature(panic_info_message)] #![feature(alloc_error_han...
(info: &core::panic::PanicInfo) ->! { if let Some(location) = info.location() { error!( "Panic in {} at ({}, {}):", location.file(), location.line(), location.column() ); if let Some(message) = info.message() { error!("{}", message)...
panic_handler
identifier_name
main.rs
//! Initium is a modern bootloader with no legacy components. #![no_std] #![no_main] #![feature(asm)] #![feature(try_trait)] #![feature(abi_efiapi)] #![feature(global_asm)] #![feature(const_mut_refs)] #![feature(num_as_ne_bytes)] #![feature(in_band_lifetimes)] #![feature(panic_info_message)] #![feature(alloc_error_han...
// TODO: halt in a way that makes sense for the platform loop {} }
{ error!( "Panic in {} at ({}, {}):", location.file(), location.line(), location.column() ); if let Some(message) = info.message() { error!("{}", message); } }
conditional_block
parser.rs
//! A simple parser for a tiny subset of HTML and CSS. use std::ascii::OwnedStrAsciiExt; // for `into_ascii_lower` use std::collections::hashmap::HashMap; use std::num::FromStrRadix; use css::{Stylesheet,Rule,Selector,Simple,SimpleSelector,Declaration,Value,Keyword,Length,Unit,Color,Px}; use dom; /// Parse an HTML d...
let mut rules = Vec::new(); loop { self.consume_whitespace(); if self.eof() { break; } rules.push(self.parse_rule()); } rules } /// Parse a rule set: `<selectors> { <declarations> }`. fn parse_rule(&mut self) -...
/// Parse a list of rules separated by optional whitespace. fn parse_rules(&mut self) -> Vec<Rule> {
random_line_split
parser.rs
//! A simple parser for a tiny subset of HTML and CSS. use std::ascii::OwnedStrAsciiExt; // for `into_ascii_lower` use std::collections::hashmap::HashMap; use std::num::FromStrRadix; use css::{Stylesheet,Rule,Selector,Simple,SimpleSelector,Declaration,Value,Keyword,Length,Unit,Color,Px}; use dom; /// Parse an HTML d...
(&self) -> char { self.input.as_slice().char_at(self.pos) } /// Do the next characters start with the given string? fn starts_with(&self, s: &str) -> bool { self.input.as_slice().slice_from(self.pos).starts_with(s) } /// Return true if all input is consumed. fn eof(&self) -> bo...
next_char
identifier_name
parser.rs
//! A simple parser for a tiny subset of HTML and CSS. use std::ascii::OwnedStrAsciiExt; // for `into_ascii_lower` use std::collections::hashmap::HashMap; use std::num::FromStrRadix; use css::{Stylesheet,Rule,Selector,Simple,SimpleSelector,Declaration,Value,Keyword,Length,Unit,Color,Px}; use dom; /// Parse an HTML d...
/// Parse a quoted value. fn parse_attr_value(&mut self) -> String { let open_quote = self.consume_char(); assert!(open_quote == '"' || open_quote == '\''); let value = self.consume_while(|c| c!= open_quote); assert!(self.consume_char() == open_quote); value } ...
{ let name = self.parse_tag_name(); assert!(self.consume_char() == '='); let value = self.parse_attr_value(); (name, value) }
identifier_body
worker.rs
//! Client socket I/O operation `Worker`. use std::io::Write; use std::sync::Arc; use std::sync::atomic::Ordering; use std::thread; use wrust_async::crossbeam::sync::chase_lev::Steal; use wrust_io::mio::{TryRead, TryWrite, EventSet}; use wrust_types::{Result, Error}; use wrust_types::net::Protocol; use wrust_types::n...
} fn try_read_buf(client: &Arc<Client>, buf: &mut Vec<u8>) -> Result<Option<usize>> { client.then_on_socket(|sock| -> Result<Option<usize>> { match sock { &mut Protocol::Tcp(ref mut stream) => match stream.try_read_buf(buf) { Ok(count) => Ok(count), Err(msg) => Error::new("Cannot read from client ...
} }
random_line_split
worker.rs
//! Client socket I/O operation `Worker`. use std::io::Write; use std::sync::Arc; use std::sync::atomic::Ordering; use std::thread; use wrust_async::crossbeam::sync::chase_lev::Steal; use wrust_io::mio::{TryRead, TryWrite, EventSet}; use wrust_types::{Result, Error}; use wrust_types::net::Protocol; use wrust_types::n...
let write_result = Worker::try_write_buf(client, &mut buf); // Check the result of the I/O operation match write_result { Ok(Some(n)) => { if n < buf.len() { // Not all data has been written. Drain the written part and // left unwritten data for future write tries. buf.drain(0..n); cl...
{ // If there is data left unwritten since the last write operation // then we try to write it before we get data from the stream processing module // and write to the stream let left_data = client.left_data(); let (mut buf, further_action) = match left_data { Some(data) => { // Some data left dat...
identifier_body
worker.rs
//! Client socket I/O operation `Worker`. use std::io::Write; use std::sync::Arc; use std::sync::atomic::Ordering; use std::thread; use wrust_async::crossbeam::sync::chase_lev::Steal; use wrust_io::mio::{TryRead, TryWrite, EventSet}; use wrust_types::{Result, Error}; use wrust_types::net::Protocol; use wrust_types::n...
(client: &Arc<Client>, buf: &mut Vec<u8>) -> Result<Option<usize>> { client.then_on_socket(|sock| -> Result<Option<usize>> { match sock { &mut Protocol::Tcp(ref mut stream) => match stream.try_read_buf(buf) { Ok(count) => Ok(count), Err(msg) => Error::new("Cannot read from client socket").because(msg...
try_read_buf
identifier_name
issue-75525-bounds-checks.rs
// Regression test for #75525, verifies that no bounds checks are generated. // compile-flags: -O #![crate_type = "lib"] // CHECK-LABEL: @f0 // CHECK-NOT: panic #[no_mangle] pub fn f0(idx: usize, buf: &[u8; 10]) -> u8 { if idx < 8 { buf[idx + 1] } else { 0 } } // CHECK-LABEL: @f1 // CHECK-NOT: panic #[no_mangle...
(idx: usize, buf: &[u8; 10]) -> u8 { if idx > 5 && idx < 8 { buf[idx - 1] } else { 0 } } // CHECK-LABEL: @f2 // CHECK-NOT: panic #[no_mangle] pub fn f2(idx: usize, buf: &[u8; 10]) -> u8 { if idx > 5 && idx < 8 { buf[idx] } else { 0 } }
f1
identifier_name
issue-75525-bounds-checks.rs
#![crate_type = "lib"] // CHECK-LABEL: @f0 // CHECK-NOT: panic #[no_mangle] pub fn f0(idx: usize, buf: &[u8; 10]) -> u8 { if idx < 8 { buf[idx + 1] } else { 0 } } // CHECK-LABEL: @f1 // CHECK-NOT: panic #[no_mangle] pub fn f1(idx: usize, buf: &[u8; 10]) -> u8 { if idx > 5 && idx < 8 { buf[idx - 1] } else { 0 ...
// Regression test for #75525, verifies that no bounds checks are generated. // compile-flags: -O
random_line_split
issue-75525-bounds-checks.rs
// Regression test for #75525, verifies that no bounds checks are generated. // compile-flags: -O #![crate_type = "lib"] // CHECK-LABEL: @f0 // CHECK-NOT: panic #[no_mangle] pub fn f0(idx: usize, buf: &[u8; 10]) -> u8 { if idx < 8 { buf[idx + 1] } else { 0 } } // CHECK-LABEL: @f1 // CHECK-NOT: panic #[no_mangle...
{ if idx > 5 && idx < 8 { buf[idx] } else { 0 } }
identifier_body
issue-75525-bounds-checks.rs
// Regression test for #75525, verifies that no bounds checks are generated. // compile-flags: -O #![crate_type = "lib"] // CHECK-LABEL: @f0 // CHECK-NOT: panic #[no_mangle] pub fn f0(idx: usize, buf: &[u8; 10]) -> u8 { if idx < 8 { buf[idx + 1] } else { 0 } } // CHECK-LABEL: @f1 // CHECK-NOT: panic #[no_mangle...
}
{ 0 }
conditional_block
rustc.rs
use std::path::PathBuf; use util::{self, CargoResult, internal, ProcessBuilder}; /// Information on the `rustc` executable #[derive(Debug)] pub struct Rustc { /// The location of the exe pub path: PathBuf, /// An optional program that will be passed the path of the rust exe as its first argument, and ...
verbose_version: verbose_version, host: host, }) } /// Get a process builder set up to use the found rustc version, with a wrapper if Some pub fn process(&self) -> ProcessBuilder { if let Some(ref wrapper) = self.wrapper { let mut cmd = util::process(wra...
{ let mut cmd = util::process(&path); cmd.arg("-vV"); let output = cmd.exec_with_output()?; let verbose_version = String::from_utf8(output.stdout).map_err(|_| { internal("rustc -v didn't return utf8 output") })?; let host = { let triple = verbos...
identifier_body
rustc.rs
use std::path::PathBuf; use util::{self, CargoResult, internal, ProcessBuilder}; /// Information on the `rustc` executable #[derive(Debug)] pub struct
{ /// The location of the exe pub path: PathBuf, /// An optional program that will be passed the path of the rust exe as its first argument, and /// rustc args following this. pub wrapper: Option<PathBuf>, /// Verbose version information (the output of `rustc -vV`) pub verbose_version: Stri...
Rustc
identifier_name
rustc.rs
use std::path::PathBuf; use util::{self, CargoResult, internal, ProcessBuilder}; /// Information on the `rustc` executable #[derive(Debug)] pub struct Rustc { /// The location of the exe pub path: PathBuf, /// An optional program that will be passed the path of the rust exe as its first argument, and ...
else { util::process(&self.path) } } }
{ let mut cmd = util::process(wrapper); { cmd.arg(&self.path); } cmd }
conditional_block
rustc.rs
use std::path::PathBuf; use util::{self, CargoResult, internal, ProcessBuilder}; /// Information on the `rustc` executable #[derive(Debug)] pub struct Rustc { /// The location of the exe pub path: PathBuf, /// An optional program that will be passed the path of the rust exe as its first argument, and ...
let triple = verbose_version.lines().find(|l| { l.starts_with("host: ") }).map(|l| &l[6..]).ok_or_else(|| internal("rustc -v didn't have a line for `host:`"))?; triple.to_string() }; Ok(Rustc { path: path, wrapper: wrapper, ...
internal("rustc -v didn't return utf8 output") })?; let host = {
random_line_split
lib.rs
// Copyright 2014 Pierre Talbot (IRCAM) // 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...
(lo: usize, hi: usize) -> Span { mk_sp( BytePos(lo as u32), BytePos(hi as u32)) }
make_span
identifier_name
lib.rs
// Copyright 2014 Pierre Talbot (IRCAM) // 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...
{ mk_sp( BytePos(lo as u32), BytePos(hi as u32)) }
identifier_body
lib.rs
// Copyright 2014 Pierre Talbot (IRCAM) // 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 governi...
random_line_split
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ ///! Async job scheduling utilities for a blocking application ///! ///! We have a blocking application. We have async libraries. This crate ...
/// Unlike `futures::stream::iter`, the iterator's `next()` function could be /// blocking. pub fn iter_to_stream<I: Send +'static>( iter: impl Iterator<Item = I> + Send +'static, ) -> BoxStream<'static, I> { let stream = futures::stream::unfold(iter, |mut iter| async { let (item, iter) = tokio::task::s...
/// Convert a blocking iterator to an async stream. ///
random_line_split
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ ///! Async job scheduling utilities for a blocking application ///! ///! We have a blocking application. We have async libraries. This crate ...
<I: Send +'static>( iter: impl Iterator<Item = I> + Send +'static, ) -> BoxStream<'static, I> { let stream = futures::stream::unfold(iter, |mut iter| async { let (item, iter) = tokio::task::spawn_blocking(move || { let item = iter.next(); (item, iter) }) .await ...
iter_to_stream
identifier_name
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ ///! Async job scheduling utilities for a blocking application ///! ///! We have a blocking application. We have async libraries. This crate ...
} /// Convert a blocking iterator to an async stream. /// /// Unlike `futures::stream::iter`, the iterator's `next()` function could be /// blocking. pub fn iter_to_stream<I: Send +'static>( iter: impl Iterator<Item = I> + Send +'static, ) -> BoxStream<'static, I> { let stream = futures::stream::unfold(iter, ...
{ let mut rx = self.rx.take().unwrap(); let (next, rx) = block_on_future(async { let next = rx.recv().await; (next, rx) }); self.rx = Some(rx); next }
identifier_body
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ ///! Async job scheduling utilities for a blocking application ///! ///! We have a blocking application. We have async libraries. This crate ...
} }); RunStream { rx: Some(rx) } } } /// Blocking thread handler for receiving the results following processing a `Stream`. pub struct RunStream<T> { // Option is used to workaround lifetime in Iterator::next. rx: Option<tokio::sync::mpsc::Receiver<T>>, } impl<T: Send +'static...
{ // receiver dropped; TODO(T74252041): add logging return; }
conditional_block
lib.rs
use anyhow::{Context, Error}; use next_swc::{custom_before_pass, TransformOptions}; use once_cell::sync::Lazy; use std::sync::Arc; use swc::{config::JsMinifyOptions, try_with_handler, Compiler}; use swc_common::{FileName, FilePathMapping, SourceMap}; use swc_ecmascript::transforms::pass::noop; use wasm_bindgen::prelude...
else { FileName::Real(opts.swc.filename.clone().into()) }, s.into(), ); let before_pass = custom_before_pass(c.cm.clone(), fm.clone(), &opts); let out = c .process_js_with_custom_pass(fm, None, handler, &opts.swc, |_| before_pass, |_| noop()) ...
{ FileName::Anon }
conditional_block
lib.rs
use anyhow::{Context, Error}; use next_swc::{custom_before_pass, TransformOptions}; use once_cell::sync::Lazy; use std::sync::Arc; use swc::{config::JsMinifyOptions, try_with_handler, Compiler}; use swc_common::{FileName, FilePathMapping, SourceMap}; use swc_ecmascript::transforms::pass::noop; use wasm_bindgen::prelude...
JsValue::from_serde(&out).context("failed to serialize json") }) .map_err(convert_err) } /// Get global sourcemap fn compiler() -> Arc<Compiler> { static C: Lazy<Arc<Compiler>> = Lazy::new(|| { let cm = Arc::new(SourceMap::new(FilePathMapping::empty())); Arc::new(Compiler::new(cm))...
); let before_pass = custom_before_pass(c.cm.clone(), fm.clone(), &opts); let out = c .process_js_with_custom_pass(fm, None, handler, &opts.swc, |_| before_pass, |_| noop()) .context("failed to process js file")?;
random_line_split
lib.rs
use anyhow::{Context, Error}; use next_swc::{custom_before_pass, TransformOptions}; use once_cell::sync::Lazy; use std::sync::Arc; use swc::{config::JsMinifyOptions, try_with_handler, Compiler}; use swc_common::{FileName, FilePathMapping, SourceMap}; use swc_ecmascript::transforms::pass::noop; use wasm_bindgen::prelude...
() -> Arc<Compiler> { static C: Lazy<Arc<Compiler>> = Lazy::new(|| { let cm = Arc::new(SourceMap::new(FilePathMapping::empty())); Arc::new(Compiler::new(cm)) }); C.clone() }
compiler
identifier_name
lib.rs
use anyhow::{Context, Error}; use next_swc::{custom_before_pass, TransformOptions}; use once_cell::sync::Lazy; use std::sync::Arc; use swc::{config::JsMinifyOptions, try_with_handler, Compiler}; use swc_common::{FileName, FilePathMapping, SourceMap}; use swc_ecmascript::transforms::pass::noop; use wasm_bindgen::prelude...
{ static C: Lazy<Arc<Compiler>> = Lazy::new(|| { let cm = Arc::new(SourceMap::new(FilePathMapping::empty())); Arc::new(Compiler::new(cm)) }); C.clone() }
identifier_body
11_only_specific_values.rs
extern crate clap; use clap::{App, Arg}; fn main() { // If you have arguments of specific values you want to test for, you can use the //.possible_values() method of Arg // // This allows you specify the valid values for that argument. If the user does not use one of // those specific values, the...
, "slow" => { // Do slow things... }, _ => unreachable!() } }
{ // Do fast things... }
conditional_block
11_only_specific_values.rs
extern crate clap; use clap::{App, Arg}; fn main()
match matches.value_of("MODE").unwrap() { "fast" => { // Do fast things... }, "slow" => { // Do slow things... }, _ => unreachable!() } }
{ // If you have arguments of specific values you want to test for, you can use the // .possible_values() method of Arg // // This allows you specify the valid values for that argument. If the user does not use one of // those specific values, they will receive a graceful exit with error message in...
identifier_body
11_only_specific_values.rs
extern crate clap; use clap::{App, Arg}; fn
() { // If you have arguments of specific values you want to test for, you can use the //.possible_values() method of Arg // // This allows you specify the valid values for that argument. If the user does not use one of // those specific values, they will receive a graceful exit with error message ...
main
identifier_name
11_only_specific_values.rs
extern crate clap; use clap::{App, Arg}; fn main() { // If you have arguments of specific values you want to test for, you can use the //.possible_values() method of Arg // // This allows you specify the valid values for that argument. If the user does not use one of // those specific values, the...
// Note, it's safe to call unwrap() because the arg is required match matches.value_of("MODE").unwrap() { "fast" => { // Do fast things... }, "slow" => { // Do slow things... }, _ => unreachable!() } }
.possible_values(&mode_vals) .required(true)) .get_matches();
random_line_split
2_primitives.rs
/* array A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time constant size, N. bool The boolean type. char A character type. f32 The 32-bit floating point type. f64 The 64-bit floating point type. i16 The 16-bit signed integer type. i32 The 32-bit signed intege...
{ let age: u32 = 30; let score: f64 = std::f64::consts::PI; { let mut age_copy = age; age_copy = 15; println!("age_copy = {:?}\n", age_copy); } assert_eq!(30, age); println!("age = {:?}", age); println!("score = {:?}", score); // tuple let tuple = (1, 2, 3, 4)...
identifier_body
2_primitives.rs
/* array A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time constant size, N. bool The boolean type. char A character type. f32 The 32-bit floating point type. f64 The 64-bit floating point type. i16 The 16-bit signed integer type. i32 The 32-bit signed intege...
() { let age: u32 = 30; let score: f64 = std::f64::consts::PI; { let mut age_copy = age; age_copy = 15; println!("age_copy = {:?}\n", age_copy); } assert_eq!(30, age); println!("age = {:?}", age); println!("score = {:?}", score); // tuple let tuple = (1, 2, 3,...
main
identifier_name
2_primitives.rs
/* array A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time constant size, N. bool The boolean type. char A character type. f32 The 32-bit floating point type. f64 The 64-bit floating point type. i16 The 16-bit signed integer type. i32 The 32-bit signed intege...
age_copy = 15; println!("age_copy = {:?}\n", age_copy); } assert_eq!(30, age); println!("age = {:?}", age); println!("score = {:?}", score); // tuple let tuple = (1, 2, 3, 4); let (a, b, c, d) = tuple; println!("a = {:?}", a); println!("b = {:?}", b); println!("c ...
let score: f64 = std::f64::consts::PI; { let mut age_copy = age;
random_line_split
issue-14865.rs
// Copyright 2012-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...
{ let x = match X::Foo(42) { X::Foo(..) => 1, _ if true => 0, X::Bar(..) => panic!("Oh dear") }; assert_eq!(x, 1); let x = match X::Foo(42) { _ if true => 0, X::Foo(..) => 1, X::Bar(..) => panic!("Oh dear") }; assert_eq!(x, 0); }
identifier_body
issue-14865.rs
// Copyright 2012-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...
{ Foo(usize), Bar(bool) } fn main() { let x = match X::Foo(42) { X::Foo(..) => 1, _ if true => 0, X::Bar(..) => panic!("Oh dear") }; assert_eq!(x, 1); let x = match X::Foo(42) { _ if true => 0, X::Foo(..) => 1, X::Bar(..) => panic!("Oh dear") ...
X
identifier_name
issue-14865.rs
// Copyright 2012-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...
}
}; assert_eq!(x, 0);
random_line_split
sweep.rs
use error::{CliError, Usage, UsageKind}; use super::Command; use constant::MAIN_DIR; use lib::fs::*; use lib::setting::{Config, ConfigKey, Ignore, Storage}; use std::path::{Path, PathBuf}; #[derive(Debug)] pub struct Sweep { option1: Option<String>, option2: Option<String>, } impl Command for Sweep { fn ...
let storage = Storage::new("sweep", indeed); try!(storage.create_box()); let config = try!(Config::read()); let moratorium = try!(config.get(ConfigKey::SweepMoratorium)); let moratorium = Config::to_duration(moratorium); let ignore = try!(Ignore::read()); le...
random_line_split
sweep.rs
use error::{CliError, Usage, UsageKind}; use super::Command; use constant::MAIN_DIR; use lib::fs::*; use lib::setting::{Config, ConfigKey, Ignore, Storage}; use std::path::{Path, PathBuf}; #[derive(Debug)] pub struct
{ option1: Option<String>, option2: Option<String>, } impl Command for Sweep { fn usage(&self) -> Usage { return Usage::new(UsageKind::Sweep); } fn main(&self) -> Result<(), CliError> { let indeed = [&self.option1, &self.option2] .iter() .any(|option| match o...
Sweep
identifier_name
crc64.rs
pub struct Crc64 { table: [u64; 256], value: u64, count: u32, } fn table_maker(polynomial: u64) -> [u64; 256] { let mut table: [u64; 256] = [0; 256]; for i in 0..256 { let mut v = i as u64; for _ in 0..8 { v = if v & 1!= 0 { polynomial ^ (v >> 1) ...
self.value = self.value ^ 0xffffffffffffffffu64; } pub fn checksum(&mut self, buf: &[u8]) -> u64 { self.reset(); self.update(buf); self.finalize(); self.getsum() } pub fn getsum(&self) -> u64 { self.value } pub fn bytecount(&self) -> u32 { ...
} } pub fn finalize(&mut self) {
random_line_split
crc64.rs
pub struct Crc64 { table: [u64; 256], value: u64, count: u32, } fn table_maker(polynomial: u64) -> [u64; 256] { let mut table: [u64; 256] = [0; 256]; for i in 0..256 { let mut v = i as u64; for _ in 0..8 { v = if v & 1!= 0 { polynomial ^ (v >> 1) ...
pub fn getsum(&self) -> u64 { self.value } pub fn bytecount(&self) -> u32 { self.count } } #[test] fn crc32_test() { let mut crc64 = Crc64::new(); crc64.checksum(b"0000"); assert_eq!(crc64.getsum(), 0x2B5C866A7CBEF446); }
{ self.reset(); self.update(buf); self.finalize(); self.getsum() }
identifier_body
crc64.rs
pub struct Crc64 { table: [u64; 256], value: u64, count: u32, } fn table_maker(polynomial: u64) -> [u64; 256] { let mut table: [u64; 256] = [0; 256]; for i in 0..256 { let mut v = i as u64; for _ in 0..8 { v = if v & 1!= 0 { polynomial ^ (v >> 1) ...
} table[i] = v; } table } impl Crc64 { pub fn new() -> Crc64 { let polynomial = 0xC96C5795D7870F42; let c64 = Crc64 { table: table_maker(polynomial), value: 0xffffffffffffffff, count: 0, }; c64 } pub fn reset(&mut...
{ v >> 1 }
conditional_block
crc64.rs
pub struct
{ table: [u64; 256], value: u64, count: u32, } fn table_maker(polynomial: u64) -> [u64; 256] { let mut table: [u64; 256] = [0; 256]; for i in 0..256 { let mut v = i as u64; for _ in 0..8 { v = if v & 1!= 0 { polynomial ^ (v >> 1) } else { ...
Crc64
identifier_name
trim_pass.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 ...
() -> Pass { text_pass::mk_pass(~"trim", |s| s.trim().to_owned() ) } #[cfg(test)] mod test { use astsrv; use attr_pass; use doc; use extract; use prune_hidden_pass; use trim_pass::mk_pass; fn mk_doc(source: ~str) -> doc::Doc { do astsrv::from_str(copy source) |srv| { ...
mk_pass
identifier_name
trim_pass.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 ...
}
{ use std::option::Some; let doc = mk_doc(~"#[doc = \" desc \"] \ mod m { }"); assert_eq!(doc.cratemod().mods()[0].desc(), Some(~"desc")); }
identifier_body
trim_pass.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 ...
do astsrv::from_str(copy source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); let doc = (attr_pass::mk_pass().f)(srv.clone(), doc); let doc = (prune_hidden_pass::mk_pass().f)(srv.clone(), doc); (mk_pass().f)(srv.clone(), doc) } } #[test]...
fn mk_doc(source: ~str) -> doc::Doc {
random_line_split
htmlulistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLUListElementBinding; use dom::bindings::js::Root; use dom::document::Doc...
}
{ let element = HTMLUListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLUListElementBinding::Wrap) }
identifier_body
htmlulistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLUListElementBinding; use dom::bindings::js::Root; use dom::document::Doc...
impl HTMLUListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUListElement { HTMLUListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom...
random_line_split
htmlulistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLUListElementBinding; use dom::bindings::js::Root; use dom::document::Doc...
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUListElement { HTMLUListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, ...
new_inherited
identifier_name
evolve.rs
extern crate rand; extern crate nadezhda;
use nadezhda::grammar::Program; use nadezhda::environment::Environment; use nadezhda::population::Population; use nadezhda::evaluate::Evaluator; use nadezhda::darwin::evolve::succesion; fn survivors(population: Population, environment: Environment) -> Vec<Program> { let Population(generation) = population; le...
use std::env; use std::process;
random_line_split
evolve.rs
extern crate rand; extern crate nadezhda; use std::env; use std::process; use nadezhda::grammar::Program; use nadezhda::environment::Environment; use nadezhda::population::Population; use nadezhda::evaluate::Evaluator; use nadezhda::darwin::evolve::succesion; fn survivors(population: Population, environment: Environ...
fn main() { if env::args().len() < 3 { println!("Usage: evolve FOOD POPULATION"); process::exit(1); } let food_string: String = env::args().nth(1).unwrap(); let food: i32 = match i32::from_str_radix(&food_string, 10) { Ok(value) => value, Err(_) => { printl...
{ let Population(generation) = population; let survivors: Vec<Program> = generation .iter() .map(|program| (program.clone(), program.evaluate_on(environment.clone()))) .filter(|&(_, ref env)| env.cockroach_location - env.food_location == 0) .map(|(program, _)| program) .c...
identifier_body
evolve.rs
extern crate rand; extern crate nadezhda; use std::env; use std::process; use nadezhda::grammar::Program; use nadezhda::environment::Environment; use nadezhda::population::Population; use nadezhda::evaluate::Evaluator; use nadezhda::darwin::evolve::succesion; fn survivors(population: Population, environment: Environ...
}; let population_count_string: String = env::args().nth(2).unwrap(); let population_count: i32 = match i32::from_str_radix(&population_count_string, 10) { Ok(value) => value, Err(_) => { println!("POPULATION argument is not an integer"); process::exit(3); }...
{ println!("FOOD argument is not an integer"); process::exit(2); }
conditional_block
evolve.rs
extern crate rand; extern crate nadezhda; use std::env; use std::process; use nadezhda::grammar::Program; use nadezhda::environment::Environment; use nadezhda::population::Population; use nadezhda::evaluate::Evaluator; use nadezhda::darwin::evolve::succesion; fn survivors(population: Population, environment: Environ...
() { if env::args().len() < 3 { println!("Usage: evolve FOOD POPULATION"); process::exit(1); } let food_string: String = env::args().nth(1).unwrap(); let food: i32 = match i32::from_str_radix(&food_string, 10) { Ok(value) => value, Err(_) => { println!("FOOD ...
main
identifier_name
test.rs
//! //! test.rs.rs //! //! Created by Mitchell Nordine at 05:57PM on December 19, 2014. //! //! Always remember to run high performance Rust code with the --release flag. `Synth` //! extern crate pitch_calc as pitch; extern crate portaudio; extern crate sample; extern crate synth; use portaudio as pa; use pitch::...
let note = LetterOctave(Letter::C, 1); let note_velocity = 1.0; synth.note_on(note, note_velocity); // We'll call this to release the note after 4 seconds. let note_duration = 4.0; let mut is_note_off = false; // We'll use this to keep track of time and break from the loop after 6 seconds....
random_line_split
test.rs
//! //! test.rs.rs //! //! Created by Mitchell Nordine at 05:57PM on December 19, 2014. //! //! Always remember to run high performance Rust code with the --release flag. `Synth` //! extern crate pitch_calc as pitch; extern crate portaudio; extern crate sample; extern crate synth; use portaudio as pa; use pitch::...
() { run().unwrap() } fn run() -> Result<(), pa::Error> { // Construct our fancy Synth! let mut synth = { use synth::{Point, Oscillator, oscillator, Envelope}; // The following envelopes should create a downward pitching sine wave that gradually quietens. // Try messing around wit...
main
identifier_name
test.rs
//! //! test.rs.rs //! //! Created by Mitchell Nordine at 05:57PM on December 19, 2014. //! //! Always remember to run high performance Rust code with the --release flag. `Synth` //! extern crate pitch_calc as pitch; extern crate portaudio; extern crate sample; extern crate synth; use portaudio as pa; use pitch::...
fn run() -> Result<(), pa::Error> { // Construct our fancy Synth! let mut synth = { use synth::{Point, Oscillator, oscillator, Envelope}; // The following envelopes should create a downward pitching sine wave that gradually quietens. // Try messing around with the points and adding s...
{ run().unwrap() }
identifier_body
test.rs
//! //! test.rs.rs //! //! Created by Mitchell Nordine at 05:57PM on December 19, 2014. //! //! Always remember to run high performance Rust code with the --release flag. `Synth` //! extern crate pitch_calc as pitch; extern crate portaudio; extern crate sample; extern crate synth; use portaudio as pa; use pitch::...
pa::Continue } else { pa::Complete } }; // Construct PortAudio and the stream. let pa = try!(pa::PortAudio::new()); let settings = try!(pa.default_output_stream_settings::<f32>(CHANNELS, SAMPLE_HZ, FRAMES)); let mut stream = try!(pa.open_non_blocking_stream(...
{ if !is_note_off { synth.note_off(note); is_note_off = true; } }
conditional_block
types.rs
//! Representation of an email address use std::{ convert::{TryFrom, TryInto}, error::Error, ffi::OsStr, fmt::{Display, Formatter, Result as FmtResult}, net::IpAddr, str::FromStr, }; use idna::domain_to_ascii; use once_cell::sync::Lazy; use regex::Regex; /// Represents an email address with a...
(&self) -> &str { &self.serialized[..self.at_start] } /// Gets the domain portion of the `Address`. /// /// # Examples /// /// ``` /// use lettre::Address; /// /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// let address = Address::new...
user
identifier_name
types.rs
//! Representation of an email address use std::{ convert::{TryFrom, TryInto}, error::Error, ffi::OsStr, fmt::{Display, Formatter, Result as FmtResult}, net::IpAddr, str::FromStr, }; use idna::domain_to_ascii; use once_cell::sync::Lazy; use regex::Regex; /// Represents an email address with a...
impl TryFrom<String> for Address { type Error = AddressError; fn try_from(serialized: String) -> Result<Self, AddressError> { let at_start = check_address(&serialized)?; Ok(Address { serialized, at_start, }) } } impl AsRef<str> for Address { fn as_ref(&s...
random_line_split
types.rs
//! Representation of an email address use std::{ convert::{TryFrom, TryInto}, error::Error, ffi::OsStr, fmt::{Display, Formatter, Result as FmtResult}, net::IpAddr, str::FromStr, }; use idna::domain_to_ascii; use once_cell::sync::Lazy; use regex::Regex; /// Represents an email address with a...
} impl TryFrom<String> for Address { type Error = AddressError; fn try_from(serialized: String) -> Result<Self, AddressError> { let at_start = check_address(&serialized)?; Ok(Address { serialized, at_start, }) } } impl AsRef<str> for Address { fn as_re...
{ let user = user.as_ref(); Address::check_user(user)?; let domain = domain.as_ref(); Address::check_domain(domain)?; let serialized = format!("{}@{}", user, domain); Ok(Address { serialized, at_start: user.len(), }) }
identifier_body
types.rs
//! Representation of an email address use std::{ convert::{TryFrom, TryInto}, error::Error, ffi::OsStr, fmt::{Display, Formatter, Result as FmtResult}, net::IpAddr, str::FromStr, }; use idna::domain_to_ascii; use once_cell::sync::Lazy; use regex::Regex; /// Represents an email address with a...
else { Err(AddressError::InvalidUser) } } pub(super) fn check_domain(domain: &str) -> Result<(), AddressError> { Address::check_domain_ascii(domain).or_else(|_| { domain_to_ascii(domain) .map_err(|_| AddressError::InvalidDomain) .and_then(|...
{ Ok(()) }
conditional_block
list_retention.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use super::*; use crate::{extensions::RequestExt, font_awesome}; use iml_wire_types::snapshot::{ReserveUnit, SnapshotRetention}; #[derive(Clone, Debug)] pub enum Msg ...
Msg::Delete(x) => { if let Ok(true) = window().confirm_with_message("Are you sure you want to delete this retention policy?") { let query = snapshot::remove_retention::build(x.id); let req = fetch::Request::graphql_query(&query); orders.perform_cmd(...
{ paging::update(msg, &mut model.pager, &mut orders.proxy(Msg::Page)); }
conditional_block
list_retention.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use super::*; use crate::{extensions::RequestExt, font_awesome}; use iml_wire_types::snapshot::{ReserveUnit, SnapshotRetention}; #[derive(Clone, Debug)] pub enum Msg ...
session, GroupType::FilesystemAdministrators, button![ class![ C.bg_blue_500, C.duration_300, ...
class![C.flex, C.justify_center, C.p_4, C.px_3], restrict::view(
random_line_split
list_retention.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use super::*; use crate::{extensions::RequestExt, font_awesome}; use iml_wire_types::snapshot::{ReserveUnit, SnapshotRetention}; #[derive(Clone, Debug)] pub enum Msg ...
fn remove_record(&mut self, _: RecordId, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) { self.rows = cache.snapshot_retention.values().cloned().collect(); orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len())); } fn set_records(&mut self, cache: &ArcCache, orders...
{ self.rows = cache.snapshot_retention.values().cloned().collect(); orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len())); }
identifier_body
list_retention.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use super::*; use crate::{extensions::RequestExt, font_awesome}; use iml_wire_types::snapshot::{ReserveUnit, SnapshotRetention}; #[derive(Clone, Debug)] pub enum Msg ...
(model: &Model, cache: &ArcCache, session: Option<&Session>) -> Node<Msg> { panel::view( h3![class![C.py_4, C.font_normal, C.text_lg], "Snapshot Retention Policies"], div![ table::wrapper_view(vec![ table::thead_view(vec![ table::th_view(plain!["Filesy...
view
identifier_name
vec.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 ...
pub fn move_iter(self) -> MoveItems<T> { unsafe { let iter = transmute(iter(self.as_slice())); let ptr = self.ptr as *mut u8; forget(self); MoveItems { allocation: ptr, iter: iter } } } pub unsafe fn set_len(&mut self, len: uint) { s...
{ let slice = Slice { data: self.ptr as *T, len: self.len }; unsafe { transmute(slice) } }
identifier_body
vec.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 ...
pub struct MoveItems<T> { priv allocation: *mut u8, // the block of memory allocated for the vector priv iter: Items<'static, T> } impl<T> Iterator<T> for MoveItems<T> { fn next(&mut self) -> Option<T> { unsafe { self.iter.next().map(|x| read_ptr(x)) } } fn size_hint(&...
heap.free(self.ptr as *mut u8) } } }
random_line_split
vec.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 old_size = self.cap * size_of::<T>(); self.cap = self.cap * 2; let size = old_size * 2; if old_size > size { out_of_memory() } unsafe { let (addr, sz) = heap.realloc(self.ptr as *mut u8, size); self.ptr = addr as *mut T; ...
{ self.cap += 2 }
conditional_block
vec.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 ...
(capacity: uint) -> Vec<T> { if capacity == 0 { Vec::new() } else { let (size, overflow) = mul_with_overflow(capacity, size_of::<T>()); if overflow { out_of_memory(); } let (addr, sz) = unsafe { heap.alloc(size) }; V...
with_capacity
identifier_name
kindck-nonsendable-1.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 ...
fn main() { let x = @3u; let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send` let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send` let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send` let _: proc() = proc() foo(x); }
{}
identifier_body
kindck-nonsendable-1.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 ...
// except according to those terms. #![feature(managed_boxes)] fn foo(_x: @uint) {} fn main() { let x = @3u; let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send` let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send` let _: proc():Send = proc() foo(x); //~ ERROR does n...
random_line_split
kindck-nonsendable-1.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 ...
(_x: @uint) {} fn main() { let x = @3u; let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send` let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send` let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send` let _: proc() = proc() foo(x); }
foo
identifier_name
lib.rs
//! The purpose of this library is to provide an OpenGL context on as many //! platforms as possible. //! //! # Building a window //! //! There are two ways to create a window: //! //! - Calling `Window::new()`. //! - Calling `let builder = WindowBuilder::new()` then `builder.build()`. //! //! The first way is the s...
fn cause(&self) -> Option<&std::error::Error> { match *self { CreationError::NoBackendAvailable(ref err) => Some(&**err), _ => None } } } /// Error that can happen when manipulating an OpenGL context. #[derive(Debug)] pub enum ContextError { IoError(io::Error), ...
{ self.to_string() }
identifier_body
lib.rs
//! The purpose of this library is to provide an OpenGL context on as many //! platforms as possible. //! //! # Building a window //! //! There are two ways to create a window: //! //! - Calling `Window::new()`. //! - Calling `let builder = WindowBuilder::new()` then `builder.build()`. //! //! The first way is the s...
<'a> { winit_builder: winit::WindowBuilder, /// The attributes to use to create the context. pub opengl: GlAttributes<&'a platform::Window>, // Should be made public once it's stabilized. pf_reqs: PixelFormatRequirements, } /// Provides a way to retreive events from the windows that are registere...
WindowBuilder
identifier_name