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
glutin.rs
//! Window creation using glutin for gfx. //! //! # Examples //! //! The following code creates a `gfx::Surface` using glutin. //! //! ```no_run //! extern crate glutin; //! extern crate gfx_backend_gl; //! //! fn main() { //! use gfx_backend_gl::Surface; //! use glutin::{EventsLoop, WindowBuilder, ContextBuild...
<C>( &mut self, _config: hal::SwapchainConfig, _: &hal::CommandQueue<B, C>, ) -> (Swapchain, hal::Backbuffer<B>) { let swapchain = Swapchain { window: self.window.clone(), }; let backbuffer = hal::Backbuffer::Framebuffer(0); (swapchain, backbuffer)...
build_swapchain
identifier_name
glutin.rs
//! Window creation using glutin for gfx. //! //! # Examples //! //! The following code creates a `gfx::Surface` using glutin. //! //! ```no_run //! extern crate glutin; //! extern crate gfx_backend_gl; //! //! fn main() { //! use gfx_backend_gl::Surface; //! use glutin::{EventsLoop, WindowBuilder, ContextBuild...
ds_format: Option<f::Format>, ) -> glutin::ContextBuilder { let color_bits = color_format.0.describe_bits(); let depth_bits = match ds_format { Some(fm) => fm.0.describe_bits(), None => f::BITS_ZERO, }; builder .with_depth_buffer(depth_bits.depth) .with_stencil_buffer(d...
pub fn config_context( builder: glutin::ContextBuilder, color_format: f::Format,
random_line_split
model_clip_iterator.rs
use std::cmp::min; use std::slice::Iter; use cairo; use super::context::CellMetrics; use crate::ui_model; pub struct RowView<'a> { pub line: &'a ui_model::Line, pub cell_metrics: &'a CellMetrics, pub line_y: f64, pub ctx: &'a cairo::Context, } impl<'a> RowView<'a> { pub fn new( row: usiz...
} } } pub struct ModelClipIterator<'a> { model_idx: usize, model_iter: Iter<'a, ui_model::Line>, cell_metrics: &'a CellMetrics, ctx: &'a cairo::Context, } pub trait ModelClipIteratorFactory { fn get_clip_iterator<'a>( &'a self, ctx: &'a cairo::Context, cell_metr...
line_y: row as f64 * cell_metrics.line_height, cell_metrics, ctx,
random_line_split
model_clip_iterator.rs
use std::cmp::min; use std::slice::Iter; use cairo; use super::context::CellMetrics; use crate::ui_model; pub struct RowView<'a> { pub line: &'a ui_model::Line, pub cell_metrics: &'a CellMetrics, pub line_y: f64, pub ctx: &'a cairo::Context, } impl<'a> RowView<'a> { pub fn new( row: usiz...
(&mut self) -> Option<RowView<'a>> { let next = if let Some(line) = self.model_iter.next() { Some(RowView::new( self.model_idx, self.ctx, self.cell_metrics, line, )) } else { None }; self....
next
identifier_name
model_clip_iterator.rs
use std::cmp::min; use std::slice::Iter; use cairo; use super::context::CellMetrics; use crate::ui_model; pub struct RowView<'a> { pub line: &'a ui_model::Line, pub cell_metrics: &'a CellMetrics, pub line_y: f64, pub ctx: &'a cairo::Context, } impl<'a> RowView<'a> { pub fn new( row: usiz...
} pub struct ModelClipIterator<'a> { model_idx: usize, model_iter: Iter<'a, ui_model::Line>, cell_metrics: &'a CellMetrics, ctx: &'a cairo::Context, } pub trait ModelClipIteratorFactory { fn get_clip_iterator<'a>( &'a self, ctx: &'a cairo::Context, cell_metrics: &'a CellMe...
{ RowView { line, line_y: row as f64 * cell_metrics.line_height, cell_metrics, ctx, } }
identifier_body
model_clip_iterator.rs
use std::cmp::min; use std::slice::Iter; use cairo; use super::context::CellMetrics; use crate::ui_model; pub struct RowView<'a> { pub line: &'a ui_model::Line, pub cell_metrics: &'a CellMetrics, pub line_y: f64, pub ctx: &'a cairo::Context, } impl<'a> RowView<'a> { pub fn new( row: usiz...
; self.model_idx += 1; next } } /// Clip implemented as top - 1/bot + 1 /// this is because in some cases(like 'g' character) drawing character does not fit to calculated bounds /// and if one line must be repainted - also previous and next line must be repainted to impl ModelClipIteratorFactory f...
{ None }
conditional_block
rand-f64.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 ...
} }
{ validate(format!("{:e}", x)); i += 1; }
conditional_block
rand-f64.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 ...
{ let mut rnd = IsaacRng::from_seed(&SEED); let mut i = 0; while i < 10_000_000 { let bits = rnd.next_u64(); let x: f64 = unsafe { transmute(bits) }; if x.is_finite() { validate(format!("{:e}", x)); i += 1; } } }
identifier_body
rand-f64.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 ...
if x.is_finite() { validate(format!("{:e}", x)); i += 1; } } }
random_line_split
rand-f64.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 ...
() { let mut rnd = IsaacRng::from_seed(&SEED); let mut i = 0; while i < 10_000_000 { let bits = rnd.next_u64(); let x: f64 = unsafe { transmute(bits) }; if x.is_finite() { validate(format!("{:e}", x)); i += 1; } } }
main
identifier_name
main.rs
extern crate regex; use regex::Regex; use std::fs::File; use std::path::Path; use std::io::BufRead; use std::io::BufReader; use std::io; static LEFT : i32 = -1; static RIGHT : i32 = 1; struct Direction { dx: i32, dz: i32 } static DIRECTIONS : &'static [Direction] = &[ Direction{dx: 0, dz: -1}, Direc...
}
} println!("{}", state.x.abs() + state.z.abs());
random_line_split
main.rs
extern crate regex; use regex::Regex; use std::fs::File; use std::path::Path; use std::io::BufRead; use std::io::BufReader; use std::io; static LEFT : i32 = -1; static RIGHT : i32 = 1; struct Direction { dx: i32, dz: i32 } static DIRECTIONS : &'static [Direction] = &[ Direction{dx: 0, dz: -1}, Direc...
struct State { x: i32, z: i32, dir: i32 } impl State { fn turn(&self, turn: i32) -> State { let m = (self.dir + turn) & ((DIRECTIONS.len()-1) as i32); State {x: self.x, z: self.z, dir: m} } fn walk(&self, dist: i32) -> State { let ref dir = &DIRECTIONS[self.dir as usi...
{ let path = Path::new(src); let file = (File::open(path))?; let reader = BufReader::new(&file); let n : Vec<Op> = reader .lines() .map(|x| x.unwrap()) .flat_map(|x| parse(&x)) .collect(); Ok(n) }
identifier_body
main.rs
extern crate regex; use regex::Regex; use std::fs::File; use std::path::Path; use std::io::BufRead; use std::io::BufReader; use std::io; static LEFT : i32 = -1; static RIGHT : i32 = 1; struct Direction { dx: i32, dz: i32 } static DIRECTIONS : &'static [Direction] = &[ Direction{dx: 0, dz: -1}, Direc...
(src: &str) -> Vec<Op> { let re = Regex::new(r"(L|R)([0-9]+)").unwrap(); src .split(",") .map(|x| x.trim().to_string()) .map(|x| { let c = re.captures(&x).unwrap(); let turn = match c.at(1) { Some("L") => LEFT, Some("R") => RIGHT, ...
parse
identifier_name
mod.rs
use std::env; use std::error::Error; use std::ffi::OsStr; use std::fmt; use std::fs; use std::io::prelude::*; use std::os; use std::path::{Path, PathBuf}; use std::process::Output; use std::str; use std::usize; use url::Url; use hamcrest as ham; use cargo::util::ProcessBuilder; use cargo::util::ProcessError; use cargo...
(&self) -> Result<(), String> { try!(mkdir_recursive(&self.dirname())); os::unix::fs::symlink(&self.dst, &self.src) .with_err_msg(format!("Could not create symlink; dst={} src={}", self.dst.display(), self.src.display())) } #[cfg(windows)] fn m...
mk
identifier_name
mod.rs
use std::env; use std::error::Error; use std::ffi::OsStr; use std::fmt; use std::fs; use std::io::prelude::*; use std::os; use std::path::{Path, PathBuf}; use std::process::Output; use std::str; use std::usize; use url::Url; use hamcrest as ham; use cargo::util::ProcessBuilder; use cargo::util::ProcessError; use cargo...
, (None, Some(e)) => { Some(format!("{:3} - |{}|\n +\n", i, e)) }, (None, None) => panic!("Cannot get here") } }).collect() } } fn lines_match(expected: &str, mut actual: &str) -> bool { for part in expected.split("[..]"...
{ Some(format!("{:3} -\n + |{}|\n", i, a)) }
conditional_block
mod.rs
use std::env; use std::error::Error; use std::ffi::OsStr; use std::fmt; use std::fs; use std::io::prelude::*; use std::os; use std::path::{Path, PathBuf}; use std::process::Output; use std::str; use std::usize; use url::Url; use hamcrest as ham; use cargo::util::ProcessBuilder; use cargo::util::ProcessError; use cargo...
SymlinkBuilder { dst: dst, src: src } } #[cfg(unix)] fn mk(&self) -> Result<(), String> { try!(mkdir_recursive(&self.dirname())); os::unix::fs::symlink(&self.dst, &self.src) .with_err_msg(format!("Could not create symlink; dst={} src={}", ...
random_line_split
slider.rs
use { Backend, CharacterCache, Color, Colorable, FontSize, Frameable, Labelable, IndexSlot, KidArea, Mouse, Padding, Positionable, Range, Rect, Rectangle, Scalar, Text, Widget, }; use num::{Float, NumCast, ToPrimitive}; use widget; /// Linear va...
(&self) -> &widget::CommonBuilder { &self.common } fn common_mut(&mut self) -> &mut widget::CommonBuilder { &mut self.common } fn unique_kind(&self) -> &'static str { KIND } fn init_state(&self) -> State<T> { State { value: self.value, m...
common
identifier_name
slider.rs
use { Backend, CharacterCache, Color, Colorable, FontSize, Frameable, Labelable, IndexSlot, KidArea, Mouse, Padding, Positionable, Range, Rect, Rectangle, Scalar, Text, Widget, }; use num::{Float, NumCast, ToPrimitive}; use widget; /// Linear val...
}; value_from_perc(w_perc as f32, min, max) } else { // Vertical. let inner_h = inner_rect.h(); let h_perc = match (interaction, new_interaction) { (Highlighted, Clicked) | (Clicked, Clicked) => { ...
let slider_w = clamp(value_percentage as f64 * inner_w, 0.0, inner_w); let perc = slider_w / inner_w; perc },
random_line_split
helper.rs
/// Turn a failed parse into `None` and a successful parse into `Some`. /// /// - **Syntax:** `option!(THING)` /// - **Output:** `Option<THING>` /// /// ```rust /// extern crate syn; /// #[macro_use] extern crate synom; /// /// use syn::tokens::Bang; /// /// named!(maybe_bang -> Option<Bang>, option!(syn!(Bang))); /// ...
/// extern crate syn; /// #[macro_use] extern crate synom; /// /// use syn::Expr; /// use synom::tokens::Dot; /// /// named!(expression -> Expr, syn!(Expr)); /// /// named!(expression_dot -> (Expr, Dot), tuple!(syn!(Expr), syn!(Dot))); /// /// # fn main() {} /// ``` #[macro_export] macro_rules! syn { ($i:expr, $t:t...
/// - **Syntax:** `syn!(TYPE)` /// - **Output:** `TYPE` /// /// ```rust
random_line_split
chacha20hmacsha512256.rs
//! This module provides an implementation of authenticated encryption and plain authentication for a given key. This should be used through the interface in super:: //! //! # Cryptography //! Authenticates *first* with HMAC-SHA512 (only the first 256 bytes are used). This was chosen as it is the default authenticatio...
() { let e_k = chacha20::gen_key(); let e_k2 = chacha20::gen_key(); let a_k = hmacsha512256::gen_key(); let nonce = chacha20::gen_nonce(); let dut = ChaCha20HmacSha512256::new(e_k.clone(), a_k.clone(), nonce.clone()); let dut_corrupted = ChaCha20HmacSha512256::new(e_k2.cl...
authenticated_encryptor_decryptor_corrupted_enc
identifier_name
chacha20hmacsha512256.rs
//! This module provides an implementation of authenticated encryption and plain authentication for a given key. This should be used through the interface in super:: //! //! # Cryptography //! Authenticates *first* with HMAC-SHA512 (only the first 256 bytes are used). This was chosen as it is the default authenticatio...
} } /******************** Tests ******************/ #[cfg(test)] mod tests { use super::*; use sodiumoxide::crypto::stream::chacha20; use sodiumoxide::crypto::auth::hmacsha512256; use std::str; use sodiumoxide; use sodiumoxide::randombytes; const MESSAGE_LENGTH: usize = 1024; #[t...
{ None }
conditional_block
chacha20hmacsha512256.rs
//! This module provides an implementation of authenticated encryption and plain authentication for a given key. This should be used through the interface in super:: //! //! # Cryptography //! Authenticates *first* with HMAC-SHA512 (only the first 256 bytes are used). This was chosen as it is the default authenticatio...
if self.verify_auth(auth_tag, message) { let mut ret = vec![]; ret.extend_from_slice(message); Some(ret) } else { None } } } /******************** Tests ******************/ #[cfg(test)] mod tests { use super::*; use sodiumoxide::crypt...
let (message, auth_tag) = plaintext.split_at(ciphertext.len() - hmacsha512256::TAGBYTES);
random_line_split
chacha20hmacsha512256.rs
//! This module provides an implementation of authenticated encryption and plain authentication for a given key. This should be used through the interface in super:: //! //! # Cryptography //! Authenticates *first* with HMAC-SHA512 (only the first 256 bytes are used). This was chosen as it is the default authenticatio...
} /******************** Tests ******************/ #[cfg(test)] mod tests { use super::*; use sodiumoxide::crypto::stream::chacha20; use sodiumoxide::crypto::auth::hmacsha512256; use std::str; use sodiumoxide; use sodiumoxide::randombytes; const MESSAGE_LENGTH: usize = 1024; #[test] ...
{ assert!(ciphertext.len() > hmacsha512256::TAGBYTES); let plaintext = chacha20::stream_xor(ciphertext, &self.nonce, &self.encryption_key); let (message, auth_tag) = plaintext.split_at(ciphertext.len() - hmacsha512256::TAGBYTES); if self.verify_auth(auth_tag, message) { let...
identifier_body
test_udp_socket.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf, MutBuf}; use super::localhost; use std::str; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf } impl U...
}, _ => {} } } } } fn assert_send<T: Send>() { } #[test] pub fn test_udp_socket() { debug!("Starting TEST_UDP_SOCKETS"); let mut event_loop = EventLoop::new().unwrap(); let addr = localhost(); let any = str::FromStr::from_str("0.0.0.0:0").unwrap...
.unwrap(); self.buf.advance(cnt);
random_line_split
test_udp_socket.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf, MutBuf}; use super::localhost; use std::str; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf } impl U...
} impl Handler for UdpHandler { type Timeout = usize; type Message = (); fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: EventSet) { if events.is_readable() { match token { LISTENER => { debug!("We are receiving a ...
{ UdpHandler { tx: tx, rx: rx, msg: msg, buf: SliceBuf::wrap(msg.as_bytes()), rx_buf: RingBuf::new(1024) } }
identifier_body
test_udp_socket.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf, MutBuf}; use super::localhost; use std::str; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf } impl U...
(tx: UdpSocket, rx: UdpSocket, msg : &'static str) -> UdpHandler { UdpHandler { tx: tx, rx: rx, msg: msg, buf: SliceBuf::wrap(msg.as_bytes()), rx_buf: RingBuf::new(1024) } } } impl Handler for UdpHandler { type Timeout = usize; typ...
new
identifier_name
test_udp_socket.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf, MutBuf}; use super::localhost; use std::str; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf } impl U...
, _ => {} } } } } fn assert_send<T: Send>() { } #[test] pub fn test_udp_socket() { debug!("Starting TEST_UDP_SOCKETS"); let mut event_loop = EventLoop::new().unwrap(); let addr = localhost(); let any = str::FromStr::from_str("0.0.0.0:0").unwrap(); let tx =...
{ let addr = self.rx.local_addr().unwrap(); let cnt = self.tx.send_to(self.buf.bytes(), &addr).unwrap() .unwrap(); self.buf.advance(cnt); }
conditional_block
segmentation.rs
use core::fmt; use shared::descriptor; use shared::PrivilegeLevel; /// Specifies which element to load into a segment from /// descriptor tables (i.e., is a index to LDT or GDT table /// with some additional flags). /// /// See Intel 3a, Section 3.4.2 "Segment Selectors" bitflags! { #[repr(C, packed)] pub fla...
true => "LDT Table", }; write!(f, "Index {} in {}, {}{}{}{}", self.bits >> 3, tbl, r0, r1, r2, r3) // write!(f, "Index") } } /// Reload stack segment register. pub unsafe f...
true => "Ring 3 segment selector.", }; let tbl = match self.contains(TI_LDT) { false => "GDT Table",
random_line_split
segmentation.rs
use core::fmt; use shared::descriptor; use shared::PrivilegeLevel; /// Specifies which element to load into a segment from /// descriptor tables (i.e., is a index to LDT or GDT table /// with some additional flags). /// /// See Intel 3a, Section 3.4.2 "Segment Selectors" bitflags! { #[repr(C, packed)] pub fla...
(sel: SegmentSelector) { asm!("movw $0, %ss " :: "r" (sel) : "memory"); } /// Reload data segment register. pub unsafe fn load_ds(sel: SegmentSelector) { asm!("movw $0, %ds " :: "r" (sel) : "memory"); } /// Reload es segment register. pub unsafe fn load_es(sel: SegmentSelector) { asm!("movw $0, %es " :: "...
load_ss
identifier_name
segmentation.rs
use core::fmt; use shared::descriptor; use shared::PrivilegeLevel; /// Specifies which element to load into a segment from /// descriptor tables (i.e., is a index to LDT or GDT table /// with some additional flags). /// /// See Intel 3a, Section 3.4.2 "Segment Selectors" bitflags! { #[repr(C, packed)] pub fla...
| Flags::from_limit2(limit2), } } } bitflags! { pub flags Flags: u8 { /// Available for use by system software. const FLAGS_AVL = 1 << 4, /// 64-bit code segment (IA-32e mode only). const FLAGS_L = 1 << 5, /// Default operation size (0 = 16-b...
{ Flags::empty() }
conditional_block
iter.rs
use {Task, Poll}; use stream::Stream; /// A stream which is just a shim over an underlying instance of `Iterator`. /// /// This stream will never block and is always ready. pub struct IterStream<I> { iter: I, } /// Converts an `Iterator` into a `Stream` which is always ready to yield the /// next value. /// /// I...
<I, T, E>(i: I) -> IterStream<I> where I: Iterator<Item=Result<T, E>>, I: Send +'static, T: Send +'static, E: Send +'static, { IterStream { iter: i, } } impl<I, T, E> Stream for IterStream<I> where I: Iterator<Item=Result<T, E>>, I: Send +'static, ...
iter
identifier_name
iter.rs
use {Task, Poll}; use stream::Stream; /// A stream which is just a shim over an underlying instance of `Iterator`. /// /// This stream will never block and is always ready. pub struct IterStream<I> { iter: I, } /// Converts an `Iterator` into a `Stream` which is always ready to yield the /// next value. /// /// I...
/// will always be returned upwards as a successful value. pub fn iter<I, T, E>(i: I) -> IterStream<I> where I: Iterator<Item=Result<T, E>>, I: Send +'static, T: Send +'static, E: Send +'static, { IterStream { iter: i, } } impl<I, T, E> Stream for IterStream<I> whe...
/// generic here as it will never be returned, instead the type of the iterator
random_line_split
iter.rs
use {Task, Poll}; use stream::Stream; /// A stream which is just a shim over an underlying instance of `Iterator`. /// /// This stream will never block and is always ready. pub struct IterStream<I> { iter: I, } /// Converts an `Iterator` into a `Stream` which is always ready to yield the /// next value. /// /// I...
fn schedule(&mut self, task: &mut Task) { task.notify() } }
{ match self.iter.next() { Some(Ok(e)) => Poll::Ok(Some(e)), Some(Err(e)) => Poll::Err(e), None => Poll::Ok(None), } }
identifier_body
deref_coercions.rs
pub fn deref_coercions() { println!("***Deref Coercions***"); derefs(); deref_and_method_calls(); println!(""); } // trait Deref is used to overload *, the dereference operator use std::ops::Deref; struct DerefExample<T> { value: T, } impl<T> Deref for DerefExample<T> { type Target = T; ...
(s: &str) { println!("Borrowed str: {}", s); } use std::rc::Rc; fn bar(s: &[i32]) { print!("Vec: "); for i in s { print!("{} ", i); } println!(""); } fn derefs() { let x = DerefExample { value: 'a' }; println!("x->value = '{}'", *x); assert_eq!('a', *x); // String impleme...
foo
identifier_name
deref_coercions.rs
pub fn deref_coercions() { println!("***Deref Coercions***"); derefs(); deref_and_method_calls(); println!(""); } // trait Deref is used to overload *, the dereference operator use std::ops::Deref; struct DerefExample<T> { value: T, } impl<T> Deref for DerefExample<T> { type Target = T; ...
} fn foo(s: &str) { println!("Borrowed str: {}", s); } use std::rc::Rc; fn bar(s: &[i32]) { print!("Vec: "); for i in s { print!("{} ", i); } println!(""); } fn derefs() { let x = DerefExample { value: 'a' }; println!("x->value = '{}'", *x); assert_eq!('a', *x); // Stri...
{ &self.value }
identifier_body
deref_coercions.rs
pub fn deref_coercions() { println!("***Deref Coercions***"); derefs(); deref_and_method_calls(); println!(""); } // trait Deref is used to overload *, the dereference operator use std::ops::Deref; struct DerefExample<T> { value: T, } impl<T> Deref for DerefExample<T> { type Target = T; ...
fn deref_and_method_calls() { // &&&s coerce to one & so that it can be used as &self argument let f = &&Foo2; f.foo2(); (&&&&&&&&&f).foo2(); }
fn foo2(&self) { println!("foo2 called!"); } }
random_line_split
db_variable_name.rs
use rusqlite::Connection; #[derive(Debug)] pub struct VariableName { pub id: i32, pub name: String, } pub fn table_create_variable_name(conn: &Connection) -> &Connection { conn.execute( "CREATE TABLE VARIABLE_NAME ( id INTEGER PRIMARY KEY ASC, name ...
pub fn variable_name_list(conn: &Connection) { let mut stmt = conn .prepare("SELECT id, name, fk_provider, sq_order FROM VARIABLE_NAME") .unwrap(); let person_iter = stmt.query_map(&[], |row| VariableName { id: row.get(0), name: row.get(1), }).unwrap(); ...
{ let mut stmt = conn.prepare("SELECT id, name FROM VARIABLE_NAME").unwrap(); let wraped_fs_file_iter = stmt.query_map(&[], |row| VariableName { id: row.get(0), name: row.get(1), }); let mut items = Vec::<VariableName>::new(); if wraped_fs_file_iter.is_err() { return items; ...
identifier_body
db_variable_name.rs
use rusqlite::Connection; #[derive(Debug)] pub struct VariableName { pub id: i32, pub name: String, } pub fn table_create_variable_name(conn: &Connection) -> &Connection { conn.execute( "CREATE TABLE VARIABLE_NAME ( id INTEGER PRIMARY KEY ASC, name ...
let variable_name_instance = conn.execute( "INSERT INTO VARIABLE_NAME (name) VALUES (?1)", &[&me.name], ); if variable_name_instance.is_err() { return Err("Insert failed"); } variable_name_instance.unwrap(); return Ok(0); } pub fn list_variable_name(con...
pub fn insert_variable_name(conn: &Connection, name: &String) -> Result<i32, &'static str> { let me = VariableName { id: 0, name: name.clone(), };
random_line_split
db_variable_name.rs
use rusqlite::Connection; #[derive(Debug)] pub struct VariableName { pub id: i32, pub name: String, } pub fn table_create_variable_name(conn: &Connection) -> &Connection { conn.execute( "CREATE TABLE VARIABLE_NAME ( id INTEGER PRIMARY KEY ASC, name ...
return Err("None found"); }
{ return Ok(output); }
conditional_block
db_variable_name.rs
use rusqlite::Connection; #[derive(Debug)] pub struct VariableName { pub id: i32, pub name: String, } pub fn
(conn: &Connection) -> &Connection { conn.execute( "CREATE TABLE VARIABLE_NAME ( id INTEGER PRIMARY KEY ASC, name TEXT NOT NULL UNIQUE )", &[], ).unwrap(); return conn; } pub fn insert_variable_name(conn: &Connection, nam...
table_create_variable_name
identifier_name
memory_section.rs
/* Copyright 2018 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...
(&self) -> usize { self.reader.original_position() } pub fn get_count(&self) -> u32 { self.count } /// Reads content of the memory section. /// /// # Examples /// ``` /// # let data: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, /// # 0x01, 0x4, 0x01...
original_position
identifier_name
memory_section.rs
/* Copyright 2018 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...
impl<'a> SectionWithLimitedItems for MemorySectionReader<'a> { fn get_count(&self) -> u32 { MemorySectionReader::get_count(self) } } impl<'a> IntoIterator for MemorySectionReader<'a> { type Item = Result<MemoryType>; type IntoIter = SectionIteratorLimited<MemorySectionReader<'a>>; fn into_...
fn original_position(&self) -> usize { MemorySectionReader::original_position(self) } }
random_line_split
memory_section.rs
/* Copyright 2018 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...
} impl<'a> SectionReader for MemorySectionReader<'a> { type Item = MemoryType; fn read(&mut self) -> Result<Self::Item> { MemorySectionReader::read(self) } fn eof(&self) -> bool { self.reader.eof() } fn original_position(&self) -> usize { MemorySectionReader::original_p...
{ self.reader.read_memory_type() }
identifier_body
thss.rs
#![cfg(test)] #![feature(test)] #![cfg(feature = "dss")] extern crate rusty_secrets; extern crate test; mod shared; mod thss { use rusty_secrets::dss::thss; use shared; use test::{black_box, Bencher}; macro_rules! bench_generate { ($name:ident, $k:expr, $n:expr, $secret:ident) => { ...
b.iter(move || { let shares = thss::split_secret($k, $n, &secret, &None).unwrap(); black_box(shares); }); } }; } macro_rules! bench_recover { ($name:ident, $k:expr, $n:expr, $secret:ident) => { #[ben...
random_line_split
db.rs
use std::{borrow::Cow, cell::RefCell, fmt::Write as FmtWrite}; use bytes::{Bytes, BytesMut}; use futures::{Future, FutureExt}; use nanorand::{WyRand, RNG}; use smallvec::SmallVec; use tokio_postgres::types::ToSql; use tokio_postgres::{connect, Client, NoTls, Statement}; use yarte::{ywrite_html, Serialize}; #[derive(C...
pub fn update(&self, num: u16) -> impl Future<Output = Vec<World>> { let mut futs = Vec::with_capacity(num as usize); let mut rng = self.rng.borrow_mut(); for _ in 0..num { let id = (rng.generate::<u32>() % 10_000 + 1) as i32; let w_id = (rng.generate::<u32>() % 10_...
{ let mut futs = Vec::with_capacity(num as usize); let mut rng = self.rng.borrow_mut(); for _ in 0..num { let w_id = (rng.generate::<u32>() % 10_000 + 1) as i32; futs.push(self.cl.query(&self.world, &[&w_id])); } async move { let mut worlds: V...
identifier_body
db.rs
use std::{borrow::Cow, cell::RefCell, fmt::Write as FmtWrite}; use bytes::{Bytes, BytesMut}; use futures::{Future, FutureExt}; use nanorand::{WyRand, RNG}; use smallvec::SmallVec; use tokio_postgres::types::ToSql; use tokio_postgres::{connect, Client, NoTls, Statement}; use yarte::{ywrite_html, Serialize}; #[derive(C...
(db_url: &str) -> PgConnection { let (cl, conn) = connect(db_url, NoTls) .await .expect("can not connect to postgresql"); ntex::rt::spawn(conn.map(|_| ())); let fortune = cl.prepare("SELECT * FROM fortune").await.unwrap(); let mut updates = Vec::new(); for ...
connect
identifier_name
db.rs
use std::{borrow::Cow, cell::RefCell, fmt::Write as FmtWrite}; use bytes::{Bytes, BytesMut}; use futures::{Future, FutureExt}; use nanorand::{WyRand, RNG}; use smallvec::SmallVec; use tokio_postgres::types::ToSql; use tokio_postgres::{connect, Client, NoTls, Statement}; use yarte::{ywrite_html, Serialize}; #[derive(C...
updates: Vec<Statement>, } impl PgConnection { pub async fn connect(db_url: &str) -> PgConnection { let (cl, conn) = connect(db_url, NoTls) .await .expect("can not connect to postgresql"); ntex::rt::spawn(conn.map(|_| ())); let fortune = cl.prepare("SELECT * FROM ...
world: Statement, rng: RefCell<WyRand>,
random_line_split
semigroup.rs
use lift::SemiGroup; use std::hash::Hash; use std::collections::linked_list::LinkedList; use std::collections::vec_deque::VecDeque; use std::collections::{BinaryHeap, BTreeSet, HashSet}; //implementation for numerics semigroup_num!(i8); semigroup_num!(i16); semigroup_num!(i32); semigroup_num!(i64); semigroup_num!(u8);...
(&self, b: &Self::A) -> Self::A { let mut ret = String::from(""); ret.push_str(self); ret.push_str(b); ret } } //Implementation for SemiGroup for HashSet impl<T: Clone + Hash + Eq> SemiGroup for HashSet<T> { type A = HashSet<T>; fn add(&self, b: &Self::A) -> Self::A { ...
add
identifier_name
semigroup.rs
use lift::SemiGroup; use std::hash::Hash; use std::collections::linked_list::LinkedList; use std::collections::vec_deque::VecDeque; use std::collections::{BinaryHeap, BTreeSet, HashSet}; //implementation for numerics semigroup_num!(i8); semigroup_num!(i16); semigroup_num!(i32); semigroup_num!(i64); semigroup_num!(u8);...
type A = HashSet<T>; fn add(&self, b: &Self::A) -> Self::A { let mut ret = HashSet::new(); ret.extend(self.iter().cloned()); ret.extend(b.iter().cloned()); ret } } //Implementation of SemiGroup for Vec<T> semigroup!(Vec); //Implementation of SemiGroup for LinkedList<T> sem...
impl<T: Clone + Hash + Eq> SemiGroup for HashSet<T> {
random_line_split
semigroup.rs
use lift::SemiGroup; use std::hash::Hash; use std::collections::linked_list::LinkedList; use std::collections::vec_deque::VecDeque; use std::collections::{BinaryHeap, BTreeSet, HashSet}; //implementation for numerics semigroup_num!(i8); semigroup_num!(i16); semigroup_num!(i32); semigroup_num!(i64); semigroup_num!(u8);...
} //Implementation for SemiGroup for HashSet impl<T: Clone + Hash + Eq> SemiGroup for HashSet<T> { type A = HashSet<T>; fn add(&self, b: &Self::A) -> Self::A { let mut ret = HashSet::new(); ret.extend(self.iter().cloned()); ret.extend(b.iter().cloned()); ret } } //Implem...
{ let mut ret = String::from(""); ret.push_str(self); ret.push_str(b); ret }
identifier_body
generic-tup.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 ...
<T>(t: (T, T, T)) -> T { let (_, _, x) = t; return x; } pub fn main() { println!("{:?}", get_third((1, 2, 3))); assert_eq!(get_third((1, 2, 3)), 3); assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8); }
get_third
identifier_name
generic-tup.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 ...
{ println!("{:?}", get_third((1, 2, 3))); assert_eq!(get_third((1, 2, 3)), 3); assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8); }
identifier_body
generic-tup.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn get_third<T>(t: (T, T, T)) -> T { let (_, _, x) = t; return x; } pub fn main() { ...
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
random_line_split
file_stream_iter.rs
use std::io::{BufReader, Read, BufWriter, Error}; use std::io::Write; use std::fs::{OpenOptions, File}; pub struct FileStreamReader<Read> { file_name: String, start: u64, end: u64, buf: [u8; 512], reader: BufReader<Read>, } impl FileStreamReader<File> { // std::fs::File because we are talking ...
(&mut self) -> Option<Self::Item> { let num_bytes_read = self.reader.read(&mut self.buf); let mut arr = [0; 512]; let mut i = 0usize; for c in self.buf.iter() { arr[i] = *c; i += 1; } Some((arr, num_bytes_read.unwrap())) } } pub struct FileStr...
next
identifier_name
file_stream_iter.rs
use std::io::{BufReader, Read, BufWriter, Error}; use std::io::Write; use std::fs::{OpenOptions, File}; pub struct FileStreamReader<Read> { file_name: String, start: u64, end: u64, buf: [u8; 512], reader: BufReader<Read>, } impl FileStreamReader<File> { // std::fs::File because we are talking ...
} pub struct FileStreamWriter<W: Write> { file_name: String, start: u64, end: u64, buf: [u8; 512], writer: BufWriter<W>, } impl FileStreamWriter<File> { pub fn new(file_name: String) -> Option<Self> { let f = match OpenOptions::new().create(true).append(true).open(file_name.clone()) {...
{ let num_bytes_read = self.reader.read(&mut self.buf); let mut arr = [0; 512]; let mut i = 0usize; for c in self.buf.iter() { arr[i] = *c; i += 1; } Some((arr, num_bytes_read.unwrap())) }
identifier_body
file_stream_iter.rs
use std::io::{BufReader, Read, BufWriter, Error}; use std::io::Write; use std::fs::{OpenOptions, File}; pub struct FileStreamReader<Read> { file_name: String, start: u64, end: u64, buf: [u8; 512], reader: BufReader<Read>, } impl FileStreamReader<File> { // std::fs::File because we are talking ...
let mut fs = FileStreamWriter { file_name: file_name, start: 0, end: 0, writer: BufWriter::with_capacity(512, f.unwrap()), buf: [0; 512], }; Some(fs) } else { println!("cant open file"...
Err(msg) => None, }; if f.is_some() {
random_line_split
server.rs
use tls_api::TlsAcceptor; use tls_api::TlsAcceptorBuilder as tls_api_TlsAcceptorBuilder; use httpbis::ServerResponse; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread; struct
{ counter: Arc<AtomicUsize>, } impl ServiceImpl { fn new() -> ServiceImpl { ServiceImpl { counter: Arc::new(AtomicUsize::new(0)), } } } impl httpbis::ServerHandler for ServiceImpl { fn start_request( &self, req: httpbis::ServerRequest, resp: ServerR...
ServiceImpl
identifier_name
server.rs
use tls_api::TlsAcceptor; use tls_api::TlsAcceptorBuilder as tls_api_TlsAcceptorBuilder; use httpbis::ServerResponse; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread; struct ServiceImpl { counter: Arc<AtomicUsize>, } impl ServiceImpl { fn new() -> Serv...
", self.counter.load(Ordering::Relaxed) ); let mut sink = resp.send_headers(resp_headers)?; sink.send_data_end_of_stream(page.into())? } Ok(()) } } fn main() { let server_keys = &test_cert_gen::keys().server; let mut tls_accepto...
{ let mut resp_headers = httpbis::Headers::ok_200(); resp_headers.add("content-type", "text/html; charset=utf-8"); let page = format!( " <html> <head> <title>httpbis demo</title> </head> <body> <h3>httpbis demo</h3> <div>Counter: {...
conditional_block
server.rs
use tls_api::TlsAcceptor; use tls_api::TlsAcceptorBuilder as tls_api_TlsAcceptorBuilder; use httpbis::ServerResponse; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread; struct ServiceImpl { counter: Arc<AtomicUsize>, } impl ServiceImpl { fn new() -> Serv...
.expect("acceptor builder"); tls_acceptor .set_alpn_protocols(&[b"h2"]) .expect("set_alpn_protocols"); let mut conf = httpbis::ServerConf::new(); conf.alpn = Some(httpbis::ServerAlpn::Require); let mut server = httpbis::ServerBuilder::new(); server.set_port(8443); server.set_tl...
)
random_line_split
server.rs
use tls_api::TlsAcceptor; use tls_api::TlsAcceptorBuilder as tls_api_TlsAcceptorBuilder; use httpbis::ServerResponse; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread; struct ServiceImpl { counter: Arc<AtomicUsize>, } impl ServiceImpl { fn new() -> Serv...
} impl httpbis::ServerHandler for ServiceImpl { fn start_request( &self, req: httpbis::ServerRequest, resp: ServerResponse, ) -> httpbis::Result<()> { println!("starting request: {:?}", req.headers); if req.headers.method() == "POST" { self.counter.fetch_ad...
{ ServiceImpl { counter: Arc::new(AtomicUsize::new(0)), } }
identifier_body
rpc.rs
use std::collections::HashMap; use std::io::{self, Read, Write}; use std::marker::PhantomData; use std::string::String; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::sync::mpsc::{channel, Sender, Receiver}; use std::thread::{self, JoinHandle}; use super::{Valu...
/// of a MessagePack data type identifier. pub fn new(reader: R, writer: W) -> Client<R, W> { let pending = Arc::new(Mutex::new(HashMap::new())); Client{ input: PhantomData, output: writer, pending: pending.clone(), main_loop_handle: Client::<R, W>...
/// Construct a new Client instance. /// /// This will spawn a main loop thread which will take ownership of the `Read` /// instance, and which will exit when it detects EOF, or when it receives a 0 in lieu
random_line_split
rpc.rs
use std::collections::HashMap; use std::io::{self, Read, Write}; use std::marker::PhantomData; use std::string::String; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::sync::mpsc::{channel, Sender, Receiver}; use std::thread::{self, JoinHandle}; use super::{Valu...
} impl<R, W> Drop for Client<R, W> where R: Read + Send +'static, W: Write + Send { fn drop(&mut self) { match self.output.write(&[0]) { Ok(_) => (), Err(ref e) if e.kind() == io::ErrorKind::BrokenPipe => (), // already closed, no need to kill it Err(e) => panic!("{}", ...
{ let msgid = MSGID.fetch_add(1, Ordering::SeqCst) as u32; let (responder, listener) = channel(); self.pending.lock().unwrap().insert(msgid, responder); try!(write_value(&mut self.output, Value::Array(vec![ Value::Int8(0), Value::Uint32(msgid), Value:...
identifier_body
rpc.rs
use std::collections::HashMap; use std::io::{self, Read, Write}; use std::marker::PhantomData; use std::string::String; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::sync::mpsc::{channel, Sender, Receiver}; use std::thread::{self, JoinHandle}; use super::{Valu...
(&mut self) { match self.output.write(&[0]) { Ok(_) => (), Err(ref e) if e.kind() == io::ErrorKind::BrokenPipe => (), // already closed, no need to kill it Err(e) => panic!("{}", e), } } } #[cfg(test)] mod test { use std::sync::mpsc::channel; use std::thr...
drop
identifier_name
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
//! ``` //! # #![allow(deprecated)] //! extern crate num; //! //! use num::bigint::BigInt; //! use num::rational::{Ratio, BigRational}; //! //! fn approx_sqrt(number: u64, iterations: uint) -> BigRational { //! let start: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u64(number).unwrap()); //! let mut...
random_line_split
util.rs
use std::io; use std::path::PathBuf; use app_dirs::{app_dir, AppDataType, AppInfo}; pub const TITLE: &str = "Sokoban"; const APP_INFO: AppInfo = AppInfo { name: "sokoban", author: "yzhs", }; lazy_static! { pub static ref DATA_DIR: PathBuf = app_dir(AppDataType::UserData, &APP_INFO, "").unwrap(); //...
(e: quick_xml::Error) -> Self { SokobanError::XmlError(e) } }
from
identifier_name
util.rs
use std::io; use std::path::PathBuf; use app_dirs::{app_dir, AppDataType, AppInfo}; pub const TITLE: &str = "Sokoban"; const APP_INFO: AppInfo = AppInfo { name: "sokoban", author: "yzhs", }; lazy_static! { pub static ref DATA_DIR: PathBuf = app_dir(AppDataType::UserData, &APP_INFO, "").unwrap(); //...
SokobanError::XmlError(e) } }
impl From<quick_xml::Error> for SokobanError { fn from(e: quick_xml::Error) -> Self {
random_line_split
util.rs
use std::io; use std::path::PathBuf; use app_dirs::{app_dir, AppDataType, AppInfo}; pub const TITLE: &str = "Sokoban"; const APP_INFO: AppInfo = AppInfo { name: "sokoban", author: "yzhs", }; lazy_static! { pub static ref DATA_DIR: PathBuf = app_dir(AppDataType::UserData, &APP_INFO, "").unwrap(); //...
} /// Automatically wrap XML reader errors impl From<quick_xml::Error> for SokobanError { fn from(e: quick_xml::Error) -> Self { SokobanError::XmlError(e) } }
{ SokobanError::IoError(err) }
identifier_body
get_permission_response.rs
use crate::from_headers::*; use crate::permission::CosmosPermission; use crate::Permission; use azure_sdk_core::errors::AzureError; use azure_sdk_core::{etag_from_headers, session_token_from_headers}; use http::HeaderMap; use std::borrow::Cow; #[derive(Debug, Clone, PartialEq)] pub struct
<'a> { pub permission: Permission<'a, Cow<'a, str>>, pub charge: f64, pub etag: String, pub activity_id: uuid::Uuid, pub session_token: String, pub content_path: String, pub alt_content_path: String, } impl<'a> std::convert::TryFrom<(&HeaderMap, &[u8])> for GetPermissionResponse<'a> { t...
GetPermissionResponse
identifier_name
get_permission_response.rs
use crate::from_headers::*; use crate::permission::CosmosPermission; use crate::Permission; use azure_sdk_core::errors::AzureError; use azure_sdk_core::{etag_from_headers, session_token_from_headers}; use http::HeaderMap; use std::borrow::Cow; #[derive(Debug, Clone, PartialEq)] pub struct GetPermissionResponse<'a> { ...
// first get the Cosmos REST API permission let cosmos_permission: CosmosPermission<'_> = serde_json::from_slice(body)?; debug!("cosmos_permission== {:#?}", cosmos_permission); // now convert into the SDK struct let permission = Permission::try_from(cosmos_permission)?; ...
debug!("body == {:#?}", std::str::from_utf8(body)?);
random_line_split
uniq.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 body_datum = body_datum.to_value_datum(bcx); let llty = type_of(bcx.ccx(), body_datum.ty); let size = llsize_of(bcx.ccx(), llty); let Result { bcx: bcx, val: val } = malloc_raw_dyn(bcx, body_datum.ty, heap_exchange, size); body_datum.copy_to(bcx, datum::INIT, val); ...
conditional_block
uniq.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 duplicate(bcx: block, src_box: ValueRef, src_ty: ty::t) -> Result { let _icx = push_ctxt("uniq::duplicate"); // Load the body of the source (*src) let src_datum = immediate_rvalue(src_box, src_ty); let body_datum = src_datum.box_body(bcx); // Malloc space in exchange heap and copy src int...
{ let _icx = push_ctxt("uniq::make_free_glue"); let box_datum = immediate_rvalue(Load(bcx, vptrptr), box_ty); let not_null = IsNotNull(bcx, box_datum.val); do with_cond(bcx, not_null) |bcx| { let body_datum = box_datum.box_body(bcx); let bcx = glue::drop_ty(bcx, body_datum.to_ref_llval(...
identifier_body
uniq.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 ...
(bcx: block, src_box: ValueRef, src_ty: ty::t) -> Result { let _icx = push_ctxt("uniq::duplicate"); // Load the body of the source (*src) let src_datum = immediate_rvalue(src_box, src_ty); let body_datum = src_datum.box_body(bcx); // Malloc space in exchange heap and copy src into it if ty::ty...
duplicate
identifier_name
uniq.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 ...
Result { bcx: bcx, val: val } } }
let size = llsize_of(bcx.ccx(), llty); let Result { bcx: bcx, val: val } = malloc_raw_dyn(bcx, body_datum.ty, heap_exchange, size); body_datum.copy_to(bcx, datum::INIT, val);
random_line_split
compile_error.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) -> Box<dyn base::MacResult + 'cx> { let var = match get_single_str_from_tts(cx, sp, tts, "compile_error!") { None => return DummyResult::expr(sp), ...
expand_compile_error
identifier_name
compile_error.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
DummyResult::any(sp) }
cx.span_err(sp, &var);
random_line_split
compile_error.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ let var = match get_single_str_from_tts(cx, sp, tts, "compile_error!") { None => return DummyResult::expr(sp), Some(v) => v, }; cx.span_err(sp, &var); DummyResult::any(sp) }
identifier_body
directory.rs
use std::mem::size_of; use std::sync::atomic::*; use super::{SharedMemory, open_shared}; use utils::PAGE_SIZE; /// A directory of shared structures. const MAX_LEN: usize = 256; // 255 byte names const DIRECTORY_PAGES: usize = 2; // Dedicate 2 pages to the directory. const BYTE_SIZE: usize = DIRECTORY_PAGES * PAGE_SIZE...
unsafe { (*self.head).current_version.fetch_add(1, Ordering::SeqCst); } } #[inline] pub fn end_snapshot(&mut self) { unsafe { let version = (*self.head).current_version.load(Ordering::Acquire); (*self.head).committed_version.store(version, Orderin...
random_line_split
directory.rs
use std::mem::size_of; use std::sync::atomic::*; use super::{SharedMemory, open_shared}; use utils::PAGE_SIZE; /// A directory of shared structures. const MAX_LEN: usize = 256; // 255 byte names const DIRECTORY_PAGES: usize = 2; // Dedicate 2 pages to the directory. const BYTE_SIZE: usize = DIRECTORY_PAGES * PAGE_SIZE...
} #[inline] pub fn begin_snapshot(&mut self) { unsafe { (*self.head).current_version.fetch_add(1, Ordering::SeqCst); } } #[inline] pub fn end_snapshot(&mut self) { unsafe { let version = (*self.head).current_version.load(Ordering::Acquire); ...
{ unsafe { let entry_ptr = self.data.offset(entry as isize); (*entry_ptr).name.copy_from_slice(name.as_bytes()); (*self.head).entries.store(entry, Ordering::Release); } self.entry += 1; Some(entry) }
conditional_block
directory.rs
use std::mem::size_of; use std::sync::atomic::*; use super::{SharedMemory, open_shared}; use utils::PAGE_SIZE; /// A directory of shared structures. const MAX_LEN: usize = 256; // 255 byte names const DIRECTORY_PAGES: usize = 2; // Dedicate 2 pages to the directory. const BYTE_SIZE: usize = DIRECTORY_PAGES * PAGE_SIZE...
#[inline] pub fn end_snapshot(&mut self) { unsafe { let version = (*self.head).current_version.load(Ordering::Acquire); (*self.head).committed_version.store(version, Ordering::Release); } } }
{ unsafe { (*self.head).current_version.fetch_add(1, Ordering::SeqCst); } }
identifier_body
directory.rs
use std::mem::size_of; use std::sync::atomic::*; use super::{SharedMemory, open_shared}; use utils::PAGE_SIZE; /// A directory of shared structures. const MAX_LEN: usize = 256; // 255 byte names const DIRECTORY_PAGES: usize = 2; // Dedicate 2 pages to the directory. const BYTE_SIZE: usize = DIRECTORY_PAGES * PAGE_SIZE...
(&mut self) { unsafe { let version = (*self.head).current_version.load(Ordering::Acquire); (*self.head).committed_version.store(version, Ordering::Release); } } }
end_snapshot
identifier_name
csv.rs
//! CSV read / write module pub use libcsv::{Reader, Writer, Error}; use rustc_serialize::{Decodable, Encodable}; use std::io::{Read, Write}; use super::super::matrix::{Matrix, BaseMatrix}; impl<T> Matrix<T> where T: Decodable { /// Read csv file as Matrix. /// /// # Examples /// /// ```ignore...
} Ok(()) } }
try!(writer.encode(row.raw_slice()));
random_line_split
csv.rs
//! CSV read / write module pub use libcsv::{Reader, Writer, Error}; use rustc_serialize::{Decodable, Encodable}; use std::io::{Read, Write}; use super::super::matrix::{Matrix, BaseMatrix}; impl<T> Matrix<T> where T: Decodable { /// Read csv file as Matrix. /// /// # Examples /// /// ```ignore...
}
{ for row in self.row_iter() { try!(writer.encode(row.raw_slice())); } Ok(()) }
identifier_body
csv.rs
//! CSV read / write module pub use libcsv::{Reader, Writer, Error}; use rustc_serialize::{Decodable, Encodable}; use std::io::{Read, Write}; use super::super::matrix::{Matrix, BaseMatrix}; impl<T> Matrix<T> where T: Decodable { /// Read csv file as Matrix. /// /// # Examples /// /// ```ignore...
<'a, R: Read>(mut reader: Reader<R>) -> Result<Matrix<T>, Error> { // headers read 1st row regardless of has_headers property let header: Vec<String> = try!(reader.headers()); let mut nrows = 0; let ncols = header.len(); let mut records: Vec<T> = vec![]; for re...
read_csv
identifier_name
stylist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::SourceLocation; use euclid::TypedSize2D; use html5ever::LocalName; use selectors::parser::LocalName...
#[test] fn test_revalidation_selectors() { let test = parse_selectors(&[ // Not revalidation selectors. "div", "div:not(.foo)", "div span", "div > span", // ID selectors. "#foo1", // FIXME(bz) This one should not be a revalidation // selecto...
{ selectors.iter() .map(|x| SelectorParser::parse_author_origin_no_namespace(x).unwrap().0 .into_iter() .nth(0) ...
identifier_body
stylist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::SourceLocation; use euclid::TypedSize2D; use html5ever::LocalName; use selectors::parser::LocalName...
() { let stylist = mock_stylist(); assert_eq!(stylist.device().media_type(), MediaType::Screen); let mut stylist_mut = mock_stylist(); assert_eq!(stylist_mut.device_mut().media_type(), MediaType::Screen); } #[test] fn test_stylist_rule_tree_accessors() { let stylist = mock_stylist(); stylist.ru...
test_stylist_device_accessors
identifier_name
stylist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::SourceLocation; use euclid::TypedSize2D; use html5ever::LocalName; use selectors::parser::LocalName...
"div:only-of-type", // Note: it would be nice to test :moz-any and the various other non-TS // pseudo classes supported by gecko, but we don't have access to those // in these unit tests. :-( // Sibling combinators. "span + div", "span ~ div", // Select...
"div:last-of-type",
random_line_split
core-std.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } fn is_utf8_multibyte() { let s = "b¢€𤭢"; let mut v : Vec<u8> = Vec::new(); for _ in range(0u, 5000) { v.push_all(s.as_bytes()); if!str::is_utf8(v.as_slice()) { fail!("is_utf8 failed"); } } }
{ fail!("is_utf8 failed"); }
conditional_block
core-std.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn maybe_run_test(argv: &[~str], name: ~str, test: ||) { let mut run_test = false; if os::getenv("RUST_BENCH").is_some() { run_test = true } else if argv.len() > 0 { run_test = argv.iter().any(|x| x == &~"all") || argv.iter().any(|x| x == &name) } if!run_test { return ...
{ let argv = os::args(); let _tests = argv.slice(1, argv.len()); bench!(argv, shift_push); bench!(argv, read_line); bench!(argv, vec_plus); bench!(argv, vec_append); bench!(argv, vec_push_all); bench!(argv, is_utf8_ascii); bench!(argv, is_utf8_multibyte); }
identifier_body
core-std.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 mut v1 = Vec::from_elem(30000, 1); let mut v2 = Vec::new(); while v1.len() > 0 { v2.push(v1.shift().unwrap()); } } fn read_line() { use std::io::BufferedReader; let mut path = Path::new(env!("CFG_SRC_DIR")); path.push("src/test/bench/shootout-k-nucleotide.data"); for...
shift_push
identifier_name
core-std.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 mut v1 = Vec::from_elem(30000, 1); let mut v2 = Vec::new(); while v1.len() > 0 { v2.push(v1.shift().unwrap()); } } fn read_line() { use std::io::BufferedReader; let mut path = Path::new(env!("CFG_SRC_DIR")); path.push("src/test/bench/shootout-k-nucleotide.data"); for _ in...
} fn shift_push() {
random_line_split
emptycards.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use super::{ cardgen::group_generated_cards_by_note, CardGenContext, NoteType, NoteTypeID, NoteTypeKind, }; use crate::{ card::CardID, collection::Collection, err::Result, ...
}; let class = if note.current_count == note.empty.len() { "allempty" } else { "" }; write!( buf, "<li class={}>[anki:nid:{}...
random_line_split
emptycards.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use super::{ cardgen::group_generated_cards_by_note, CardGenContext, NoteType, NoteTypeID, NoteTypeKind, }; use crate::{ card::CardID, collection::Collection, err::Result, ...
{ pub nid: NoteID, // (ordinal, card id) pub empty: Vec<(u32, CardID)>, pub current_count: usize, } impl Collection { fn empty_cards_for_notetype(&self, nt: &NoteType) -> Result<Vec<EmptyCardsForNote>> { let ctx = CardGenContext::new(nt, self.usn()?); let existing_cards = self.stor...
EmptyCardsForNote
identifier_name
emptycards.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use super::{ cardgen::group_generated_cards_by_note, CardGenContext, NoteType, NoteTypeID, NoteTypeKind, }; use crate::{ card::CardID, collection::Collection, err::Result, ...
NoteTypeKind::Normal => note .empty .iter() .map(|(ord, _)| { nt.templates .get(*ord as usize) .map(|t| t.name.cl...
{ let nts = self.get_all_notetypes()?; let mut buf = String::new(); for (ntid, notes) in empty { if !notes.is_empty() { let nt = nts.get(ntid).unwrap(); write!( buf, "<div><b>{}</b></div><ol>", ...
identifier_body
error.rs
use libc::c_int; use std::error::Error as Base; use std::fmt; use ffi::nfq_errno; #[derive(Debug)] pub enum Reason { OpenHandle, Bind, Unbind, CreateQueue, SetQueueMode, SetQueueMaxlen, SetVerdict, GetHeader, GetPayload, } pub struct Error { reason: Reason, description: Str...
} pub fn error(reason: Reason, msg: &str, res: Option<c_int>) -> Error { let errno = nfq_errno; let desc = match res { Some(r) => format!("{} (errno: {}, res: {})", msg, errno, r), None => format!("{}, (errno: {})", msg, errno) }; Error { reason: reason, description: de...
{ self.cause.as_ref().map(|c| &**c) }
identifier_body
error.rs
use libc::c_int; use std::error::Error as Base; use std::fmt; use ffi::nfq_errno; #[derive(Debug)] pub enum Reason { OpenHandle, Bind, Unbind, CreateQueue, SetQueueMode, SetQueueMaxlen, SetVerdict, GetHeader, GetPayload, } pub struct Error { reason: Reason, description: Str...
(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { let msg = format!("{:?}: {:?} (cause: {:?})", self.reason, self.description, self.cause); formatter.write_str(msg.as_ref()) } } impl fmt::Display for Error { fn fmt(&self, formatter: &mut fmt::Formatte...
fmt
identifier_name
error.rs
use libc::c_int; use std::error::Error as Base; use std::fmt; use ffi::nfq_errno;
pub enum Reason { OpenHandle, Bind, Unbind, CreateQueue, SetQueueMode, SetQueueMaxlen, SetVerdict, GetHeader, GetPayload, } pub struct Error { reason: Reason, description: String, cause: Option<Box<Base>>, } impl fmt::Debug for Error { fn fmt(&self, formatter: &mut ...
#[derive(Debug)]
random_line_split
mod.rs
#![cfg(target_os = "android")] extern crate android_glue; use libc; use std::ffi::{CString}; use std::sync::mpsc::{Receiver, channel}; use {CreationError, Event, MouseCursor}; use CreationError::OsError; use events::ElementState::{Pressed, Released}; use events::{Touch, TouchPhase}; use std::collections::VecDeque; ...
(&self) -> bool { false } #[inline] pub fn set_title(&self, _: &str) { } #[inline] pub fn show(&self) { } #[inline] pub fn hide(&self) { } #[inline] pub fn get_position(&self) -> Option<(i32, i32)> { None } #[inline] pub fn set_position(&s...
is_closed
identifier_name
mod.rs
#![cfg(target_os = "android")] extern crate android_glue; use libc; use std::ffi::{CString}; use std::sync::mpsc::{Receiver, channel}; use {CreationError, Event, MouseCursor}; use CreationError::OsError; use events::ElementState::{Pressed, Released}; use events::{Touch, TouchPhase}; use std::collections::VecDeque; ...
#[inline] fn is_current(&self) -> bool { self.0.is_current() } #[inline] fn get_proc_address(&self, addr: &str) -> *const libc::c_void { self.0.get_proc_address(addr) } #[inline] fn swap_buffers(&self) -> Result<(), ContextError> { self.0.swap_buffers() } ...
{ self.0.make_current() }
identifier_body
mod.rs
#![cfg(target_os = "android")] extern crate android_glue; use libc; use std::ffi::{CString}; use std::sync::mpsc::{Receiver, channel}; use {CreationError, Event, MouseCursor}; use CreationError::OsError; use events::ElementState::{Pressed, Released}; use events::{Touch, TouchPhase}; use std::collections::VecDeque; ...
opengl: &GlAttributes<&Window>) -> Result<Window, CreationError> { use std::{mem, ptr}; let opengl = opengl.clone().map_sharing(|w| &w.context); let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null() { return Err(OsEr...
impl Window { pub fn new(win_attribs: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
random_line_split
htmlmodelement.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::HTMLModElementBinding; use dom::bindings::js::Root; use dom::bindings::str::...
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLModElement { HTMLModElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local...
new_inherited
identifier_name