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
grabbing.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use glutin::{Event, ElementState}; mod support; #[cfg(target_os = "android")] android_start!(main); fn main()
}, Event::Closed => break, a @ Event::MouseMoved(_, _) => { println!("{:?}", a); }, _ => (), } context.draw_frame((0.0, 1.0, 0.0, 1.0)); let _ = window.swap_buffers(); } }
{ let window = glutin::WindowBuilder::new().build().unwrap(); window.set_title("glutin - Cursor grabbing test"); let _ = unsafe { window.make_current() }; let context = support::load(&window); let mut grabbed = false; for event in window.wait_events() { match event { Event:...
identifier_body
grabbing.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use glutin::{Event, ElementState}; mod support; #[cfg(target_os = "android")] android_start!(main); fn
() { let window = glutin::WindowBuilder::new().build().unwrap(); window.set_title("glutin - Cursor grabbing test"); let _ = unsafe { window.make_current() }; let context = support::load(&window); let mut grabbed = false; for event in window.wait_events() { match event { Eve...
main
identifier_name
struct_lits_visual.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-struct_lit_style: Visual // rustfmt-error_on_line_overflow: false // Struct literal expressions. fn
() { let x = Bar; // Comment let y = Foo { a: x }; Foo { a: foo(), // comment // comment b: bar(), ..something }; Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { a: f(), b: b() }; Fooooooooooooooooooooooooooooooooooooooooooooooooooo...
main
identifier_name
struct_lits_visual.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-struct_lit_style: Visual // rustfmt-error_on_line_overflow: false // Struct literal expressions. fn main() { let x = Bar; // Comment let y = Foo { a: x }; Foo { a: foo(), // comment // comment b: bar(),...
, y: baz(), }; Baz { x: yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, z: zzzzz, /* test */ }; A { // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit // amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante ...
{ bar(); }
conditional_block
struct_lits_visual.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-struct_lit_style: Visual // rustfmt-error_on_line_overflow: false // Struct literal expressions. fn main() { let x = Bar; // Comment let y = Foo { a: x }; Foo { a: foo(), // comment // comment b: bar(),...
// Comment b: bar(), /* Comment */ }; Foo { a: Bar, b: f() }; Quux { x: if cond { bar(); }, y: ba...
a: foo(), /* Comment */
random_line_split
struct_lits_visual.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-struct_lit_style: Visual // rustfmt-error_on_line_overflow: false // Struct literal expressions. fn main()
Quux { x: if cond { bar(); }, y: baz(), }; Baz { x: yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, z: zzzzz, /* test */ }; A { // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit // amet ipsum mauris. Maecenas ...
{ let x = Bar; // Comment let y = Foo { a: x }; Foo { a: foo(), // comment // comment b: bar(), ..something }; Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { a: f(), b: b() }; Fooooooooooooooooooooooooooooooooooooooooooooooooooooo...
identifier_body
mod.rs
//! A'simple' ARM emulator. //! //! At the moment the emulator only has support for a handful of THUMB-2 instructions /// and no ARM-mode support. use super::*; pub use self::memory_tree::MemoryTree; pub use self::ram::RAM; pub use self::emu::SimpleEmulator; pub use self::system::SimpleSystem; pub mod memory_tree; p...
(a: Word, b: Word, c: Word) -> (Word, bool, bool) { let sa = a as i64; let sb = b as i64; let sc = c as i64; let ua = (a as u32) as u64; let ub = (b as u32) as u64; let uc = (c as u32) as u64; let us = ua.wrapping_add(ub).wrapping_add(uc); let ss = sa.wrapping_add(sb).wrapping_add(s...
adc32
identifier_name
mod.rs
//! A'simple' ARM emulator. //! //! At the moment the emulator only has support for a handful of THUMB-2 instructions /// and no ARM-mode support. use super::*; pub use self::memory_tree::MemoryTree; pub use self::ram::RAM; pub use self::emu::SimpleEmulator; pub use self::system::SimpleSystem; pub mod memory_tree; p...
fn write_u32(&self, addr: u64, val: u32) -> Result<()> { self.write(addr, &[(val & 0xff) as u8, ((val >> 8) & 0xff) as u8, ((val >> 16) & 0xff) as u8, ((val >> 24) & 0xff) as u8]) } } pub trait System { type Memory: ...
{ self.write(addr, &[(val & 0xff) as u8, ((val >> 8) & 0xff) as u8]) }
identifier_body
mod.rs
//! A'simple' ARM emulator. //! //! At the moment the emulator only has support for a handful of THUMB-2 instructions /// and no ARM-mode support. use super::*; pub use self::memory_tree::MemoryTree; pub use self::ram::RAM; pub use self::emu::SimpleEmulator; pub use self::system::SimpleSystem; pub mod memory_tree; p...
dest[x] = src[x] } } fn swap_word(src: Word) -> Word { let src = src as u32; let src = (src >> 24) | ((src >> 8) & 0xff00) | ((src << 8) & 0xff0000) | ((src << 24) & 0xff000000); src as Word } fn adc32(a: Word, b: Word, c: Word) -> (Word, bool, bool) { let sa = a ...
{ break }
conditional_block
mod.rs
//! A'simple' ARM emulator. //! //! At the moment the emulator only has support for a handful of THUMB-2 instructions /// and no ARM-mode support. use super::*; pub use self::memory_tree::MemoryTree; pub use self::ram::RAM; pub use self::emu::SimpleEmulator; pub use self::system::SimpleSystem; pub mod memory_tree; p...
try!(self.read(addr, &mut data)); Ok((data[0] as u16) | ((data[1] as u16) << 8)) } fn read_u32(&self, addr: u64) -> Result<u32> { let mut data = [0u8;4]; try!(self.read(addr, &mut data)); Ok((data[0] as u32) | ((data[1] as u32) << 8) | ((data[2] as ...
let mut data = [0u8;2];
random_line_split
result_try.rs
use std::io::prelude::*; use std::fs::File; type Result<T> = std::result::Result<T, String>; // Setup to make this work. Create two files with some info. Ignore the // return values because we don't care about them here. fn setup() { File::create("a") .and_then(|mut file| file.write_all(b"grape")) ....
// Concat the contents of the two files together into a new `Result`. fn concat(a: &str, b: &str) -> Result<String> { let (data_a, data_b) = (get_data(a), get_data(b)); data_a.and_then(|a| // Return `Ok` when both `a` and `b` are `Ok`. Otherwise return // whichever has the first `Err`. ...
.map(|_| contents) }) }
random_line_split
result_try.rs
use std::io::prelude::*; use std::fs::File; type Result<T> = std::result::Result<T, String>; // Setup to make this work. Create two files with some info. Ignore the // return values because we don't care about them here. fn setup() { File::create("a") .and_then(|mut file| file.write_all(b"grape")) ....
{ setup(); match concat("a", "b") { Ok(n) => println!("{}", n), Err(e) => println!("Error: {}", e), } }
identifier_body
result_try.rs
use std::io::prelude::*; use std::fs::File; type Result<T> = std::result::Result<T, String>; // Setup to make this work. Create two files with some info. Ignore the // return values because we don't care about them here. fn setup() { File::create("a") .and_then(|mut file| file.write_all(b"grape")) ....
() { setup(); match concat("a", "b") { Ok(n) => println!("{}", n), Err(e) => println!("Error: {}", e), } }
main
identifier_name
lib.rs
// Copyright 2016 Mozilla Foundation // // 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...
println!(); 1 } }); } fn init_logging() { if env::var(LOGGING_ENV).is_ok() { match env_logger::Builder::from_env(LOGGING_ENV).try_init() { Ok(_) => (), Err(e) => panic!("Failed to initalize logging: {:?}", e), } } }
println!("sccache: caused by: {}", e); } cmdline::get_app().print_help().unwrap();
random_line_split
lib.rs
// Copyright 2016 Mozilla Foundation // // 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...
() { if env::var(LOGGING_ENV).is_ok() { match env_logger::Builder::from_env(LOGGING_ENV).try_init() { Ok(_) => (), Err(e) => panic!("Failed to initalize logging: {:?}", e), } } }
init_logging
identifier_name
lib.rs
// Copyright 2016 Mozilla Foundation // // 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...
}, Err(e) => { println!("sccache: {}", e); for e in e.chain().skip(1) { println!("sccache: caused by: {}", e); } cmdline::get_app().print_help().unwrap(); println!(); 1 } }); } fn init_logging() { i...
{ eprintln!("sccache: error: {}", e); for e in e.chain().skip(1) { eprintln!("sccache: caused by: {}", e); } 2 }
conditional_block
lib.rs
// Copyright 2016 Mozilla Foundation // // 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...
{ if env::var(LOGGING_ENV).is_ok() { match env_logger::Builder::from_env(LOGGING_ENV).try_init() { Ok(_) => (), Err(e) => panic!("Failed to initalize logging: {:?}", e), } } }
identifier_body
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::i...
() { let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}]...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection unsaf...
main
identifier_name
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::i...
, None => () } }, None => () } let mut buf = [0,..500]; stream.read(buf); let request_str = str::from_utf8(buf); println(format!("Received request :\n{:s}",...
{println(format!("Received connection from: [{:s}]", pn.to_str()));}
conditional_block
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::i...
None => () } let mut buf = [0,..500]; stream.read(buf); let request_str = str::from_utf8(buf); println(format!("Received request :\n{:s}", request_str)); let mut index: int = 0; let mut file_name = ~""; for splitted in req...
{ let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}] ...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection unsafe ...
identifier_body
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. //
// Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::io::*; use std::io::net::ip::{SocketAddr}; use std::{str}; static IP: &'static str = "127.0.0.1"; static PORT: int = 4414; static mut visitor_count: int = 0; fn main() { let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)...
// University of Virginia - cs4414 Spring 2014
random_line_split
bin.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors //
// 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of ...
// 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 Free Software Foundation; version
random_line_split
unified.rs
extern crate arrayfire as af; use af::*; #[allow(unused_must_use)] fn test_backend(){ info(); let num_rows: u64 = 10; let num_cols: u64 = 10; let dims = Dim4::new(&[num_rows, num_cols, 1, 1]); println!("Create a 10-by-10 matrix of random floats on the compute device"); let a = match randu(dims, Aftype::...
() { println!("There are {:?} available backends", get_backend_count().unwrap()); let available = get_available_backends().unwrap(); if available.contains(&Backend::AF_BACKEND_CPU){ println!("Evaluating CPU Backend..."); let err = set_backend(Backend::AF_BACKEND_CPU); println!("There are {} CPU compu...
main
identifier_name
unified.rs
extern crate arrayfire as af; use af::*; #[allow(unused_must_use)] fn test_backend(){ info(); let num_rows: u64 = 10; let num_cols: u64 = 10; let dims = Dim4::new(&[num_rows, num_cols, 1, 1]); println!("Create a 10-by-10 matrix of random floats on the compute device"); let a = match randu(dims, Aftype::...
if available.contains(&Backend::AF_BACKEND_CUDA){ println!("Evaluating CUDA Backend..."); let err = set_backend(Backend::AF_BACKEND_CUDA); println!("There are {} CUDA compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CUDA backend ...
{ println!("Evaluating CPU Backend..."); let err = set_backend(Backend::AF_BACKEND_CPU); println!("There are {} CPU compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CPU backend error: {}", e), }; }
conditional_block
unified.rs
extern crate arrayfire as af; use af::*; #[allow(unused_must_use)] fn test_backend()
#[allow(unused_must_use)] fn main() { println!("There are {:?} available backends", get_backend_count().unwrap()); let available = get_available_backends().unwrap(); if available.contains(&Backend::AF_BACKEND_CPU){ println!("Evaluating CPU Backend..."); let err = set_backend(Backend::AF_BACKEND_CPU); ...
{ info(); let num_rows: u64 = 10; let num_cols: u64 = 10; let dims = Dim4::new(&[num_rows, num_cols, 1, 1]); println!("Create a 10-by-10 matrix of random floats on the compute device"); let a = match randu(dims, Aftype::F32) { Ok(value) => value, Err(error) => panic!("{}", error), }; print(&a)...
identifier_body
unified.rs
extern crate arrayfire as af; use af::*; #[allow(unused_must_use)] fn test_backend(){ info(); let num_rows: u64 = 10; let num_cols: u64 = 10; let dims = Dim4::new(&[num_rows, num_cols, 1, 1]); println!("Create a 10-by-10 matrix of random floats on the compute device"); let a = match randu(dims, Aftype::...
}; } }
println!("There are {} OpenCL compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("OpenCL backend error: {}", e),
random_line_split
mod.rs
/* io::mod.rs */ use core::mem::volatile_store; use kernel::sgash; mod font; /* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */ pub static UART0: *mut u32 = 0x101f1000 as *mut u32; pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32; #[allow(dead_code)] pub stati...
(addr: u32, value: u32) { *(addr as *mut u32) = value; } pub unsafe fn set_fg(color: u32) { FG_COLOR = color; } pub unsafe fn set_bg(color: u32) { BG_COLOR = color; } pub unsafe fn set_cursor_color(color: u32) { CURSOR_COLOR = color; }
wh
identifier_name
mod.rs
/* io::mod.rs */ use core::mem::volatile_store; use kernel::sgash; mod font; /* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */ pub static UART0: *mut u32 = 0x101f1000 as *mut u32; pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32; #[allow(dead_code)] pub stati...
while i < SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR as u32 + i*4) as *mut u32) = color; i+=1; } } pub unsafe fn fill_bg() { paint(BG_COLOR); } #[allow(dead_code)] pub unsafe fn read(addr: u32) -> u32 { *(addr as *mut u32) } pub unsafe fn ws(addr: u32, value: u32) { *(addr as *mut u32) = *(addr as *mut u32...
pub unsafe fn paint(color: u32) { let mut i = 0;
random_line_split
mod.rs
/* io::mod.rs */ use core::mem::volatile_store; use kernel::sgash; mod font; /* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */ pub static UART0: *mut u32 = 0x101f1000 as *mut u32; pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32; #[allow(dead_code)] pub stati...
let font_offset = (c as u8) - 0x20; let map = font::bitmaps[font_offset]; let mut i = -1; let mut j = 0; let mut addr = START_ADDR + 4*(CURSOR_X + /*CURSOR_WIDTH +*/ 1 + SCREEN_WIDTH*CURSOR_Y + CURSOR_HEIGHT*SCREEN_WIDTH); while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { //let addr = START_ADDR + 4*(CURS...
{ scrollup(); }
conditional_block
mod.rs
/* io::mod.rs */ use core::mem::volatile_store; use kernel::sgash; mod font; /* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */ pub static UART0: *mut u32 = 0x101f1000 as *mut u32; pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32; #[allow(dead_code)] pub stati...
/* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } // 640x480 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480) { ws(0x10000010, 0x2C77); ws(0x1012...
{ SCREEN_WIDTH = width; SCREEN_HEIGHT= height; sgash::init(); /* For the following magic values, see * http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACHEDGD.html */ // 800x600 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html if (SCREEN_WIDT...
identifier_body
rec-align-u64.rs
// run-pass #![allow(dead_code)] #![allow(unused_unsafe)] // ignore-wasm32-bare seems unimportant to test // Issue #2303 #![feature(intrinsics)] use std::mem; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> usize; pub fn min_align_of<T>() -> usize; } } // This is the type...
target_os = "netbsd", target_os = "openbsd", target_os = "solaris", target_os = "vxworks"))] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> usize { 4 } pub fn size() -> usize { 12 } } #[cfg(not(target_arch = "x86"))] pub mod...
target_os = "linux", target_os = "macos",
random_line_split
rec-align-u64.rs
// run-pass #![allow(dead_code)] #![allow(unused_unsafe)] // ignore-wasm32-bare seems unimportant to test // Issue #2303 #![feature(intrinsics)] use std::mem; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> usize; pub fn min_align_of<T>() -> usize; } } // This is the type...
() -> usize { 16 } } } #[cfg(target_os = "windows")] mod m { pub mod m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } pub fn main() { unsafe { let x = Outer {c8: 22, t: Inner {c64: 44}}; let y = format!("{:?}", x); println!("align inner = {:...
size
identifier_name
rec-align-u64.rs
// run-pass #![allow(dead_code)] #![allow(unused_unsafe)] // ignore-wasm32-bare seems unimportant to test // Issue #2303 #![feature(intrinsics)] use std::mem; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> usize; pub fn min_align_of<T>() -> usize; } } // This is the type...
pub fn size() -> usize { 16 } } } #[cfg(target_os = "windows")] mod m { pub mod m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } pub fn main() { unsafe { let x = Outer {c8: 22, t: Inner {c64: 44}}; let y = format!("{:?}", x); printl...
{ 8 }
identifier_body
accept_ranges.rs
use std::fmt::{self, Display}; use std::str::FromStr; header! { #[doc="`Accept-Ranges` header, defined in"] #[doc="[RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)"] #[doc=""] #[doc="The `Accept-Ranges` header field allows a server to indicate that it"] #[doc="supports range requests for t...
{ /// Indicating byte-range requests are supported. Bytes, /// Reserved as keyword, indicating no ranges are supported. None, /// The given range unit is not registered at IANA. Unregistered(String), } impl FromStr for RangeUnit { type Err = ::Error; fn from_str(s: &str) -> ::Result<S...
RangeUnit
identifier_name
accept_ranges.rs
use std::fmt::{self, Display}; use std::str::FromStr; header! { #[doc="`Accept-Ranges` header, defined in"] #[doc="[RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)"] #[doc=""] #[doc="The `Accept-Ranges` header field allows a server to indicate that it"] #[doc="supports range requests for t...
} impl Display for RangeUnit { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RangeUnit::Bytes => f.write_str("bytes"), RangeUnit::None => f.write_str("none"), RangeUnit::Unregistered(ref x) => f.write_str(&x), } } }
{ match s { "bytes" => Ok(RangeUnit::Bytes), "none" => Ok(RangeUnit::None), // FIXME: Check if s is really a Token _ => Ok(RangeUnit::Unregistered(s.to_owned())), } }
identifier_body
accept_ranges.rs
use std::fmt::{self, Display}; use std::str::FromStr; header! { #[doc="`Accept-Ranges` header, defined in"] #[doc="[RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)"] #[doc=""] #[doc="The `Accept-Ranges` header field allows a server to indicate that it"] #[doc="supports range requests for t...
#[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(AcceptRanges(vec![RangeUnit::None]));"] #[doc="```"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="l...
#[doc="```"]
random_line_split
chunks.rs
use std::sync::{Arc, Mutex}; use simple_parallel; use state::LSystem; use super::{LProcessor, SimpleProcessor}; /// Parallel processor dividing a state into chunks to be individually iterated /// within a pool of threads. pub struct
{ /// The number of symbols per full chunk. chunk_size: usize, /// The thread pool. pool: simple_parallel::Pool, } impl ChunksProcessor { /// Try and create a new 'ChunksProcessor' instance with the given parameters. /// Typical values: /// - max_tasks : number of CPU logical cores ///...
ChunksProcessor
identifier_name
chunks.rs
use std::sync::{Arc, Mutex}; use simple_parallel; use state::LSystem; use super::{LProcessor, SimpleProcessor}; /// Parallel processor dividing a state into chunks to be individually iterated /// within a pool of threads. pub struct ChunksProcessor { /// The number of symbols per full chunk. chunk_size: usize...
where S: Clone + Eq + Send + Sync { // TODO : better error handling... fn iterate<'a>(&mut self, lsystem: &LSystem<'a, S>) -> Result<LSystem<'a, S>, String> { // Set-up let mut vec: Vec<Vec<S>> = Vec::new(); let state_len = lsystem.state().len(); if state_len == 0 { ...
} } impl<S> LProcessor<S> for ChunksProcessor
random_line_split
chunks.rs
use std::sync::{Arc, Mutex}; use simple_parallel; use state::LSystem; use super::{LProcessor, SimpleProcessor}; /// Parallel processor dividing a state into chunks to be individually iterated /// within a pool of threads. pub struct ChunksProcessor { /// The number of symbols per full chunk. chunk_size: usize...
}
{ let mut rules = HashMapRules::new(); // algae rules rules.set_str('A', "AB", TurtleCommand::None); rules.set_str('B', "A", TurtleCommand::None); let expected_sizes = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946...
identifier_body
mod.rs
//! This module contains type definition for ECMAScript values. //! According to the ECMA-262 specification, there are six "types" //! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`, //! and `Object`. Four of these are value types and do not need //! heap allocation, while `String` and `Object` have to ...
() -> Value { Value::Null } pub fn number(ptr: heap::NumberPtr) -> Value { Value::Number(ptr) } pub fn boolean(ptr: heap::BooleanPtr) -> Value { Value::Boolean(ptr) } pub fn string(ptr: heap::StringPtr) -> Value { Value::String(ptr) } pub fn object(ptr...
null
identifier_name
mod.rs
//! This module contains type definition for ECMAScript values. //! According to the ECMA-262 specification, there are six "types" //! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`, //! and `Object`. Four of these are value types and do not need //! heap allocation, while `String` and `Object` have to ...
} impl Value { pub fn undefined() -> Value { Value::Undefined } pub fn null() -> Value { Value::Null } pub fn number(ptr: heap::NumberPtr) -> Value { Value::Number(ptr) } pub fn boolean(ptr: heap::BooleanPtr) -> Value { Value::Boolean(ptr) } pub ...
{ Value::Undefined }
identifier_body
mod.rs
//! This module contains type definition for ECMAScript values. //! According to the ECMA-262 specification, there are six "types" //! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`, //! and `Object`. Four of these are value types and do not need //! heap allocation, while `String` and `Object` have to ...
} else { vec![].into_iter() } } } impl Default for Value { fn default() -> Value { Value::Undefined } } impl Value { pub fn undefined() -> Value { Value::Undefined } pub fn null() -> Value { Value::Null } pub fn number(ptr: heap::Nu...
random_line_split
mod.rs
//! This module contains type definition for ECMAScript values. //! According to the ECMA-262 specification, there are six "types" //! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`, //! and `Object`. Four of these are value types and do not need //! heap allocation, while `String` and `Object` have to ...
} } impl Default for Value { fn default() -> Value { Value::Undefined } } impl Value { pub fn undefined() -> Value { Value::Undefined } pub fn null() -> Value { Value::Null } pub fn number(ptr: heap::NumberPtr) -> Value { Value::Number(ptr) } ...
{ vec![].into_iter() }
conditional_block
compiled.rs
_meta_key", "has_status_line", "insert_null_glitch", "memory_above", "memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok", "dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff", "prtr_silent", "hard_cursor", "non_rev_rmcup", "n...
{ let mut strings = HashMap::new(); strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec()); strings.insert("bold".to_string(), b"\x1B[1m".to_vec()); strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec()); strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec()); box TermInfo { ...
identifier_body
compiled.rs
Info; // These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable. pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin", "no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type", "hard_copy", "has_met...
"stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr", "zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse", "set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init", "set0_des_seq", "set1_des_seq", "set2_de...
"set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin", "set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image",
random_line_split
compiled.rs
_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff", "prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region", "can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch", "cr_cancels_micro_mode", "has_print_wheel", "row_addr_...
test_veclens
identifier_name
overflowing_mul.rs
use num::arithmetic::traits::{OverflowingMul, OverflowingMulAssign}; macro_rules! impl_overflowing_mul { ($t:ident) => { impl OverflowingMul<$t> for $t { type Output = $t; #[inline] fn overflowing_mul(self, other: $t) -> ($t, bool) { $t::overflowing_mul(...
/// Replaces `self` with `self * other`. /// /// Returns a boolean indicating whether an arithmetic overflow would occur. If an /// overflow would have occurred, then the wrapped value is assigned. /// /// # Worst-case complexity /// Co...
impl OverflowingMulAssign<$t> for $t {
random_line_split
main.rs
#![feature(plugin)] #![allow(dead_code)] #![allow(unused_variables)] // error-chain can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate error_chain; extern crate chrono; extern crate markdown; extern crate liquid; extern crate walkdir; extern crate rustc_serialize; extern crate docopt; extern cr...
() { use std::path::Path; use std::fs; let site_dir = Path::new("./blog"); let site_config_file = Path::new("./blog/config.toml"); bootstrap("blog"); assert_eq!(true, site_dir.is_dir()); assert_eq!(true, site_config_file.exists()); fs::remove_dir_all("./bl...
test_create_site
identifier_name
main.rs
#![feature(plugin)] #![allow(dead_code)] #![allow(unused_variables)] // error-chain can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate error_chain; extern crate chrono; extern crate markdown; extern crate liquid; extern crate walkdir; extern crate rustc_serialize; extern crate docopt; extern cr...
Metadata, Content, WeGood, MarkdownParseError, NotValidSite, IOError, } enum SilicaParseError { ConfigFile, NotASite, Other, } fn watch() { let site = Site::new(); let (tx, rx) = channel(); thread::spawn(move || { site.watch_changes(tx.clone()); }); prin...
pub enum State {
random_line_split
main.rs
#![feature(plugin)] #![allow(dead_code)] #![allow(unused_variables)] // error-chain can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate error_chain; extern crate chrono; extern crate markdown; extern crate liquid; extern crate walkdir; extern crate rustc_serialize; extern crate docopt; extern cr...
Ok(()) } // The entry point for silica. Parses command line arguments and acts accordingly fn main() { let args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if let Err(ref e) = process_cmd(&args) { use ::std::io::Writ...
{ println!("{}", USAGE); }
conditional_block
rustdoc.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...
}; run(config); } /// Runs rustdoc over the given file fn run(config: Config) { let source_file = copy config.input_crate; // Create an AST service from the source code do astsrv::from_file(source_file.to_str()) |srv| { // Just time how long it takes for the AST to become available ...
{ io::println(fmt!("error: %s", err)); return; }
conditional_block
rustdoc.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...
pass::run_passes(srv, doc, ~[ // Generate type and signature strings tystr_pass::mk_pass(), // Record the full paths to various nodes path_pass::mk_pass(), // Extract the docs attributes and attach them to doc nodes attr_pass::mk_pass(), ...
{ let source_file = copy config.input_crate; // Create an AST service from the source code do astsrv::from_file(source_file.to_str()) |srv| { // Just time how long it takes for the AST to become available do time(~"wait_ast") { do astsrv::exec(srv.clone()) |_ctxt| { } ...
identifier_body
rustdoc.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...
(config: Config) { let source_file = copy config.input_crate; // Create an AST service from the source code do astsrv::from_file(source_file.to_str()) |srv| { // Just time how long it takes for the AST to become available do time(~"wait_ast") { do astsrv::exec(srv.clone()) |_c...
run
identifier_name
rustdoc.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...
config::usage(); return; } let config = match config::parse_config(args) { Ok(config) => config, Err(err) => { io::println(fmt!("error: %s", err)); return; } }; run(config); } /// Runs rustdoc over the given file fn run(config: Config) { let sour...
let args = os::args(); if args.iter().any(|x| "-h" == *x) || args.iter().any(|x| "--help" == *x) {
random_line_split
rgb24.rs
#[derive(Clone, Copy, Debug)] pub struct Rgb24 { pub red: u8, pub green: u8, pub blue: u8, } impl Rgb24 { pub fn new(red: u8, green: u8, blue: u8) -> Self { Rgb24 { red: red, green: green, blue: blue, } } pub fn
(self) -> u8 { self.red } pub fn green(self) -> u8 { self.green } pub fn blue(self) -> u8 { self.blue } } pub mod colours { use super::*; pub const RED: Rgb24 = Rgb24 { red: 255, green: 0, blue: 0 }; pub const GREEN: Rgb24 = Rgb24 { red: 0, green: 255, blue: 0...
red
identifier_name
rgb24.rs
#[derive(Clone, Copy, Debug)] pub struct Rgb24 { pub red: u8, pub green: u8, pub blue: u8, } impl Rgb24 { pub fn new(red: u8, green: u8, blue: u8) -> Self { Rgb24 { red: red, green: green, blue: blue, } } pub fn red(self) -> u8 { self...
pub fn blue(self) -> u8 { self.blue } } pub mod colours { use super::*; pub const RED: Rgb24 = Rgb24 { red: 255, green: 0, blue: 0 }; pub const GREEN: Rgb24 = Rgb24 { red: 0, green: 255, blue: 0 }; pub const BLUE: Rgb24 = Rgb24 { red: 0, green: 0, blue: 255 }; }
{ self.green }
identifier_body
userscripts.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::g...
for file in files { let mut f = File::open(&file).unwrap(); let mut contents = vec![]; f.read_to_end(&mut contents).unwrap(); let script_text = String::from_utf8_lossy(&contents); win.upcast::<GlobalScope>() .evaluate_script_on_global_w...
{ let path_str = match opts::get().userscripts.clone() { Some(p) => p, None => return, }; let doc = document_from_node(head); let win = Trusted::new(doc.window()); doc.add_delayed_task(task!(UserScriptExecute: move || { let win = win.root(); let cx = win.get_cx(); ...
identifier_body
userscripts.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::g...
&file.to_string_lossy(), rval.handle_mut(), 1, ); } })); }
.evaluate_script_on_global_with_result( &script_text,
random_line_split
userscripts.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::g...
(head: &HTMLHeadElement) { let path_str = match opts::get().userscripts.clone() { Some(p) => p, None => return, }; let doc = document_from_node(head); let win = Trusted::new(doc.window()); doc.add_delayed_task(task!(UserScriptExecute: move || { let win = win.root(); l...
load_script
identifier_name
walker.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. */ use std::fs::{self, DirEntry, Metadata}; use std::io; use std::path::{Path, PathBuf}; use anyhow::Result; use thiserror::Error; use pathmat...
dir_matches: Vec<RepoPathBuf>, results: Vec<Result<WalkEntry>>, matcher: M, include_directories: bool, } impl<M> Walker<M> where M: Matcher, { pub fn new(root: PathBuf, matcher: M, include_directories: bool) -> Result<Self> { let mut dir_matches = vec![]; if matcher.matches_dire...
/// finding files matched by matcher pub struct Walker<M> { root: PathBuf,
random_line_split
walker.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. */ use std::fs::{self, DirEntry, Metadata}; use std::io; use std::path::{Path, PathBuf}; use anyhow::Result; use thiserror::Error; use pathmat...
(&mut self) -> Option<Self::Item> { match self.walk() { Err(e) => Some(Err(e)), Ok(()) => self.results.pop(), } } } #[cfg(test)] mod tests { use super::*; use std::fs::{create_dir_all, OpenOptions}; use std::path::PathBuf; use tempfile::tempdir; use pa...
next
identifier_name
walker.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. */ use std::fs::{self, DirEntry, Metadata}; use std::io; use std::path::{Path, PathBuf}; use anyhow::Result; use thiserror::Error; use pathmat...
fn match_entry(&mut self, next_dir: &RepoPathBuf, entry: DirEntry) -> Result<()> { // It'd be nice to move all this conversion noise to a function, but having it here saves // us from allocating filename repeatedly. let filename = entry.file_name(); let filename = filename.to_str()...
{ let mut dir_matches = vec![]; if matcher.matches_directory(&RepoPathBuf::new())? != DirectoryMatch::Nothing { dir_matches.push(RepoPathBuf::new()); } let walker = Walker { root, dir_matches, results: Vec::new(), matcher, ...
identifier_body
issue-8498.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert!(**z == 7); } None => () } }
{ match &[(box 5,box 7)] { ps => { let (ref y, _) = ps[0]; assert!(**y == 5); } } match Some(&[(box 5,)]) { Some(ps) => { let (ref y,) = ps[0]; assert!(**y == 5); } None => () } match Some(&[(box 5,box 7)]) { ...
identifier_body
issue-8498.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
assert!(**z == 7); } None => () }
random_line_split
issue-8498.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { match &[(box 5,box 7)] { ps => { let (ref y, _) = ps[0]; assert!(**y == 5); } } match Some(&[(box 5,)]) { Some(ps) => { let (ref y,) = ps[0]; assert!(**y == 5); } None => () } match Some(&[(box 5,box 7)]) { ...
main
identifier_name
json.rs
#![cfg(feature = "alloc")] #[macro_use] extern crate nom; extern crate jemallocator; #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use nom::{Err, IResult, Offset, error::{VerboseError, VerboseErrorKind}}; use nom::{ character::complete::alphanumeric1 as alphanumeric, bytes::c...
|i| tag("false")(i).map(|(i,_)| (i, false)), |i| tag("true")(i).map(|(i,_)| (i, true)) ))(input) /* match tag::<&'static str, &'a str, E>("false")(i) { Ok((i, _)) => Ok((i, false)), Err(_) => tag("true")(i).map(|(i,_)| (i, true)) } */ } fn array<'a, E: ParseError<&'a str>>(i: &'a str) ->I...
fn boolean<'a, E: ParseError<&'a str>>(input: &'a str) ->IResult<&'a str, bool, E> { alt( (
random_line_split
json.rs
#![cfg(feature = "alloc")] #[macro_use] extern crate nom; extern crate jemallocator; #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use nom::{Err, IResult, Offset, error::{VerboseError, VerboseErrorKind}}; use nom::{ character::complete::alphanumeric1 as alphanumeric, bytes::c...
fn string<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> { //delimitedc(i, char('\"'), parse_str, char('\"')) let (i, _) = char('\"')(i)?; //context("string", |i| terminatedc(i, parse_str, char('\"')))(i) context("string", terminated(parse_str, char('\"')))(i) } fn boolean<'a, E: Pa...
{ escaped!(i, call!(alphanumeric), '\\', one_of!("\"n\\")) }
identifier_body
json.rs
#![cfg(feature = "alloc")] #[macro_use] extern crate nom; extern crate jemallocator; #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use nom::{Err, IResult, Offset, error::{VerboseError, VerboseErrorKind}}; use nom::{ character::complete::alphanumeric1 as alphanumeric, bytes::c...
<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, f64, E> { flat_map!(i, recognize_float, parse_to!(f64)) } fn parse_str<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> { escaped!(i, call!(alphanumeric), '\\', one_of!("\"n\\")) } fn string<'a, E: ParseError<&'a str>>(i: &'a str)...
float
identifier_name
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().pars...
{ let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
identifier_body
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().pars...
} } count } fn main() { println!("{}", region_within(include_str!("input.txt").into(), 10000)); } #[test] fn test_06b() { let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
{ count += 1; }
conditional_block
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().pars...
let total_distance: i32 = points.into_iter().map(|p| distance((x, y), *p)).sum(); if total_distance < n { count += 1; } } } count } fn main() { println!("{}", region_within(include_str!("input.txt").into(), 10000)); } #[test] fn test_06b() { ...
for x in min_x..=max_x { for y in min_y..=max_y {
random_line_split
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().pars...
() { let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
test_06b
identifier_name
errors.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use std::error; use std::result; quick_error! { #[derive(Debug)] pub enum Error { Io(err: std::io::Error) { from() cause(err) display("{}", err) ...
}
{ match self { Error::Io(_) => error_code::pd::IO, Error::ClusterBootstrapped(_) => error_code::pd::CLUSTER_BOOTSTRAPPED, Error::ClusterNotBootstrapped(_) => error_code::pd::CLUSTER_NOT_BOOTSTRAPPED, Error::Incompatible => error_code::pd::INCOMPATIBLE, ...
identifier_body
errors.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use std::error; use std::result; quick_error! { #[derive(Debug)] pub enum Error { Io(err: std::io::Error) { from() cause(err) display("{}", err) ...
(&self) -> ErrorCode { match self { Error::Io(_) => error_code::pd::IO, Error::ClusterBootstrapped(_) => error_code::pd::CLUSTER_BOOTSTRAPPED, Error::ClusterNotBootstrapped(_) => error_code::pd::CLUSTER_NOT_BOOTSTRAPPED, Error::Incompatible => error_code::pd::INCO...
error_code
identifier_name
errors.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use std::error; use std::result; quick_error! { #[derive(Debug)] pub enum Error { Io(err: std::io::Error) { from() cause(err) display("{}", err) ...
display("unknown error {:?}", err) } RegionNotFound(key: Vec<u8>) { display("region is not found for key {}", &log_wrappers::Value::key(key)) } StoreTombstone(msg: String) { display("store is tombstone {:?}", msg) } } } pub type Result<T> ...
Other(err: Box<dyn error::Error + Sync + Send>) { from() cause(err.as_ref())
random_line_split
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0...
(&mut self) -> Result<(), LinuxI2CError> { self.reset_display()?; // Switch to Picture Mode. self.register(CONFIG_BANK, MODE_REGISTER, PICTURE_MODE)?; // Disable audio sync. self.register(CONFIG_BANK, AUDIOSYNC_REGISTER, 0)?; // Initialize frames 0 and 1. for f...
init_display
identifier_name
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0...
self.write_data(BANK_ADDRESS, &[bank]) } fn register(&mut self, bank: u8, register: u8, value: u8) -> Result<(), LinuxI2CError> { self.bank(bank)?; self.write_data(register, &[value]) } fn frame(&mut self, frame: u8) -> Result<(), LinuxI2CError> { self.register(CONFIG_B...
display } fn bank(&mut self, bank: u8) -> Result<(), LinuxI2CError> {
random_line_split
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0...
Ok(()) } }
{ // Double buffering with frames 0 and 1. let new_frame = (self.frame + 1) % 2; self.bank(new_frame)?; for y in 0..DISPLAY_HEIGHT { for x in 0..DISPLAY_WIDTH { let offset = if x >= 8 { (x - 8) * 16 + y } else { ...
identifier_body
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0...
else { 1 }) } } impl Display for I2CDisplay { fn show(&mut self, buffer: &[Column]) -> Result<(), Error> { // Double buffering with frames 0 and 1. let new_frame = (self.frame + 1) % 2; self.bank(new_frame)?; for y in 0..DISPLAY_HEIGHT { for x in 0..DISPLAY_WIDTH { ...
{ 0 }
conditional_block
scancode.rs
// Copyright 2014 The sdl2-rs Developers. // // 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 a...
SDL_SCANCODE_INSERT = 73, SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = ...
SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72,
random_line_split
scancode.rs
// Copyright 2014 The sdl2-rs Developers. // // 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 a...
{ SDL_SCANCODE_UNKNOWN = 0, SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L...
SDL_Scancode
identifier_name
hidden_unicode_codepoints.rs
use crate::{EarlyContext, EarlyLintPass, LintContext}; use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; use rustc_ast as ast; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_span::{BytePos, Span, Symbol}; declare_lint! { /// The `text_direction_codepoint_in_literal...
&self, cx: &EarlyContext<'_>, text: Symbol, span: Span, padding: u32, point_at_inner_spans: bool, label: &str, ) { // Obtain the `Span`s for each of the forbidden chars. let spans: Vec<_> = text .as_str() .char_indices() ...
nt_text_direction_codepoint(
identifier_name
hidden_unicode_codepoints.rs
use crate::{EarlyContext, EarlyLintPass, LintContext}; use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; use rustc_ast as ast; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_span::{BytePos, Span, Symbol}; declare_lint! { /// The `text_direction_codepoint_in_literal...
}
// byte strings are already handled well enough by `EscapeError::NonAsciiCharInByteString` let (text, span, padding) = match &expr.kind { ast::ExprKind::Lit(ast::Lit { token, kind, span }) => { let text = token.symbol; if !contains_text_flow_control_chars(&tex...
identifier_body
hidden_unicode_codepoints.rs
use crate::{EarlyContext, EarlyLintPass, LintContext}; use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; use rustc_ast as ast; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_span::{BytePos, Span, Symbol}; declare_lint! { /// The `text_direction_codepoint_in_literal...
err.multipart_suggestion( "if you want to keep them but make them visible in your source code, you can \ escape them", spans .into_iter() .map(|(c, span)| { let c = forma...
spans.iter().map(|(_, span)| (*span, "".to_string())).collect(), Applicability::MachineApplicable, SuggestionStyle::HideCodeAlways, );
random_line_split
htmltextareaelement.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::HTMLTextAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLTextAr...
} impl<'a> HTMLTextAreaElementMethods for JSRef<'a, HTMLTextAreaElement> { // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom...
{ let element = HTMLTextAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTextAreaElementBinding::Wrap) }
identifier_body
htmltextareaelement.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::HTMLTextAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLTextAr...
(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_dis...
after_set_attr
identifier_name
htmltextareaelement.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::HTMLTextAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLTextAr...
} } fn before_remove_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.before_remove_attr(name, value), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disab...
node.set_disabled_state(true); node.set_enabled_state(false); }, _ => ()
random_line_split
shootout-ackermann.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 args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "8".to_owned()) } else { args.move_iter().collect() }; let n = from_str::<int>(*args.get(1)).unwrap(); ...
main
identifier_name
shootout-ackermann.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 ...
else { return ack(m - 1, ack(m, n - 1)); } } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "8".to_owned()) } else { args.move_...
{ return ack(m - 1, 1); }
conditional_block
shootout-ackermann.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 ...
if m == 0 { return n + 1 } else { if n == 0 { return ack(m - 1, 1); } else { return ack(m - 1, ack(m, n - 1)); } } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owne...
random_line_split
shootout-ackermann.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 args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "8".to_owned()) } else { args.move_iter().collect() }; let n = from_str::<int>(*args.get(1)).unwrap(); pri...
identifier_body
print_queue_resolvers.rs
use async_graphql::{ ID, Context, FieldResult, }; // use eyre::{ // eyre, // // Result, // Context as _, // }; use printspool_json_store::{ Record, JsonRow }; use crate::{ PrintQueue, part::Part, // package::Package, }; #[derive(async_graphql::InputObject, Default)] struct PrintQue...
async fn parts<'ctx>( &self, ctx: &'ctx Context<'_>, // id: Option<ID>, input: Option<PrintQueuePartsInput>, ) -> FieldResult<Vec<Part>> { let db: &crate::Db = ctx.data()?; let input = input.unwrap_or(PrintQueuePartsInput { include_queued: true, ...
{ &self.name }
identifier_body
print_queue_resolvers.rs
use async_graphql::{ ID, Context, FieldResult, }; // use eyre::{ // eyre, // // Result, // Context as _, // }; use printspool_json_store::{ Record, JsonRow }; use crate::{ PrintQueue, part::Part, // package::Package, }; #[derive(async_graphql::InputObject, Default)] struct PrintQue...
<'ctx>( &self, ctx: &'ctx Context<'_>, // id: Option<ID>, input: Option<PrintQueuePartsInput>, ) -> FieldResult<Vec<Part>> { let db: &crate::Db = ctx.data()?; let input = input.unwrap_or(PrintQueuePartsInput { include_queued: true, include_fin...
parts
identifier_name
print_queue_resolvers.rs
use async_graphql::{ ID, Context, FieldResult, }; // use eyre::{ // eyre, // // Result, // Context as _, // }; use printspool_json_store::{ Record, JsonRow }; use crate::{ PrintQueue, part::Part, // package::Package, }; #[derive(async_graphql::InputObject, Default)] struct PrintQue...
impl PrintQueue { async fn id(&self) -> ID { (&self.id).into() } async fn name<'ctx>(&self) -> &String { &self.name } async fn parts<'ctx>( &self, ctx: &'ctx Context<'_>, // id: Option<ID>, input: Option<PrintQueuePartsInput>, ) -> FieldResult<Vec<Part>> { ...
#[async_graphql::Object]
random_line_split
cargo.rs
extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; // Write the Docopt usage string. const USAGE: &'static str = " Rust's package manager Usage: cargo <command> [<args>...] cargo [options] Options: -h, --help Display this message -V, --version Print version info and exit...
.unwrap_or_else(|e| e.exit()); println!("{:?}", args); }
random_line_split
cargo.rs
extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; // Write the Docopt usage string. const USAGE: &'static str = " Rust's package manager Usage: cargo <command> [<args>...] cargo [options] Options: -h, --help Display this message -V, --version Print version info and exit...
() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.options_first(true).decode()) .unwrap_or_else(|e| e.exit()); println!("{:?}", args); }
main
identifier_name
sha.rs
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
pub fn handle_interrupt(&self, _nvic: u32) { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); } } pub static mut KEYMGR0_SHA: ShaEngine = unsafe { ShaEngine::new(KEYMGR0_REGS) }; const HMAC_KEY_SIZE_BYTES: usize = 32; const HMAC_KEY_SIZE_WORDS: usize = HMAC_KEY_SIZE_BYTES / 4; i...
{ ShaEngine { regs: regs, current_mode: Cell::new(None), } }
identifier_body
sha.rs
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(regs: *mut Registers) -> ShaEngine { ShaEngine { regs: regs, current_mode: Cell::new(None), } } pub fn handle_interrupt(&self, _nvic: u32) { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); } } pub static mut KEYMGR0_SHA: ShaEngine = uns...
new
identifier_name
sha.rs
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
DigestMode::Sha1 => flags |= ShaCfgEnMask::Sha1 as u32, DigestMode::Sha256 => (), DigestMode::Sha256Hmac => flags |= ShaCfgEnMask::Hmac as u32, } regs.cfg_en.set(flags); regs.trig.set(ShaTrigMask::Go as u32); Ok(()) } fn initialize_hmac(&sel...
let mut flags = ShaCfgEnMask::Livestream as u32 | ShaCfgEnMask::IntEnDone as u32; match mode {
random_line_split
script.rs
use std::fmt; use std::str::FromStr; use super::lang_mapping; use crate::error::Error; use crate::Lang; #[cfg(feature = "enum-map")] use enum_map::Enum; /// Represents a writing system (Latin, Cyrillic, Arabic, etc). #[cfg_attr(feature = "enum-map", derive(Enum))] #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enu...
}
{ // Vec of all langs obtained with script.langs() let script_langs: Vec<Lang> = Script::all() .iter() .map(|script| script.langs()) .flatten() .copied() .collect(); // Ensure all langs belong at least to one script for lang in...
identifier_body