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
pretty.rs
// Pris -- A language for designing slides // Copyright 2017 Ruud van Asseldonk // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 3. A copy // of the License is available in the root of the repository. //! The string formatting prim...
(&self, f: &mut Formatter) { (*self).print(f); } } impl<P: Print> Print for Box<P> { fn print(&self, f: &mut Formatter) { (**self).print(f); } } impl<P: Print> Print for Rc<P> { fn print(&self, f: &mut Formatter) { (**self).print(f); } } impl<'a> Print for &'a str { fn...
print
identifier_name
grid_builder.rs
extern crate extra; extern crate std; use grid::{Row, Column, alive, dead, Cell, Grid}; mod grid; /**************************************************************************** * Something to say Ben?? ****************************************************************************/ /* * Constructs an immutable grid fr...
// fn build_from_grid
{ let cell_value = |row: uint, column: uint| { let ncount = count_neighbors(Row(row), Column(column), prevg); let cv = match (prevg.inner[row][column].value, ncount) { (dead, 3) => alive, (alive, 2..3) => alive, _ => dead }; return Cell { value: cv }; }; ret...
identifier_body
grid_builder.rs
extern crate extra; extern crate std; use grid::{Row, Column, alive, dead, Cell, Grid}; mod grid; /**************************************************************************** * Something to say Ben?? ****************************************************************************/ /* * Constructs an immutable grid fr...
std::vec::from_fn(width, |column| { assert_eq!(width, file_contents[row].len()); let file_value = file_contents[row][column]; return Cell { value: cell_value(file_value as char) }; }) }) }; } // fn build_from_file_contents /* Returns a count for how many neighbors of a cell i...
_ => fail!("Unexpected cell value found in file.") }; }; return Grid { inner: std::vec::from_fn(height, |row| {
random_line_split
grid_builder.rs
extern crate extra; extern crate std; use grid::{Row, Column, alive, dead, Cell, Grid}; mod grid; /**************************************************************************** * Something to say Ben?? ****************************************************************************/ /* * Constructs an immutable grid fr...
(Row(row): Row, Column(col): Column, grid: &Grid) -> uint { let left_column = Column(col - 1); let right_column = Column(col + 1); let above_row = Row(row - 1); let below_row = Row(row + 1); return grid.cell_alive(Row(row), left_column) + // left grid.cell_alive(above_row, left_column) + // le...
count_neighbors
identifier_name
utils.rs
use std::fmt; use std::path::{Path, PathBuf}; use std::fs::{self, File}; use rustc_serialize::{Encodable, Encoder}; use url::Url; use git2::{self, ObjectType}; use core::GitReference; use util::{CargoResult, ChainError, human, ToUrl, internal}; #[derive(PartialEq, Clone, Debug)] pub struct GitRevision(git2::Oid); i...
Err(..) => { try!(self.clone_into(into).chain_error(|| { human(format!("failed to clone into: {}", into.display())) })) } }; Ok(GitDatabase { remote: self.clone(), path: into.to_path_buf(), ...
{ try!(self.fetch_into(&repo).chain_error(|| { human(format!("failed to fetch into {}", into.display())) })); repo }
conditional_block
utils.rs
use std::fmt; use std::path::{Path, PathBuf}; use std::fs::{self, File}; use rustc_serialize::{Encodable, Encoder}; use url::Url; use git2::{self, ObjectType}; use core::GitReference; use util::{CargoResult, ChainError, human, ToUrl, internal}; #[derive(PartialEq, Clone, Debug)] pub struct GitRevision(git2::Oid); i...
(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } /// GitRemote represents a remote repository. It gets cloned into a local /// GitDatabase. #[derive(PartialEq,Clone,Debug)] pub struct GitRemote { url: Url, } #[derive(PartialEq,Clone,RustcEncodable)] struct EncodableGi...
fmt
identifier_name
utils.rs
use std::fmt; use std::path::{Path, PathBuf}; use std::fs::{self, File}; use rustc_serialize::{Encodable, Encoder}; use url::Url; use git2::{self, ObjectType}; use core::GitReference; use util::{CargoResult, ChainError, human, ToUrl, internal}; #[derive(PartialEq, Clone, Debug)] pub struct GitRevision(git2::Oid); i...
} fn is_fresh(&self) -> bool { match self.repo.revparse_single("HEAD") { Ok(ref head) if head.id() == self.revision.0 => { // See comments in reset() for why we check this fs::metadata(self.location.join(".cargo-ok")).is_ok() } _ => f...
{ let dirname = into.parent().unwrap(); try!(fs::create_dir_all(&dirname).chain_error(|| { human(format!("Couldn't mkdir {}", dirname.display())) })); if fs::metadata(&into).is_ok() { try!(fs::remove_dir_all(into).chain_error(|| { human(format!("...
identifier_body
utils.rs
use std::fmt; use std::path::{Path, PathBuf}; use std::fs::{self, File}; use rustc_serialize::{Encodable, Encoder}; use url::Url; use git2::{self, ObjectType}; use core::GitReference; use util::{CargoResult, ChainError, human, ToUrl, internal}; #[derive(PartialEq, Clone, Debug)] pub struct GitRevision(git2::Oid); i...
// We check the `allowed` types of credentials, and we try to do as much as // possible based on that: // // * Prioritize SSH keys from the local ssh agent as they're likely the most // reliable. The username here is prioritized from the credential // callback, then from whatever is configur...
random_line_split
gather_moves.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 ...
mc::cat_deref(b, _, mc::uniq_ptr(*)) | mc::cat_discr(b, _) => { check_is_legal_to_move_from(bccx, cmt0, b) } } }
{ match ty::get(b.ty).sty { ty::ty_struct(did, _) | ty::ty_enum(did, _) => { if ty::has_dtor(bccx.tcx, did) { bccx.span_err( cmt0.span, fmt!("cannot move out of type `%s`, \ ...
conditional_block
gather_moves.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 ...
(bccx: @BorrowckCtxt, cmt0: mc::cmt, cmt: mc::cmt) -> bool { match cmt.cat { mc::cat_implicit_self(*) | mc::cat_deref(_, _, mc::region_ptr(*)) | mc::cat_deref(_, _, mc::gc_ptr(*)) | mc::cat_deref(_, _, mc::unsafe_ptr(*)) =...
check_is_legal_to_move_from
identifier_name
gather_moves.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 ...
move_data.add_move(bccx.tcx, loan_path, closure_expr.id, Captured(closure_expr)); } moves::CapCopy | moves::CapRef => {} } } } pub fn gather_assignment(bccx: @BorrowckCtxt, move_data: &mut MoveData, ...
moves::CapMove => { let fvar_id = ast_util::def_id_of_def(captured_var.def).node; let loan_path = @LpVar(fvar_id);
random_line_split
gather_moves.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 ...
pub fn gather_move_from_pat(bccx: @BorrowckCtxt, move_data: &mut MoveData, move_pat: @ast::pat, cmt: mc::cmt) { gather_move_from_expr_or_pat(bccx, move_data, move_pat.id, MovePat(move_pat), cmt); }...
{ gather_move_from_expr_or_pat(bccx, move_data, move_expr.id, MoveExpr(move_expr), cmt); }
identifier_body
mod.rs
// c4puter embedded controller firmware // Copyright (C) 2017 Chris Pavlina // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later v...
// // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // //! Utilities for processing and displaying data mod parseint; mod hexprint; pub mod base64; pub mo...
// GNU General Public License for more details.
random_line_split
enum-discrim-manual-sizing.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 ...
pub fn main() { assert_eq!(size_of::<Ei8>(), 1); assert_eq!(size_of::<Eu8>(), 1); assert_eq!(size_of::<Ei16>(), 2); assert_eq!(size_of::<Eu16>(), 2); assert_eq!(size_of::<Ei32>(), 4); assert_eq!(size_of::<Eu32>(), 4); assert_eq!(size_of::<Ei64>(), 8); assert_eq!(size_of::<Eu64>(), 8); ...
_None, _Some(T), }
random_line_split
enum-discrim-manual-sizing.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 ...
{ Au32 = 0, Bu32 = 1 } #[repr(i64)] enum Ei64 { Ai64 = 0, Bi64 = 1 } #[repr(u64)] enum Eu64 { Au64 = 0, Bu64 = 1 } #[repr(isize)] enum Eint { Aint = 0, Bint = 1 } #[repr(usize)] enum Euint { Auint = 0, Buint = 1 } #[repr(u8)] enum Eu8NonCLike<T> { _None, _Some(T), }...
Eu32
identifier_name
node_style.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/. */ // Style retrieval from DOM elements. use css::node_util::NodeUtil; use layout::incremental::RestyleDamage; use l...
}
{ self.get_restyle_damage() }
identifier_body
node_style.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/. */ // Style retrieval from DOM elements. use css::node_util::NodeUtil; use layout::incremental::RestyleDamage; use l...
/// Node mixin providing `style` method that returns a `NodeStyle` pub trait StyledNode { fn style<'a>(&'a self) -> &'a Arc<ComputedValues>; fn restyle_damage(&self) -> RestyleDamage; } impl<'self> StyledNode for LayoutNode<'self> { #[inline] fn style<'a>(&'a self) -> &'a Arc<ComputedValues> { ...
use extra::arc::Arc; use style::ComputedValues;
random_line_split
node_style.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/. */ // Style retrieval from DOM elements. use css::node_util::NodeUtil; use layout::incremental::RestyleDamage; use l...
<'a>(&'a self) -> &'a Arc<ComputedValues> { self.get_css_select_results() } fn restyle_damage(&self) -> RestyleDamage { self.get_restyle_damage() } }
style
identifier_name
regions-infer-at-fn-not-param.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 ...
{ g: @fn() } fn take1(p: parameterized1) -> parameterized1 { p } //~ ERROR mismatched types fn take3(p: not_parameterized1) -> not_parameterized1 { p } fn take4(p: not_parameterized2) -> not_parameterized2 { p } fn main() {}
not_parameterized2
identifier_name
regions-infer-at-fn-not-param.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 ...
g: @fn() } fn take1(p: parameterized1) -> parameterized1 { p } //~ ERROR mismatched types fn take3(p: not_parameterized1) -> not_parameterized1 { p } fn take4(p: not_parameterized2) -> not_parameterized2 { p } fn main() {}
g: @fn() } struct not_parameterized2 {
random_line_split
proxy.rs
//! A proxy that forwards data to another server and forwards that server's //! responses back to clients. //! //! You can showcase this by running this in one terminal: //! //! cargo run --example proxy //! //! This in another terminal //! //! cargo run --example echo //! //! And finally this in another termin...
impl AsyncWrite for MyTcpStream { fn shutdown(&mut self) -> Poll<(), io::Error> { try!(self.0.shutdown(Shutdown::Write)); Ok(().into()) } }
} impl AsyncRead for MyTcpStream {}
random_line_split
proxy.rs
//! A proxy that forwards data to another server and forwards that server's //! responses back to clients. //! //! You can showcase this by running this in one terminal: //! //! cargo run --example proxy //! //! This in another terminal //! //! cargo run --example echo //! //! And finally this in another termin...
(Arc<TcpStream>); impl Read for MyTcpStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { (&*self.0).read(buf) } } impl Write for MyTcpStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (&*self.0).write(buf) } fn flush(&mut self) -> io::Result<()> { ...
MyTcpStream
identifier_name
proxy.rs
//! A proxy that forwards data to another server and forwards that server's //! responses back to clients. //! //! You can showcase this by running this in one terminal: //! //! cargo run --example proxy //! //! This in another terminal //! //! cargo run --example echo //! //! And finally this in another termin...
} impl Write for MyTcpStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (&*self.0).write(buf) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl AsyncRead for MyTcpStream {} impl AsyncWrite for MyTcpStream { fn shutdown(&mut self) -> Poll<(), io::Error> { ...
{ (&*self.0).read(buf) }
identifier_body
example.rs
static ABC: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; pub fn get_diamond(diamond_char: char) -> Vec<String> { let mut result: Vec<String> = Vec::new(); let diamond_char = diamond_char.to_ascii_uppercase(); if ABC.find(diamond_char).is_none() { return result; } if diamond_char == 'A' { re...
fn get_letter_line(char_in_abc: char) -> String { let mut r = String::new(); let odd = (0..) .filter(|x| x % 2!= 0) .nth(ABC.find(char_in_abc).unwrap()) .unwrap(); for i in 0..odd { if i == 0 || i == odd - 1 { r.push(char_in_abc); } else { r.pus...
{ let mut r = String::new(); let letter_e = get_letter_line(char_in_abc); let letter_c = get_letter_line(diamond_char); let ws = letter_c.len() - letter_e.len(); //number of whitespaces //left for _ in 0..ws / 2 { r.push(' '); } //letter line for i in letter_e.chars() { ...
identifier_body
example.rs
static ABC: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; pub fn get_diamond(diamond_char: char) -> Vec<String> { let mut result: Vec<String> = Vec::new(); let diamond_char = diamond_char.to_ascii_uppercase(); if ABC.find(diamond_char).is_none() { return result; } if diamond_char == 'A' { re...
for i in letter_e.chars() { r.push(i) } //right for _ in 0..ws / 2 { r.push(' '); } r } fn get_letter_line(char_in_abc: char) -> String { let mut r = String::new(); let odd = (0..) .filter(|x| x % 2!= 0) .nth(ABC.find(char_in_abc).unwrap()) .unwrap()...
//left for _ in 0..ws / 2 { r.push(' '); } //letter line
random_line_split
example.rs
static ABC: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; pub fn get_diamond(diamond_char: char) -> Vec<String> { let mut result: Vec<String> = Vec::new(); let diamond_char = diamond_char.to_ascii_uppercase(); if ABC.find(diamond_char).is_none() { return result; } if diamond_char == 'A'
//build first half for char_in_abc in ABC.chars() { result.push(get_line(char_in_abc, diamond_char).clone()); if char_in_abc == diamond_char { break; } } //build second half let mut rev = result.clone(); rev.pop(); //remove middle piece to avoid duplicates ...
{ return vec![String::from("A")]; }
conditional_block
example.rs
static ABC: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; pub fn get_diamond(diamond_char: char) -> Vec<String> { let mut result: Vec<String> = Vec::new(); let diamond_char = diamond_char.to_ascii_uppercase(); if ABC.find(diamond_char).is_none() { return result; } if diamond_char == 'A' { re...
(char_in_abc: char) -> String { let mut r = String::new(); let odd = (0..) .filter(|x| x % 2!= 0) .nth(ABC.find(char_in_abc).unwrap()) .unwrap(); for i in 0..odd { if i == 0 || i == odd - 1 { r.push(char_in_abc); } else { r.push(' '); } ...
get_letter_line
identifier_name
lib.rs
// Copyright 2016 Phillip Oppermann, Calvin Lee and JJ Garzella. // See the README.md file at the top-level directory of this // distribution. // // Licensed under the MIT license <LICENSE or // http://opensource.org/licenses/MIT>, at your option. // This file may not be copied, modified, or distributed // except accor...
unsafe { smp::CpuLocal::init() }; // Initialize the IDT interrupts::init(); // Initialize the serial port cpuio::init(); println!("Try to write some things!"); vga_buffer::change_color(vga_buffer::Color::White, vga_buffer::Color::Black); #[cfg(feature = "test")] { ...
// Initialize CPU local variables and the scheduler
random_line_split
lib.rs
// Copyright 2016 Phillip Oppermann, Calvin Lee and JJ Garzella. // See the README.md file at the top-level directory of this // distribution. // // Licensed under the MIT license <LICENSE or // http://opensource.org/licenses/MIT>, at your option. // This file may not be copied, modified, or distributed // except accor...
} // Initialize memory memory::init(&boot_info); // Initialize CPU local variables and the scheduler unsafe { smp::CpuLocal::init() }; // Initialize the IDT interrupts::init(); // Initialize the serial port cpuio::init(); println!("Try to write some things!"); ...
{ let addr = module.start_address() as usize + memory::KERNEL_BASE; unsafe { interrupts::KEYBOARD.lock() .change_kbmap(&*(addr as *const [u8; 128])); } }
conditional_block
lib.rs
// Copyright 2016 Phillip Oppermann, Calvin Lee and JJ Garzella. // See the README.md file at the top-level directory of this // distribution. // // Licensed under the MIT license <LICENSE or // http://opensource.org/licenses/MIT>, at your option. // This file may not be copied, modified, or distributed // except accor...
(_: Layout) ->! { panic!("Error, out of memory"); } /// Runs during a `panic!()` #[panic_handler] extern "C" fn panic_fmt(pi: &core::panic::PanicInfo) ->! { vga_buffer::change_color(vga_buffer::Color::Red, vga_buffer::Color::Black); println!("\n\nESALP {}", pi); #[cfg(feature = "test")] { seri...
oom
identifier_name
lib.rs
// Copyright 2016 Phillip Oppermann, Calvin Lee and JJ Garzella. // See the README.md file at the top-level directory of this // distribution. // // Licensed under the MIT license <LICENSE or // http://opensource.org/licenses/MIT>, at your option. // This file may not be copied, modified, or distributed // except accor...
unsafe { smp::CpuLocal::init() }; // Initialize the IDT interrupts::init(); // Initialize the serial port cpuio::init(); println!("Try to write some things!"); vga_buffer::change_color(vga_buffer::Color::White, vga_buffer::Color::Black); #[cfg(feature = "test")] { ...
{ vga_buffer::clear_screen(); println!("Hello Rust log \x01"); let boot_info = unsafe { multiboot2::load(multiboot_info_address) }; for module in boot_info.module_tags() { if module.name() == "keyboard" { let addr = module.start_address() as usize + memory::KERNEL_BASE; ...
identifier_body
aabb.rs
use cgmath::prelude::*; use cgmath::Point3; use crate::consts; use crate::float::*; use crate::intersect::{Intersect, Ray}; #[derive(Clone, Debug)] pub struct Aabb { pub min: Point3<Float>, pub max: Point3<Float>, } impl Aabb { pub fn empty() -> Aabb { Aabb { min: Point3::max_value(),...
} p_min } pub fn max_point(p1: &Point3<Float>, p2: &Point3<Float>) -> Point3<Float> { let mut p_max = Point3::min_value(); for i in 0..3 { p_max[i] = p1[i].max(p2[i]); } p_max }
pub fn min_point(p1: &Point3<Float>, p2: &Point3<Float>) -> Point3<Float> { let mut p_min = Point3::max_value(); for i in 0..3 { p_min[i] = p1[i].min(p2[i]);
random_line_split
aabb.rs
use cgmath::prelude::*; use cgmath::Point3; use crate::consts; use crate::float::*; use crate::intersect::{Intersect, Ray}; #[derive(Clone, Debug)] pub struct Aabb { pub min: Point3<Float>, pub max: Point3<Float>, } impl Aabb { pub fn empty() -> Aabb { Aabb { min: Point3::max_value(),...
} impl Intersect<'_, Float> for Aabb { fn intersect(&self, ray: &Ray) -> Option<Float> { let t1 = (self.min - ray.orig).mul_element_wise(ray.reciprocal_dir); let t2 = (self.max - ray.orig).mul_element_wise(ray.reciprocal_dir); let mut start = consts::MIN; let mut end = consts::MAX;...
{ let lengths = self.max - self.min; 2.0 * (lengths.x * lengths.y + lengths.y * lengths.z + lengths.z * lengths.x).max(0.0) }
identifier_body
aabb.rs
use cgmath::prelude::*; use cgmath::Point3; use crate::consts; use crate::float::*; use crate::intersect::{Intersect, Ray}; #[derive(Clone, Debug)] pub struct Aabb { pub min: Point3<Float>, pub max: Point3<Float>, } impl Aabb { pub fn empty() -> Aabb { Aabb { min: Point3::max_value(),...
} } pub fn min_point(p1: &Point3<Float>, p2: &Point3<Float>) -> Point3<Float> { let mut p_min = Point3::max_value(); for i in 0..3 { p_min[i] = p1[i].min(p2[i]); } p_min } pub fn max_point(p1: &Point3<Float>, p2: &Point3<Float>) -> Point3<Float> { let mut p_max = Point3::min_value(); ...
{ None }
conditional_block
aabb.rs
use cgmath::prelude::*; use cgmath::Point3; use crate::consts; use crate::float::*; use crate::intersect::{Intersect, Ray}; #[derive(Clone, Debug)] pub struct
{ pub min: Point3<Float>, pub max: Point3<Float>, } impl Aabb { pub fn empty() -> Aabb { Aabb { min: Point3::max_value(), max: Point3::min_value(), } } /// Update the bounding box to enclose other aswell pub fn add_aabb(&mut self, other: &Aabb) { ...
Aabb
identifier_name
step1_read_print.rs
use rust_mal_lib::env::{Env, Environment}; use rust_mal_lib::reader; use rust_mal_lib::types::{MalError, MalResult, MalValue}; use rust_mal_steps::scaffold::*; fn read(string: &str) -> MalResult { reader::read_str(string) } fn eval(ast: MalValue) -> MalResult { Ok(ast) } fn print(expr: MalValue) -> String {...
() -> Result<Env, MalError> { Ok(Environment::new(None)) } fn rep(input: &str, _: &Env) -> Result<String, MalError> { let ast = read(input)?; let expr = eval(ast)?; Ok(print(expr)) } } fn main() -> Result<(), String> { cli_loop::<Env, Step1ReadPrint>() } #[cfg(test)] m...
create_env
identifier_name
step1_read_print.rs
use rust_mal_lib::env::{Env, Environment}; use rust_mal_lib::reader; use rust_mal_lib::types::{MalError, MalResult, MalValue}; use rust_mal_steps::scaffold::*; fn read(string: &str) -> MalResult { reader::read_str(string) } fn eval(ast: MalValue) -> MalResult { Ok(ast) } fn print(expr: MalValue) -> String {...
Ok(Environment::new(None)) } fn rep(input: &str, _: &Env) -> Result<String, MalError> { let ast = read(input)?; let expr = eval(ast)?; Ok(print(expr)) } } fn main() -> Result<(), String> { cli_loop::<Env, Step1ReadPrint>() } #[cfg(test)] mod tests { use super::*; ...
fn create_env() -> Result<Env, MalError> {
random_line_split
geth.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
(&self, address: &Address) -> Result<(), Error> { self.dir.remove(address) } }
remove
identifier_name
geth.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
} #[cfg(windows)] /// Default path for ethereum installation on Windows pub fn geth_dir_path() -> PathBuf { let mut home = env::home_dir().expect("Failed to get home dir"); home.push("AppData"); home.push("Roaming"); home.push("Ethereum"); home } #[cfg(not(any(target_os = "macos", windows)))] /// Default path fo...
home.push("Ethereum"); home
random_line_split
geth.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
pub fn open(t: DirectoryType) -> Self { GethDirectory { dir: DiskDirectory::at(geth_keystore(t)), } } } impl KeyDirectory for GethDirectory { fn load(&self) -> Result<Vec<SafeAccount>, Error> { self.dir.load() } fn insert(&self, account: SafeAccount) -> Result<SafeAccount, Error> { self.dir.insert(a...
{ let result = GethDirectory { dir: try!(DiskDirectory::create(geth_keystore(t))), }; Ok(result) }
identifier_body
part1.rs
// adventofcode - day 12 // part 1 use std::io::prelude::*; use std::fs::File; fn main()
0 }, _ if last.is_digit(10) => { let tmp = tmp_val * multiplier; tmp_val = 0; multiplier = 1; tmp } _ => 0, }; last = ch; } println!("Value: {}", value); } // Thi...
{ println!("Advent of Code - day 12 | part 1"); // import data let data = import_data(); let mut value = 0i32; let mut tmp_val = 0i32; let mut last: char = '\x00'; let mut multiplier = 1; for ch in data.chars() { value += match ch { '0'...'9' => { if...
identifier_body
part1.rs
// adventofcode - day 12 // part 1 use std::io::prelude::*; use std::fs::File; fn main(){ println!("Advent of Code - day 12 | part 1"); // import data let data = import_data(); let mut value = 0i32; let mut tmp_val = 0i32; let mut last: char = '\x00'; let mut multiplier = 1; for ch i...
}
random_line_split
part1.rs
// adventofcode - day 12 // part 1 use std::io::prelude::*; use std::fs::File; fn main(){ println!("Advent of Code - day 12 | part 1"); // import data let data = import_data(); let mut value = 0i32; let mut tmp_val = 0i32; let mut last: char = '\x00'; let mut multiplier = 1; for ch i...
() -> String { let mut file = match File::open("../../inputs/12.txt") { Ok(f) => f, Err(e) => panic!("file error: {}", e), }; let mut data = String::new(); match file.read_to_string(&mut data){ Ok(_) => {}, Err(e) => panic!("file error: {}", e), }; data }
import_data
identifier_name
data.rs
use redox::prelude::v1::*; use table::NodeTable; /// A data node (file/dir) pub enum Data { /// File File(File), /// Directory Dir(Dir), /// Nothing Nil, } impl Data { pub fn name(&self) -> &str { match self { &Data::File(ref f) => &f.name, &Data::Dir(ref d)...
/// A file pub struct File { /// The name of the file name: String, /// The actual content of the file data: Vec<u8>, } impl File { /// Create a file from a slice of bytes pub fn from_bytes(b: &[u8]) -> Self { let name = unsafe { String::from_utf8_unchecked(b[0..64].to_vec(...
}
random_line_split
data.rs
use redox::prelude::v1::*; use table::NodeTable; /// A data node (file/dir) pub enum Data { /// File File(File), /// Directory Dir(Dir), /// Nothing Nil, } impl Data { pub fn
(&self) -> &str { match self { &Data::File(ref f) => &f.name, &Data::Dir(ref d) => &d.name, &Data::Nil => "\0", } } } /// A file pub struct File { /// The name of the file name: String, /// The actual content of the file data: Vec<u8>, } impl Fil...
name
identifier_name
parser.rs
mod lex; use lex::lexeme::Lexeme; pub struct Parser<'a> { next: usize, tokens: Vec<Lexeme> } impl<'a> Parser<'a> { pub fn new(tokens: Vec<Lexeme>) -> Parser { Parser { next: 0, tokens: tokens } } pub fn parse(&self) -> Box<Expr> { let mut block: Vec...
(&self) -> bool { match self.get_token() { Lexeme::Plus | Lexeme::Minus | Lexeme::Multiply | Lexeme::Divide | Lexeme::Modulo => true, _ => false } } }
operator
identifier_name
parser.rs
mod lex; use lex::lexeme::Lexeme; pub struct Parser<'a> { next: usize, tokens: Vec<Lexeme> } impl<'a> Parser<'a> { pub fn new(tokens: Vec<Lexeme>) -> Parser { Parser { next: 0, tokens: tokens } } pub fn parse(&self) -> Box<Expr> { let mut block: Vec...
fn expect(&self, token: Lexeme) -> bool { if self.get_token() == token { true } else { false } } fn operator(&self) -> bool { match self.get_token() { Lexeme::Plus | Lexeme::Minus | Lexeme::Multiply | Lexeme::Divide | Lexeme::Modulo => true, _ => false } ...
{ self.next == tokens.len() }
identifier_body
parser.rs
mod lex;
pub struct Parser<'a> { next: usize, tokens: Vec<Lexeme> } impl<'a> Parser<'a> { pub fn new(tokens: Vec<Lexeme>) -> Parser { Parser { next: 0, tokens: tokens } } pub fn parse(&self) -> Box<Expr> { let mut block: Vec<Box<Expr>> = Vec::new(); ...
use lex::lexeme::Lexeme;
random_line_split
regions-infer-borrow-scope.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 ...
pub fn main() { let p: Box<_> = box Point {x: 3, y: 4}; let xc = x_coord(&*p); assert_eq!(*xc, 3); }
{ return &p.x; }
identifier_body
regions-infer-borrow-scope.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 ...
pub fn main() { let p: Box<_> = box Point {x: 3, y: 4}; let xc = x_coord(&*p); assert_eq!(*xc, 3); }
random_line_split
regions-infer-borrow-scope.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: isize, y: isize} fn x_coord(p: &Point) -> &isize { return &p.x; } pub fn main() { let p: Box<_> = box Point {x: 3, y: 4}; let xc = x_coord(&*p); assert_eq!(*xc, 3); }
Point
identifier_name
stability-attribute-sanity-2.rs
// Copyright 2015 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() { }
f3
identifier_name
stability-attribute-sanity-2.rs
// Copyright 2015 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() { }
fn f3() { }
random_line_split
stability-attribute-sanity-2.rs
// Copyright 2015 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() { }
{ }
identifier_body
similarity_matrix.rs
use crate::{Edges, Graph, NodeColorMatching, ScoreNorm}; use approx::relative_eq; use closed01::Closed01; use munkres::{solve_assignment, Position, WeightMatrix}; use ndarray::{Array2, FoldWhile, Zip}; use std::{cmp, mem}; type Matrix = Array2<f32>; #[derive(Debug)] pub struct SimilarityMatrix<'a, F, G, E, N> where ...
(&self) -> Closed01<f32> { let n = self.min_nodes(); if n > 0 { let sum: f32 = self.current.iter().fold(0.0, |acc, &v| acc + v); let len = self.current.shape().len(); assert!(len > 0); Closed01::new(sum / len as f32) } else { Closed01::...
score_average
identifier_name
similarity_matrix.rs
use crate::{Edges, Graph, NodeColorMatching, ScoreNorm}; use approx::relative_eq; use closed01::Closed01; use munkres::{solve_assignment, Position, WeightMatrix}; use ndarray::{Array2, FoldWhile, Zip}; use std::{cmp, mem}; type Matrix = Array2<f32>; #[derive(Debug)] pub struct SimilarityMatrix<'a, F, G, E, N> where ...
pub fn max_nodes(&self) -> usize { cmp::max(self.current.nrows(), self.current.ncols()) } pub fn optimal_node_assignment(&self) -> Vec<Position> { let n = self.min_nodes(); let assignment = if n > 0 { let mut w = WeightMatrix::from_fn(n, |ij| similarity_cost(self.current...
pub fn min_nodes(&self) -> usize { cmp::min(self.current.nrows(), self.current.ncols()) }
random_line_split
similarity_matrix.rs
use crate::{Edges, Graph, NodeColorMatching, ScoreNorm}; use approx::relative_eq; use closed01::Closed01; use munkres::{solve_assignment, Position, WeightMatrix}; use ndarray::{Array2, FoldWhile, Zip}; use std::{cmp, mem}; type Matrix = Array2<f32>; #[derive(Debug)] pub struct SimilarityMatrix<'a, F, G, E, N> where ...
/// Calculates the next iteration of the similarity matrix (x[k+1]). pub fn next(&mut self) { { let x = &self.current; for ((i, j), new_x_ij) in self.previous.indexed_iter_mut() { let scale = self .node_color_matching .node_...
{ Zip::from(&self.previous) .and(&self.current) .fold_while(true, |all_prev_in_eps, x, y| { if all_prev_in_eps && relative_eq!(x, y, epsilon = eps) { FoldWhile::Continue(true) } else { FoldWhile::Done(false) ...
identifier_body
parallel.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/. */ //! Implements parallel traversals over the DOM and flow trees. //! //! This code is highly unsafe. Keep this file...
}, shared_layout_context); }
});
random_line_split
parallel.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/. */ //! Implements parallel traversals over the DOM and flow trees. //! //! This code is highly unsafe. Keep this file...
() -> FlowParallelInfo { FlowParallelInfo { children_count: AtomicIsize::new(0), parent: null_unsafe_flow(), } } } /// A parallel bottom-up flow traversal. trait ParallelPostorderFlowTraversal : PostorderFlowTraversal { /// Process current flow and potentially traverse i...
new
identifier_name
parallel.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/. */ //! Implements parallel traversals over the DOM and flow trees. //! //! This code is highly unsafe. Keep this file...
{ if opts::get().bubble_inline_sizes_separately { let layout_context = LayoutContext::new(shared_layout_context); let bubble_inline_sizes = BubbleISizes { layout_context: &layout_context }; flow_ref::deref_mut(root).traverse_postorder(&bubble_inline_sizes); } run_queue_with_custom_w...
identifier_body
parallel.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/. */ //! Implements parallel traversals over the DOM and flow trees. //! //! This code is highly unsafe. Keep this file...
if self.should_process(flow) { // Perform the appropriate traversal. self.process(flow); } // Possibly enqueue the children. for kid in flow::child_iter(flow) { had_children = true; ...
{ flow::mut_base(flow).thread_id = proxy.worker_index(); }
conditional_block
error.rs
use std::error; use std::ffi::CStr; use std::fmt; use std::os::raw::c_int; use std::result; use std::str; /// Error codes that the library might return. #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)] pub enum Error { /// DNS server returned answer with no data. ENODATA = c_ares_sys::ARES_E...
(&self, fmt: &mut fmt::Formatter) -> result::Result<(), fmt::Error> { let text = unsafe { let ptr = c_ares_sys::ares_strerror(*self as c_int); let buf = CStr::from_ptr(ptr).to_bytes(); str::from_utf8_unchecked(buf) }; fmt.write_str(text) } } impl From<i32...
fmt
identifier_name
error.rs
use std::error; use std::ffi::CStr; use std::fmt; use std::os::raw::c_int; use std::result; use std::str; /// Error codes that the library might return.
ENODATA = c_ares_sys::ARES_ENODATA as isize, /// DNS server claims query was misformatted. EFORMERR = c_ares_sys::ARES_EFORMERR as isize, /// DNS server returned general failure. ESERVFAIL = c_ares_sys::ARES_ESERVFAIL as isize, /// Domain name not found. ENOTFOUND = c_ares_sys::ARES_ENOTF...
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)] pub enum Error { /// DNS server returned answer with no data.
random_line_split
error.rs
use std::error; use std::ffi::CStr; use std::fmt; use std::os::raw::c_int; use std::result; use std::str; /// Error codes that the library might return. #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)] pub enum Error { /// DNS server returned answer with no data. ENODATA = c_ares_sys::ARES_E...
} impl From<i32> for Error { fn from(code: i32) -> Self { match code { c_ares_sys::ARES_ENODATA => Error::ENODATA, c_ares_sys::ARES_EFORMERR => Error::EFORMERR, c_ares_sys::ARES_ESERVFAIL => Error::ESERVFAIL, c_ares_sys::ARES_ENOTFOUND => Error::ENOTFOUND, ...
{ let text = unsafe { let ptr = c_ares_sys::ares_strerror(*self as c_int); let buf = CStr::from_ptr(ptr).to_bytes(); str::from_utf8_unchecked(buf) }; fmt.write_str(text) }
identifier_body
extends.rs
// The MIT License (MIT) // // Copyright (c) 2015 Vladislav Orlov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use,...
(body: String, _iter: &mut Iter<Token>) -> Result<Option<NodeType>> { Ok(Some(NodeType::Extends(ExtendsNode::new(body)))) }
build
identifier_name
extends.rs
// The MIT License (MIT) // // Copyright (c) 2015 Vladislav Orlov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use,...
{ Ok(Some(NodeType::Extends(ExtendsNode::new(body)))) }
identifier_body
extends.rs
// The MIT License (MIT) // // Copyright (c) 2015 Vladislav Orlov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use,...
use ast::ExtendsNode; use scanner::Token; pub fn build(body: String, _iter: &mut Iter<Token>) -> Result<Option<NodeType>> { Ok(Some(NodeType::Extends(ExtendsNode::new(body)))) }
random_line_split
media_queries.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::ascii::StrAsciiExt; use cssparser::parse_rule_list; use cssparser::ast::*; use errors::{ErrorLoggerItera...
rules: ~[CSSRule], } pub struct MediaQueryList { // "not all" is omitted from the list. // An empty list never matches. media_queries: ~[MediaQuery] } // For now, this is a "Level 2 MQ", ie. a media type. struct MediaQuery { media_type: MediaQueryType, // TODO: Level 3 MQ expressions } enum...
pub struct MediaRule { media_queries: MediaQueryList,
random_line_split
media_queries.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::ascii::StrAsciiExt; use cssparser::parse_rule_list; use cssparser::ast::*; use errors::{ErrorLoggerItera...
{ media_type: MediaQueryType, // TODO: Level 3 MQ expressions } enum MediaQueryType { All, // Always true MediaType(MediaType), } #[deriving(Eq)] pub enum MediaType { Screen, Print, } pub struct Device { media_type: MediaType, // TODO: Level 3 MQ data: viewport size, etc. } pub f...
MediaQuery
identifier_name
media_queries.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::ascii::StrAsciiExt; use cssparser::parse_rule_list; use cssparser::ast::*; use errors::{ErrorLoggerItera...
, // Ingnore this comma-separated part _ => loop { match iter.next() { Some(&Comma) => break, None => return MediaQueryList{ media_queries: queries }, _ => (), } }, } next = it...
{ for mq in mq.move_iter() { queries.push(mq); } }
conditional_block
call_once.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::ops::FnMut; use core::ops::FnOnce; type T = i32; struct F; type Args = (T,); impl FnOnce<Args> for F { type Output = T; extern "rust-call" fn call_once(self, (x,): Args) -> Self::Output { x + 1...
assert_eq!(result, 70); } #[test] fn call_once_test2() { fn foo<F: FnOnce(T) -> T>(f: F, x: T) -> T { f(x) } let mut f: F = F; let f_ptr: &mut F = &mut f; let x: T = 68; let result: T = foo(f_ptr, x); assert_eq!(result, x + 2); assert_eq!(result, 70); } }
assert_eq!(result, x + 2);
random_line_split
call_once.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::ops::FnMut; use core::ops::FnOnce; type T = i32; struct F; type Args = (T,); impl FnOnce<Args> for F { type Output = T; extern "rust-call" fn
(self, (x,): Args) -> Self::Output { x + 1 } } impl FnMut<Args> for F { extern "rust-call" fn call_mut(&mut self, (x,): Args) -> Self::Output { x + 2 } } #[test] fn call_once_test1() { let mut f: F = F; let f_ptr: &mut F = &mut f; let x: T = 68; let result: T = f_ptr.call_once((x,...
call_once
identifier_name
call_once.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::ops::FnMut; use core::ops::FnOnce; type T = i32; struct F; type Args = (T,); impl FnOnce<Args> for F { type Output = T; extern "rust-call" fn call_once(self, (x,): Args) -> Self::Output
} impl FnMut<Args> for F { extern "rust-call" fn call_mut(&mut self, (x,): Args) -> Self::Output { x + 2 } } #[test] fn call_once_test1() { let mut f: F = F; let f_ptr: &mut F = &mut f; let x: T = 68; let result: T = f_ptr.call_once((x,)); assert_eq!(result, x + 2); assert_eq!(resul...
{ x + 1 }
identifier_body
lzw.rs
//! This modules provides an implementation of the Lempel–Ziv–Welch Compression Algorithm // Note: This implementation borrows heavily from the work of Julius Pettersson // See http://www.cplusplus.com/articles/iL18T05o/ for his extensive explanations // and a C++ implementatation use std::io; use std::io::Read; use...
c > entry.c { if let Some(k) = entry.right { j = k } else { entry.right = Some(table_size); break; } } else { return Som...
if let Some(k) = entry.left { j = k } else { entry.left = Some(table_size); break; } } else if
conditional_block
lzw.rs
//! This modules provides an implementation of the Lempel–Ziv–Welch Compression Algorithm // Note: This implementation borrows heavily from the work of Julius Pettersson // See http://www.cplusplus.com/articles/iL18T05o/ for his extensive explanations // and a C++ implementatation use std::io; use std::io::Read; use...
> Code { 1u16 << self.min_size } #[inline(always)] fn end_code(&self) -> Code { self.clear_code() + 1 } // Searches for a new prefix fn search_and_insert(&mut self, i: Option<Code>, c: u8) -> Option<Code> { if let Some(i) = i.map(|v| v as usize) { let table_...
e(&self) -
identifier_name
lzw.rs
//! This modules provides an implementation of the Lempel–Ziv–Welch Compression Algorithm // Note: This implementation borrows heavily from the work of Julius Pettersson // See http://www.cplusplus.com/articles/iL18T05o/ for his extensive explanations // and a C++ implementatation use std::io; use std::io::Read; use...
search_initials(&self, i: Code) -> Code { self.table[i as usize].c as Code } } /// Convenience function that reads and compresses all bytes from `R`. pub fn encode<R, W>(r: R, mut w: W, min_code_size: u8) -> io::Result<()> where R: Read, W: BitWriter, { let mut dict = EncodingDict::new(min_code...
self.table.len() } fn
identifier_body
lzw.rs
//! This modules provides an implementation of the Lempel–Ziv–Welch Compression Algorithm // Note: This implementation borrows heavily from the work of Julius Pettersson // See http://www.cplusplus.com/articles/iL18T05o/ for his extensive explanations // and a C++ implementatation use std::io; use std::io::Read; use...
self.push_node(Node::new(i as u8)); } } #[inline(always)] fn push_node(&mut self, node: Node) { self.table.push(node) } #[inline(always)] fn clear_code(&self) -> Code { 1u16 << self.min_size } #[inline(always)] fn end_code(&self) -> Code { ...
} fn reset(&mut self) { self.table.clear(); for i in 0..(1u16 << self.min_size as usize) {
random_line_split
htmldivelement.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::HTMLDivElementBinding::{self, HTMLDivElementMethods}; use dom::bindings::js:...
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLDivElement { HTMLDivElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMSt...
new_inherited
identifier_name
htmldivelement.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::HTMLDivElementBinding::{self, HTMLDivElementMethods}; use dom::bindings::js:...
// https://html.spec.whatwg.org/multipage/#dom-div-align make_setter!(SetAlign, "align"); }
random_line_split
problem_0005.rs
extern crate projecteuler; use projecteuler::primes::*; use std::collections::HashMap; fn main()
result *= x.0.pow(x.1 as u32);//gather all the prime exponents together } result }; println!("{}", result); }
{ let mut result_factorized = HashMap::<u64,u64>::new(); let mut primes = Primes::new(); for i in 1..21{//TODO: Make this a LCM function. let factorization = primes.factorize(i); for factor in factorization{ let current_factor = match result_factorized.get(&factor.0){ Some(i) => {*i}, ...
identifier_body
problem_0005.rs
extern crate projecteuler; use projecteuler::primes::*; use std::collections::HashMap; fn
(){ let mut result_factorized = HashMap::<u64,u64>::new(); let mut primes = Primes::new(); for i in 1..21{//TODO: Make this a LCM function. let factorization = primes.factorize(i); for factor in factorization{ let current_factor = match result_factorized.get(&factor.0){ Some(i) => {*i}, ...
main
identifier_name
problem_0005.rs
extern crate projecteuler; use projecteuler::primes::*; use std::collections::HashMap; fn main(){ let mut result_factorized = HashMap::<u64,u64>::new();
let mut primes = Primes::new(); for i in 1..21{//TODO: Make this a LCM function. let factorization = primes.factorize(i); for factor in factorization{ let current_factor = match result_factorized.get(&factor.0){ Some(i) => {*i}, _ => {0} }; if current_factor < factor.1{ ...
random_line_split
problem_0005.rs
extern crate projecteuler; use projecteuler::primes::*; use std::collections::HashMap; fn main(){ let mut result_factorized = HashMap::<u64,u64>::new(); let mut primes = Primes::new(); for i in 1..21{//TODO: Make this a LCM function. let factorization = primes.factorize(i); for factor in factorization{ ...
}; if current_factor < factor.1{ result_factorized.insert(factor.0, factor.1); } } } let result = { let mut result = 1; for x in result_factorized{ result *= x.0.pow(x.1 as u32);//gather all the prime exponents together } result }; println!("{}", result); ...
{0}
conditional_block
expect.rs
use std::fmt; use std::str; use unicase::UniCase; use header::{Header, HeaderFormat}; /// The `Expect` header. /// /// > The "Expect" header field in a request indicates a certain set of /// > behaviors (expectations) that need to be supported by the server in /// > order to properly handle this request. The only s...
fn parse_header(raw: &[Vec<u8>]) -> Option<Expect> { if raw.len() == 1 { let text = unsafe { // safe because: // 1. we just checked raw.len == 1 // 2. we don't actually care if it's utf8, we just want to // compare the bytes wi...
{ "Expect" }
identifier_body
expect.rs
use std::fmt; use std::str; use unicase::UniCase; use header::{Header, HeaderFormat}; /// The `Expect` header. /// /// > The "Expect" header field in a request indicates a certain set of /// > behaviors (expectations) that need to be supported by the server in /// > order to properly handle this request. The only s...
(raw: &[Vec<u8>]) -> Option<Expect> { if raw.len() == 1 { let text = unsafe { // safe because: // 1. we just checked raw.len == 1 // 2. we don't actually care if it's utf8, we just want to // compare the bytes with the "case" normali...
parse_header
identifier_name
expect.rs
use std::fmt; use std::str; use unicase::UniCase; use header::{Header, HeaderFormat}; /// The `Expect` header. /// /// > The "Expect" header field in a request indicates a certain set of /// > behaviors (expectations) that need to be supported by the server in /// > order to properly handle this request. The only s...
else { None } } } impl HeaderFormat for Expect { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("100-continue") } }
{ let text = unsafe { // safe because: // 1. we just checked raw.len == 1 // 2. we don't actually care if it's utf8, we just want to // compare the bytes with the "case" normalized. If it's not // utf8, then the byte compa...
conditional_block
expect.rs
use std::fmt; use std::str; use unicase::UniCase; use header::{Header, HeaderFormat}; /// The `Expect` header. /// /// > The "Expect" header field in a request indicates a certain set of /// > behaviors (expectations) that need to be supported by the server in /// > order to properly handle this request. The only s...
str::from_utf8_unchecked(raw.get_unchecked(0)) }; if UniCase(text) == EXPECT_CONTINUE { Some(Expect::Continue) } else { None } } else { None } } } impl HeaderFormat for Expect { fn fmt_he...
// 1. we just checked raw.len == 1 // 2. we don't actually care if it's utf8, we just want to // compare the bytes with the "case" normalized. If it's not // utf8, then the byte comparison will fail, and we'll return // None. No bi...
random_line_split
search_errors.rs
use std::env; use std::fs::File; use std::io::{BufWriter, Write}; use std::path::PathBuf; use calamine::{open_workbook_auto, DataType, Error, Reader}; use glob::{glob, GlobError, GlobResult}; #[derive(Debug)] enum FileStatus { VbaError(Error), RangeError(Error), Glob(GlobError), } fn main() { // Sear...
(f: GlobResult) -> Result<(PathBuf, Option<usize>, usize), FileStatus> { let f = f.map_err(FileStatus::Glob)?; println!("Analysing {:?}", f.display()); let mut xl = open_workbook_auto(&f).unwrap(); let mut missing = None; let mut cell_errors = 0; match xl.vba_project() { Some(Ok(vba)) ...
run
identifier_name
search_errors.rs
use std::env; use std::fs::File; use std::io::{BufWriter, Write}; use std::path::PathBuf; use calamine::{open_workbook_auto, DataType, Error, Reader}; use glob::{glob, GlobError, GlobResult}; #[derive(Debug)] enum FileStatus { VbaError(Error), RangeError(Error), Glob(GlobError), }
// Output statistics: nb broken references, nb broken cells etc... let folder = env::args().nth(1).unwrap_or_else(|| ".".to_string()); let pattern = format!("{}/**/*.xl*", folder); let mut filecount = 0; let mut output = pattern .chars() .take_while(|c| *c!= '*') .filter_map(|c...
fn main() { // Search recursively for all excel files matching argument pattern
random_line_split
webhooks.rs
use std::io::Read; use crypto::hmac::Hmac; use crypto::mac::Mac; use crypto::mac::MacResult; use crypto::sha1::Sha1; use hex::FromHex; use iron; use serde_json; use DB_POOL; use builds; use config::CONFIG; use error::DashResult; use github::models::{CommentFromJson, IssueFromJson, PullRequestFromJson}; use github::{h...
"public" | "pull_request_review_comment" | "pull_request_review" | "push" | "repository" | "release" | "team" | "team_add" | "watch" => { info!("Received {} event, ignoring...", event_name); Ok(Payload::Unsupported) ...
{ match event_name { "issue_comment" => Ok(Payload::IssueComment(serde_json::from_str(body)?)), "issues" => Ok(Payload::Issues(serde_json::from_str(body)?)), "pull_request" => Ok(Payload::PullRequest(serde_json::from_str(body)?)), "status" => Ok(Payload::Status(serde_json::from_str(b...
identifier_body
webhooks.rs
use std::io::Read; use crypto::hmac::Hmac; use crypto::mac::Mac; use crypto::mac::MacResult; use crypto::sha1::Sha1; use hex::FromHex; use iron; use serde_json; use DB_POOL; use builds; use config::CONFIG; use error::DashResult; use github::models::{CommentFromJson, IssueFromJson, PullRequestFromJson}; use github::{h...
{ action: String, issue: IssueFromJson, repository: Repository, comment: CommentFromJson, } #[derive(Debug, Deserialize)] struct PullRequestEvent { action: String, repository: Repository, number: i32, pull_request: PullRequestFromJson, } #[derive(Debug, Deserialize)] struct Repository...
IssueCommentEvent
identifier_name
webhooks.rs
use std::io::Read; use crypto::hmac::Hmac; use crypto::mac::Mac; use crypto::mac::MacResult; use crypto::sha1::Sha1; use hex::FromHex; use iron; use serde_json; use DB_POOL; use builds; use config::CONFIG; use error::DashResult; use github::models::{CommentFromJson, IssueFromJson, PullRequestFromJson}; use github::{h...
}, Payload::Unsupported => (), } Ok(()) } #[derive(Debug)] struct Event { delivery_id: String, event_name: String, payload: Payload, } #[derive(Debug)] enum Payload { Issues(IssuesEvent), IssueComment(IssueCommentEvent), PullRequest(PullRequestEvent), Status(Stat...
{ if let Some(url) = status_event.target_url { builds::ingest_status_event(url)? } }
conditional_block
webhooks.rs
use std::io::Read; use crypto::hmac::Hmac; use crypto::mac::Mac; use crypto::mac::MacResult; use crypto::sha1::Sha1; use hex::FromHex; use iron; use serde_json; use DB_POOL; use builds; use config::CONFIG; use error::DashResult; use github::models::{CommentFromJson, IssueFromJson, PullRequestFromJson}; use github::{h...
} fn authenticate(secret: &str, payload: &str, signature: &str) -> bool { // https://developer.github.com/webhooks/securing/#validating-payloads-from-github let sans_prefix = signature[5..].as_bytes(); match Vec::from_hex(sans_prefix) { Ok(sigbytes) => { let mut mac = Hmac::new(Sha1::ne...
Ok(())
random_line_split
test.rs
use intern::intern; use grammar::repr::*; use test_util::{normalized_grammar}; use super::lalr_states; use super::super::interpret::interpret; fn
(t: &str) -> NonterminalString { NonterminalString(intern(t)) } macro_rules! tokens { ($($x:expr),*) => { vec![$(TerminalString::Quoted(intern($x))),*].into_iter() } } #[test] fn figure9_23() { let grammar = normalized_grammar(r#" grammar; extern { enum Tok { } } S: () ...
nt
identifier_name
test.rs
use intern::intern; use grammar::repr::*; use test_util::{normalized_grammar}; use super::lalr_states; use super::super::interpret::interpret; fn nt(t: &str) -> NonterminalString
macro_rules! tokens { ($($x:expr),*) => { vec![$(TerminalString::Quoted(intern($x))),*].into_iter() } } #[test] fn figure9_23() { let grammar = normalized_grammar(r#" grammar; extern { enum Tok { } } S: () = E => (); E: () = { E "-" T => (); ...
{ NonterminalString(intern(t)) }
identifier_body
test.rs
use intern::intern; use grammar::repr::*; use test_util::{normalized_grammar}; use super::lalr_states; use super::super::interpret::interpret; fn nt(t: &str) -> NonterminalString { NonterminalString(intern(t)) } macro_rules! tokens { ($($x:expr),*) => { vec![$(TerminalString::Quoted(intern($x))),*].in...
E "-" T => (); T => (); }; T: () = { "N" => (); "(" E ")" => (); }; "#); let states = lalr_states(&grammar, nt("S")).unwrap(); println!("{:#?}", states); let tree = interpret(&states, tokens!["N", "-", "(", ...
extern { enum Tok { } } S: () = E => (); E: () = {
random_line_split
lib.rs
#![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)] //! `nib` provides useful abstractions for working with data that is described/structure in 4-bit //! chunks. //! //! //! ``` //! use quartet::NibSlice; //! let nib_slice = NibSlice::from_bytes_skip_last(&[0x12, 0x34, 0x50]); //! assert_eq!(nib_sli...
(self, slice: &NibSlice<'a>) -> Option<Self::Output> { Some(*slice) } } impl<'a> SliceIndex<'a> for ops::RangeInclusive<usize> { type Output = NibSlice<'a>; fn get(self, slice: &NibSlice<'a>) -> Option<Self::Output> { (*self.start()..(*self.end() + 1)).get(slice) } } impl<'a> SliceInd...
get
identifier_name
lib.rs
#![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)] //! `nib` provides useful abstractions for working with data that is described/structure in 4-bit //! chunks. //! //! //! ``` //! use quartet::NibSlice; //! let nib_slice = NibSlice::from_bytes_skip_last(&[0x12, 0x34, 0x50]); //! assert_eq!(nib_sli...
else { let v = self.inner.inner[0] >> 4; self.inner.exclude = Exclude::from_excludes(true, self.inner.exclude.is_last_excluded()); v }; if self.inner.inner.len() == 0 { self.inner.exclude = Exclude::None_; } if self.inner.inner.len() == 1...
{ let v = self.inner.inner[0] & 0x0f; self.inner.inner = &self.inner.inner[1..]; self.inner.exclude = Exclude::from_excludes(false, self.inner.exclude.is_last_excluded()); v }
conditional_block
lib.rs
#![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)] //! `nib` provides useful abstractions for working with data that is described/structure in 4-bit //! chunks. //! //! //! ``` //! use quartet::NibSlice; //! let nib_slice = NibSlice::from_bytes_skip_last(&[0x12, 0x34, 0x50]); //! assert_eq!(nib_sli...
} #[test] fn index_middle() { let ns = NibSlice::from_bytes_exclude(&[0x12, 0x34, 0x56], Exclude::Both); let n = ns.index(2..4); assert_eq!(n, NibSlice::from_bytes(&[0x45])); } #[test] fn iter() { let ns = NibSlice::from_bytes_exclude(&[0x12, 0x34], Exclude::Bot...
assert_eq!(nib, 0x2);
random_line_split
lib.rs
#![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)] //! `nib` provides useful abstractions for working with data that is described/structure in 4-bit //! chunks. //! //! //! ``` //! use quartet::NibSlice; //! let nib_slice = NibSlice::from_bytes_skip_last(&[0x12, 0x34, 0x50]); //! assert_eq!(nib_sli...
/// Decompose a nibble offset into byte oriented terms. /// /// Returns `(byte_offset, is_low)`. `byte_offset` is a offset into a `[u8]`. `is_low` is true when /// the `offs` refers to the lower nibble in the byte located at `byte_offset`. pub fn decompose_offset(exclude: Exclude, offs: usize) -> (usize, bool) { ...
{ let index = offs + if exclude.is_first_excluded() { 1 } else { 0 }; let b_idx = index >> 1; let is_low = index & 1 == 1; (b_idx, is_low) }
identifier_body