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
crt-static.rs
// Test proc-macro crate can be built without additional RUSTFLAGS // on musl target
#![crate_type = "proc-macro"] // FIXME: This don't work when crate-type is specified by attribute // `#![crate_type = "proc-macro"]`, not by `--crate-type=proc-macro` // command line flag. This is beacuse the list of `cfg` symbols is generated // before attributes are parsed. See rustc_interface::util::add_configurati...
// override -Ctarget-feature=-crt-static from compiletest // compile-flags: --crate-type proc-macro -Ctarget-feature= // ignore-wasm32 // ignore-sgx no support for proc-macro crate type // build-pass
random_line_split
hashmap.rs
//! This example demonstrates using Raft to implement a replicated hashmap over `n` servers and //! interact with them over `m` clients. //! //! This example uses Serde serialization. //! //! Comments below will aim to be tailored towards Raft and it's usage. If you have any questions, //! Please, just open an issue. /...
} /// A simple convenience method since this is an example and it should exit if given invalid params. fn parse_addr(addr: &str) -> SocketAddr { SocketAddr::from_str(addr) .ok() .expect(&format!("unable to parse socket address: {}", addr)) } /// Creates a Raft server using the specifi...
{ cas(&args); }
conditional_block
hashmap.rs
//! This example demonstrates using Raft to implement a replicated hashmap over `n` servers and //! interact with them over `m` clients. //! //! This example uses Serde serialization. //! //! Comments below will aim to be tailored towards Raft and it's usage. If you have any questions, //! Please, just open an issue. /...
(&mut self, new_value: &[u8]) -> Vec<u8> { // Deserialize let string = String::from_utf8_lossy(new_value); let message = serde_json::from_str(&string).unwrap(); // Handle let response = match message { Get(key) => { let old_value = &self.map.get(&key)...
apply
identifier_name
hashmap.rs
//! This example demonstrates using Raft to implement a replicated hashmap over `n` servers and //! interact with them over `m` clients. //! //! This example uses Serde serialization. //! //! Comments below will aim to be tailored towards Raft and it's usage. If you have any questions, //! Please, just open an issue. /...
serde_json::to_string(&false) } }, }; // Respond. response.unwrap().into_bytes() } /// `query()` is called on when a client's `.query()` is recieved. It does not go through the /// persistent log, it does not mutate the state of the ...
{ // Deserialize let string = String::from_utf8_lossy(new_value); let message = serde_json::from_str(&string).unwrap(); // Handle let response = match message { Get(key) => { let old_value = &self.map.get(&key).map(|v| v.clone()); serd...
identifier_body
hashmap.rs
//! This example demonstrates using Raft to implement a replicated hashmap over `n` servers and //! interact with them over `m` clients. //! //! This example uses Serde serialization. //! //! Comments below will aim to be tailored towards Raft and it's usage. If you have any questions, //! Please, just open an issue. /...
let mut client = Client::new(cluster); // In this example `serde::json` is used to serialize and deserialize messages. // Since Raft accepts `[u8]` the way you structure your data, the serialization method you // choose, and how you interpret that data is entirely up to you. let payload = serde_jso...
// Clients and be stored and reused, or used once and discarded. // There is very small overhead in connecting a new client to a cluster as it must discover and // identify itself to the leader.
random_line_split
macro_rules.rs
<'a> { parser: RefCell<Parser<'a>>, } impl<'a> ParserAnyMacro<'a> { /// Make sure we don't have any tokens left to parse, so we don't /// silently drop anything. `allow_semi` is so that "optional" /// semicolons at the end of normal expressions aren't complained /// about e.g. the semicolon in `mac...
ParserAnyMacro
identifier_name
macro_rules.rs
.parser.borrow_mut(); if allow_semi && parser.token == token::Semi { parser.bump() } if parser.token!= token::Eof { let token_str = parser.this_token_to_string(); let msg = format!("macro expansion ignores token `{}` and any \ fo...
arg_reader, argument_gram); // Extract the arguments: let lhses = match *argument_map[lhs_nm] { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured lhs") }; for ...
def.body.clone()); let argument_map = parse_or_else(cx.parse_sess(), cx.cfg(),
random_line_split
macro_rules.rs
parser.borrow_mut(); if allow_semi && parser.token == token::Semi { parser.bump() } if parser.token!= token::Eof { let token_str = parser.this_token_to_string(); let msg = format!("macro expansion ignores token `{}` and any \ fol...
op: ast::OneOrMore, num_captures: 2 })), //to phase into semicolon-termination instead of //semicolon-separation TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![TtToken(DUM...
{ let lhs_nm = gensym_ident("lhs"); let rhs_nm = gensym_ident("rhs"); // The pattern that macro_rules matches. // The grammar for macro_rules! is: // $( $lhs:tt => $rhs:tt );+ // ...quasiquoting this would be nice. // These spans won't matter, anyways let match_lhs_tok = MatchNt(lhs_...
identifier_body
grpc_status.rs
// copied from https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/status.h /// gRPC status constants. #[allow(dead_code)] #[derive(Copy, Clone, Debug)] pub enum GrpcStatus { /* Not an error; returned on success */ Ok = 0, /* The operation was cancelled (typically by the caller). */ Canc...
(code: u32) -> Option<GrpcStatus> { ALL_STATUSES.into_iter().cloned().find(|s| s.code() == code) } /// Find GrpcStatus enum variant by code or return default value pub fn from_code_or_unknown(code: u32) -> GrpcStatus { GrpcStatus::from_code(code).unwrap_or(GrpcStatus::Unknown) } }
from_code
identifier_name
grpc_status.rs
// copied from https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/status.h /// gRPC status constants. #[allow(dead_code)] #[derive(Copy, Clone, Debug)] pub enum GrpcStatus { /* Not an error; returned on success */ Ok = 0, /* The operation was cancelled (typically by the caller). */ Canc...
}
{ GrpcStatus::from_code(code).unwrap_or(GrpcStatus::Unknown) }
identifier_body
grpc_status.rs
// copied from https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/status.h /// gRPC status constants. #[allow(dead_code)] #[derive(Copy, Clone, Debug)] pub enum GrpcStatus { /* Not an error; returned on success */ Ok = 0, /* The operation was cancelled (typically by the caller). */ Canc...
/* Operation was attempted past the valid range. E.g., seeking or reading past end of file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that ...
random_line_split
util.rs
use std::fs::File; use std::io::BufReader; use std::io::Error; use std::io::prelude::*; use std::path::Path; pub fn get_mnist_vector(fname: &str) -> Result<Vec<Vec<f32>>, Error> { let path = Path::new(fname); match File::open(&path) { Ok(file) => { let mut new_vec: Vec<Vec<f32>> = Vec::new(...
}
{ let y = read_fvecs_file("./sift_query.fvecs").unwrap(); println!("{} vectors, length of first is {}", y.len(), y[0].len()); }
identifier_body
util.rs
use std::fs::File; use std::io::BufReader; use std::io::Error; use std::io::prelude::*; use std::path::Path; pub fn get_mnist_vector(fname: &str) -> Result<Vec<Vec<f32>>, Error> { let path = Path::new(fname); match File::open(&path) { Ok(file) => { let mut new_vec: Vec<Vec<f32>> = Vec::new(...
(fname: &str) -> Result<Vec<Vec<f32>>> { let path = Path::new(fname); let f = try!(File::open(path)); let mut br = BufReader::new(f); let mut output_vec = Vec::new(); while let Ok(i) = br.read_u32::<LittleEndian>() { let ind = i as usize; let mut line_vec ...
read_fvecs_file
identifier_name
util.rs
use std::fs::File; use std::io::BufReader; use std::io::Error; use std::io::prelude::*; use std::path::Path; pub fn get_mnist_vector(fname: &str) -> Result<Vec<Vec<f32>>, Error> { let path = Path::new(fname); match File::open(&path) { Ok(file) => { let mut new_vec: Vec<Vec<f32>> = Vec::new(...
}
fn test_read_fvecs_file() { let y = read_fvecs_file("./sift_query.fvecs").unwrap(); println!("{} vectors, length of first is {}", y.len(), y[0].len()); }
random_line_split
lib.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/. */ //! An actor-based remote devtools server implementation. Only tested with //! nightly Firefox versions at time of...
&actor_pipelines), Err(Empty) => acceptor.set_timeout(Some(POLL_TIMEOUT)), } } Err(_e) => { /* connection failed */ } Ok(stream) => { let actors = actors.clone(); accept...
pageinfo), Ok(DevtoolsControlMsg::SendConsoleMessage(id, console_message)) => handle_console_message(actors.clone(), id, console_message,
random_line_split
lib.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/. */ //! An actor-based remote devtools server implementation. Only tested with //! nightly Firefox versions at time of...
{ level: String, timeStamp: u64, arguments: Vec<String>, filename: String, lineNumber: u32, columnNumber: u32, } /// Spin up a devtools server that listens for connections on the specified port. pub fn start_server(port: u16) -> Sender<DevtoolsControlMsg> { let (sender, receiver) = channel...
ConsoleMsg
identifier_name
lib.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/. */ //! An actor-based remote devtools server implementation. Only tested with //! nightly Firefox versions at time of...
} } } Err(e) => { println!("error: {}", e.desc); break 'outer } } } } // We need separate actor representations for each script global that exists; // cli...
{ println!("connection established to {}", stream.peer_name().unwrap()); { let actors = actors.lock().unwrap(); let msg = actors.find::<RootActor>("root").encodable(); stream.write_json_packet(&msg); } 'outer: loop { match stream.read_json...
identifier_body
builder.rs
extern crate libc; use std::ops::Drop; use std::collections::HashMap; use std::ffi::CString; use basic_block::BasicBlock; use value::Value; use context::Context; use switch::Switch; use function::Function; use function_call::FunctionCall; use bindings::*; #[derive(PartialEq,Eq)] pub struct IRBuilder(pub(super) LLVMB...
else { Some(BasicBlock(r)) } } pub fn ret_void(&self) -> Value { Value(unsafe { LLVMBuildRetVoid(self.0) }) } pub fn ret(&self, val: Value) -> Value { Value(unsafe { LLVMBuildRet(self.0, val.0) }) } pub fn br(&self, br: BasicBlock) -> Value { Value(unsafe { LLVMBuildB...
{ None }
conditional_block
builder.rs
extern crate libc; use std::ops::Drop; use std::collections::HashMap; use std::ffi::CString; use basic_block::BasicBlock; use value::Value; use context::Context; use switch::Switch; use function::Function; use function_call::FunctionCall; use bindings::*; #[derive(PartialEq,Eq)] pub struct IRBuilder(pub(super) LLVMB...
pub fn position_at_end(&self, bb: BasicBlock) { unsafe { LLVMPositionBuilderAtEnd(self.0, bb.0); } } pub fn insertion_block(&self) -> Option<BasicBlock> { let r = unsafe { LLVMGetInsertBlock(self.0) }; if r.is_null() { None } else { Some(BasicBlock(r)) } } ...
{ IRBuilder(unsafe { LLVMCreateBuilderInContext(cont.0) }) }
identifier_body
builder.rs
extern crate libc; use std::ops::Drop; use std::collections::HashMap; use std::ffi::CString; use basic_block::BasicBlock; use value::Value; use context::Context; use switch::Switch; use function::Function; use function_call::FunctionCall; use bindings::*; #[derive(PartialEq,Eq)] pub struct IRBuilder(pub(super) LLVMB...
IRBuilder(unsafe { LLVMCreateBuilderInContext(cont.0) }) } pub fn position_at_end(&self, bb: BasicBlock) { unsafe { LLVMPositionBuilderAtEnd(self.0, bb.0); } } pub fn insertion_block(&self) -> Option<BasicBlock> { let r = unsafe { LLVMGetInsertBlock(self.0) ...
IRBuilder(unsafe { LLVMCreateBuilder() }) } pub fn new_in_context(cont: &Context) -> IRBuilder {
random_line_split
builder.rs
extern crate libc; use std::ops::Drop; use std::collections::HashMap; use std::ffi::CString; use basic_block::BasicBlock; use value::Value; use context::Context; use switch::Switch; use function::Function; use function_call::FunctionCall; use bindings::*; #[derive(PartialEq,Eq)] pub struct
(pub(super) LLVMBuilderRef); impl IRBuilder { pub fn new() -> IRBuilder { IRBuilder(unsafe { LLVMCreateBuilder() }) } pub fn new_in_context(cont: &Context) -> IRBuilder { IRBuilder(unsafe { LLVMCreateBuilderInContext(cont.0) }) } pub fn position_at_end(&self, bb: BasicBlock) { ...
IRBuilder
identifier_name
input.rs
use sdl2::rect::{Rect, Point}; use sdl2::event::Event as Sdl2Event; use sdl2::keyboard::Keycode; use sdl2::EventPump; use crate::core::*; use crate::ui::{ClickArea, ClickAreas, ScreenPos, UI}; pub fn poll(sdl_events: &mut EventPump, click_areas: &ClickAreas, ui: &UI) -> Option<UserInput> { for event in sdl_events...
{ Rect::new(x, y, w, h).contains_point(Point::new(p.0, p.1)) }
identifier_body
input.rs
use sdl2::rect::{Rect, Point}; use sdl2::event::Event as Sdl2Event; use sdl2::keyboard::Keycode; use sdl2::EventPump; use crate::core::*; use crate::ui::{ClickArea, ClickAreas, ScreenPos, UI}; pub fn
(sdl_events: &mut EventPump, click_areas: &ClickAreas, ui: &UI) -> Option<UserInput> { for event in sdl_events.poll_iter() { match event { Sdl2Event::Quit {.. } | Sdl2Event::KeyDown { keycode: Some(Keycode::Escape), .. } => return Some(UserI...
poll
identifier_name
input.rs
use sdl2::rect::{Rect, Point}; use sdl2::event::Event as Sdl2Event; use sdl2::keyboard::Keycode; use sdl2::EventPump; use crate::core::*; use crate::ui::{ClickArea, ClickAreas, ScreenPos, UI}; pub fn poll(sdl_events: &mut EventPump, click_areas: &ClickAreas, ui: &UI) -> Option<UserInput> { for event in sdl_events...
_ => {} } } None } fn contains_point((x, y, w, h): (i32, i32, u32, u32), p: ScreenPos) -> bool { Rect::new(x, y, w, h).contains_point(Point::new(p.0, p.1)) }
{ return Some(UserInput::StartScrolling()); }
conditional_block
input.rs
use sdl2::rect::{Rect, Point}; use sdl2::event::Event as Sdl2Event; use sdl2::keyboard::Keycode; use sdl2::EventPump;
use crate::ui::{ClickArea, ClickAreas, ScreenPos, UI}; pub fn poll(sdl_events: &mut EventPump, click_areas: &ClickAreas, ui: &UI) -> Option<UserInput> { for event in sdl_events.poll_iter() { match event { Sdl2Event::Quit {.. } | Sdl2Event::KeyDown { keycode: Some(Key...
use crate::core::*;
random_line_split
join_halves.rs
use malachite_base::named::Named; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base::num::conversion::traits::JoinHalves; use malachite_base_test_util::bench::bucketers::pair_max_bit_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_uti...
fn demo_join_halves<T: JoinHalves + PrimitiveUnsigned>(gm: GenMode, config: GenConfig, limit: usize) where T::Half: PrimitiveUnsigned, { for (x, y) in unsigned_pair_gen_var_27::<T::Half>() .get(gm, &config) .take(limit) { println!( "{}::join_halves({}, {}) = {}", ...
{ register_generic_demos!(runner, demo_join_halves, u16, u32, u64, u128); register_generic_benches!(runner, benchmark_join_halves, u16, u32, u64, u128); }
identifier_body
join_halves.rs
use malachite_base::named::Named; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base::num::conversion::traits::JoinHalves; use malachite_base_test_util::bench::bucketers::pair_max_bit_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_uti...
<T: JoinHalves + PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) where T::Half: PrimitiveUnsigned, { run_benchmark( &format!( "{}::join_halves({}, {})", T::NAME, T::Half::NAME, T::Half::NAME ), ...
benchmark_join_halves
identifier_name
join_halves.rs
use malachite_base::named::Named; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base::num::conversion::traits::JoinHalves; use malachite_base_test_util::bench::bucketers::pair_max_bit_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_uti...
fn benchmark_join_halves<T: JoinHalves + PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) where T::Half: PrimitiveUnsigned, { run_benchmark( &format!( "{}::join_halves({}, {})", T::NAME, T::Half::NAME, T...
y, T::join_halves(x, y) ); } }
random_line_split
cursor.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/. */ //! A list of common mouse cursors per CSS3-UI § 8.1.1. use super::ToCss; macro_rules! define_cursor { ( ...
} } } } } define_cursor! { common properties = [ "none" => None = 0, "default" => Default = 1, "pointer" => Pointer = 2, "context-menu" => ContextMenu = 3, "help" => Help = 4, "progress" => Progress = 5, "wait" => Wait...
fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result where W: ::std::fmt::Write { match *self { $( Cursor::$c_variant => dest.write_str($c_css), )+ $( #[cfg(feature = "gecko")] Cursor::$g_variant => dest.write_str($g_css), )+
random_line_split
lib.rs
/* * Panopticon - A libre disassembler * Copyright (C) 2014,2015,2016 Kai Michaelis * * 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 3 of the License, or * (at your option...
//! has a sequence of RREIL instructions (`Statement` type) implementing it. //! //! Panopticon allows multiple programs per project. An example for that would be a //! C# application that calls functions of a DLL written in C. Such an application //! would have two program instances. One for the CIL code of the C# pro...
//! program consists of functions. A function is a control flow //! graph, e.g. a graph with nodes representing a sequence of instructions and //! directed edges for (un)conditional jumps. These instruction sequences are basic //! blocks and contain a list of mnemonics. Panopticon models the semantic of each //! mnemon...
random_line_split
node_table.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...
(path: Option<String>) -> HashMap<NodeId, Node> { let mut nodes: HashMap<NodeId, Node> = HashMap::new(); if let Some(path) = path { let mut path_buf = PathBuf::from(path); path_buf.push("nodes.json"); let mut file = match fs::File::open(path_buf.as_path()) { Ok(file) => file, Err(e) => { debug...
load
identifier_name
node_table.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 to_rlp(&self, rlp: &mut RlpStream) { match self.address { SocketAddr::V4(a) => { rlp.append(&(&a.ip().octets()[..])); } SocketAddr::V6(a) => unsafe { let o: *const u8 = mem::transmute(a.ip().segments().as_ptr()); rlp.append(&from_raw_parts(o, 16)); } }; rlp.append(&self.udp_port);...
}, _ => Err(DecoderError::RlpInconsistentLengthAndData) }); Ok(NodeEndpoint { address: address, udp_port: udp_port }) }
random_line_split
node_table.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...
} impl Display for Node { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.endpoint.udp_port!= self.endpoint.address.port() { try!(write!(f, "enode://{}@{}+{}", self.id.hex(), self.endpoint.address, self.endpoint.udp_port)); } else { try!(write!(f, "enode://{}@{}", self.id.hex(), self.endpoint.add...
{ Node { id: id, endpoint: endpoint, peer_type: PeerType::Optional, failures: 0, last_attempted: None, } }
identifier_body
stdio.rs
use crate::platform::vga::{Color, COLS, ROWS}; use crate::platform::vga; pub struct StdioWriter { pub xpos: u32, pub ypos: u32, pub fg: Color, pub bg: Color } impl Copy for StdioWriter {} impl Clone for StdioWriter { fn clone(&self) -> Self { *self } } impl StdioWriter { pub fn new() -> StdioWriter { StdioWr...
(&mut self, v: u32) { if v == 0 { self.print_char('0'); return; } let mut fac = 1; let mut nv = v; while fac <= v { fac *= 10; } fac /= 10; while fac > 0 { let n = nv / fac; let c = n as u8 + '0' as u8; self.raw_print_char(c); self.go_right(); nv -= n * fac; fac /= 10; } ...
print_dec
identifier_name
stdio.rs
use crate::platform::vga::{Color, COLS, ROWS}; use crate::platform::vga; pub struct StdioWriter { pub xpos: u32, pub ypos: u32, pub fg: Color, pub bg: Color } impl Copy for StdioWriter {} impl Clone for StdioWriter { fn clone(&self) -> Self { *self } } impl StdioWriter { pub fn new() -> StdioWriter { StdioWr...
self.set_cursor(); Ok(()) } }
{ self.raw_print_char(b); self.go_right(); }
random_line_split
stdio.rs
use crate::platform::vga::{Color, COLS, ROWS}; use crate::platform::vga; pub struct StdioWriter { pub xpos: u32, pub ypos: u32, pub fg: Color, pub bg: Color } impl Copy for StdioWriter {} impl Clone for StdioWriter { fn clone(&self) -> Self { *self } } impl StdioWriter { pub fn new() -> StdioWriter { StdioWr...
self.xpos = newx; self.ypos = newy; } fn set_cursor(&self) { vga::move_cursor(self.xpos, self.ypos); } pub fn print_dec(&mut self, v: u32) { if v == 0 { self.print_char('0'); return; } let mut fac = 1; let mut nv = v; while fac <= v { fac *= 10; } fac /= 10; while fac > 0 { le...
{ newy = 0; }
conditional_block
stdio.rs
use crate::platform::vga::{Color, COLS, ROWS}; use crate::platform::vga; pub struct StdioWriter { pub xpos: u32, pub ypos: u32, pub fg: Color, pub bg: Color } impl Copy for StdioWriter {} impl Clone for StdioWriter { fn clone(&self) -> Self { *self } } impl StdioWriter { pub fn new() -> StdioWriter { StdioWr...
pub fn print_char(&mut self, value: char) { self.raw_print_char(value as u8); self.go_right(); self.set_cursor(); } fn raw_print_char(&self, value: u8) { vga::putc(self.xpos, self.ypos, value); vga::setfg(self.xpos, self.ypos, self.fg); vga::setbg(self.xpos, self.ypos, self.bg); } pub fn print_sc...
{ self.print_screen("0x"); let mut i = (sz - 4) as i32; while i >= 0 { let c = match (v >> (i as u32)) & 0xF { c if c <= 9 => c + '0' as u32, c => c - 10 + 'A' as u32, } as u8; self.raw_print_char(c); self.go_right(); i -= 4; } self.set_cursor(); }
identifier_body
next.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; use core::iter::Rev; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self...
None => { assert!(false); } } } assert_eq!(rev.next(), None::<T>); } }
{ assert_eq!(v, 6 - x); }
conditional_block
next.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; use core::iter::Rev; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self...
() { let a: A<T> = A { begin: 1, end: 6 }; let mut rev: Rev<A<T>> = a.rev(); for x in 1..6 { let y: Option<T> = rev.next(); match y { Some(v) => { assert_eq!(v, 6 - x); } None => { assert!(false); } } } assert_eq!(rev.next(), None::<T>); } }
next_test1
identifier_name
next.rs
#[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; use core::iter::Rev; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if se...
#![feature(core)] extern crate core;
random_line_split
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use bytes::{Buf, Bytes}; use diem_infallible::Mutex; use futures::{ channel::mpsc::{self, UnboundedReceiver, UnboundedSender}, io::{AsyncRead, AsyncWrite, Error, ErrorKind, Result}, ready, stream::{FusedStream, Stream}, ...
} /// Stream returned by the `MemoryListener::incoming` function representing the /// stream of sockets received from a listener. #[must_use = "streams do nothing unless polled"] #[derive(Debug)] pub struct Incoming<'a> { inner: &'a mut MemoryListener, } impl<'a> Stream for Incoming<'a> { type Item = Result<...
{ match Pin::new(&mut self.incoming).poll_next(context) { Poll::Ready(Some(socket)) => Poll::Ready(Ok(socket)), Poll::Ready(None) => { let err = Error::new(ErrorKind::Other, "MemoryListener unknown error"); Poll::Ready(Err(err)) } P...
identifier_body
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use bytes::{Buf, Bytes}; use diem_infallible::Mutex; use futures::{ channel::mpsc::{self, UnboundedReceiver, UnboundedSender}, io::{AsyncRead, AsyncWrite, Error, ErrorKind, Result}, ready, stream::{FusedStream, Stream}, ...
port } else { loop { let port = NonZeroU16::new(switchboard.1).unwrap_or_else(|| unreachable!()); // The switchboard is full and all ports are in use if Some(switchboard.0.len()) == std::u16::MAX.checked_sub(1).map(usize::from) { ...
{ return Err(ErrorKind::AddrInUse.into()); }
conditional_block
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use bytes::{Buf, Bytes}; use diem_infallible::Mutex; use futures::{ channel::mpsc::{self, UnboundedReceiver, UnboundedSender}, io::{AsyncRead, AsyncWrite, Error, ErrorKind, Result}, ready, stream::{FusedStream, Stream}, ...
loop { let port = NonZeroU16::new(switchboard.1).unwrap_or_else(|| unreachable!()); // The switchboard is full and all ports are in use if Some(switchboard.0.len()) == std::u16::MAX.checked_sub(1).map(usize::from) { return Err(ErrorKind::A...
} port } else {
random_line_split
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use bytes::{Buf, Bytes}; use diem_infallible::Mutex; use futures::{ channel::mpsc::{self, UnboundedReceiver, UnboundedSender}, io::{AsyncRead, AsyncWrite, Error, ErrorKind, Result}, ready, stream::{FusedStream, Stream}, ...
(self: Pin<&mut Self>, _context: &mut Context) -> Poll<Result<()>> { self.outgoing.close_channel(); Poll::Ready(Ok(())) } }
poll_close
identifier_name
reflect.rs
use std::collections::HashMap; #[derive(RustcDecodable)] pub struct Demo { pub name: String, pub generate: bool, pub control: Control, pub debug: Debug, pub palette: Palette, } #[derive(RustcDecodable)] pub struct Control { pub move_speed: f32, pub rotate_speed: f32, }
pub struct Debug { pub offset: (i32, i32), pub line_jump: i32, pub color: (f32, f32, f32, f32), pub time_factor: u64, } #[derive(RustcDecodable)] pub struct Palette { pub scene: String, pub size: f32, pub model: Model, pub tiles: HashMap<String, String>, pub water_plants: Vec<String...
#[derive(RustcDecodable)]
random_line_split
reflect.rs
use std::collections::HashMap; #[derive(RustcDecodable)] pub struct Demo { pub name: String, pub generate: bool, pub control: Control, pub debug: Debug, pub palette: Palette, } #[derive(RustcDecodable)] pub struct Control { pub move_speed: f32, pub rotate_speed: f32, } #[derive(RustcDecod...
{ pub offset: (i32, i32), pub line_jump: i32, pub color: (f32, f32, f32, f32), pub time_factor: u64, } #[derive(RustcDecodable)] pub struct Palette { pub scene: String, pub size: f32, pub model: Model, pub tiles: HashMap<String, String>, pub water_plants: Vec<String>, pub plant...
Debug
identifier_name
poll.rs
#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::time::TimeSpec; #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::signal::SigSet; use std::os::unix::io::RawFd; use libc; use {Errno, Result}; ...
(&self) -> Option<EventFlags> { EventFlags::from_bits(self.pollfd.revents) } } libc_bitflags! { /// These flags define the different events that can be monitored by `poll` and `ppoll` pub struct EventFlags: libc::c_short { /// There is data to read. POLLIN; /// There is some...
revents
identifier_name
poll.rs
#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::time::TimeSpec; #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::signal::SigSet; use std::os::unix::io::RawFd; use libc; use {Errno, Result}; ...
POLLWRBAND; /// Error condition (only returned in /// [`PollFd::revents`](struct.PollFd.html#method.revents); /// ignored in [`PollFd::new`](struct.PollFd.html#method.new)). /// This bit is also set for a file descriptor referring to the /// write end of a pipe when the r...
/// Priority data may be written.
random_line_split
poll.rs
#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::time::TimeSpec; #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] use sys::signal::SigSet; use std::os::unix::io::RawFd; use libc; use {Errno, Result}; ...
} libc_bitflags! { /// These flags define the different events that can be monitored by `poll` and `ppoll` pub struct EventFlags: libc::c_short { /// There is data to read. POLLIN; /// There is some exceptional condition on the file descriptor. /// /// Possibilities inc...
{ EventFlags::from_bits(self.pollfd.revents) }
identifier_body
build.rs
extern crate phf_codegen; use std::env; use std::fs::File; use std::io::{Write, BufWriter}; use std::path::Path; use std::convert::AsRef; // From http://www.postgresql.org/docs/9.2/static/errcodes-appendix.html static SQLSTATES: &'static [(&'static str, &'static str)] = &[ // Class 00 — Successful Completion ...
tic str, SqlState> = ").unwrap(); let mut builder = phf_codegen::Map::new(); for &(code, variant) in SQLSTATES { builder.entry(code, &format!("SqlState::{}", variant)); } builder.build(file).unwrap(); write!(file, ";\n").unwrap(); } fn make_impl(file: &mut BufWriter<File>) { write!(file...
ap<&'sta
identifier_name
build.rs
extern crate phf_codegen; use std::env; use std::fs::File; use std::io::{Write, BufWriter}; use std::path::Path; use std::convert::AsRef; // From http://www.postgresql.org/docs/9.2/static/errcodes-appendix.html static SQLSTATES: &'static [(&'static str, &'static str)] = &[ // Class 00 — Successful Completion ...
codes #[derive(PartialEq, Eq, Clone)] pub enum SqlState {{ "# ).unwrap(); for &(code, variant) in SQLSTATES { write!(file, " /// `{}` {},\n", code, variant).unwrap(); } write!(file, " /// An unknown code Unknown(String) }} " ).unwrap(); } fn make...
); let path = path.join("sqlstate.rs"); let mut file = BufWriter::new(File::create(&path).unwrap()); make_enum(&mut file); make_map(&mut file); make_impl(&mut file); make_debug(&mut file); } fn make_enum(file: &mut BufWriter<File>) { write!(file, r#"/// SQLSTATE error
identifier_body
build.rs
extern crate phf_codegen; use std::env; use std::fs::File; use std::io::{Write, BufWriter}; use std::path::Path; use std::convert::AsRef; // From http://www.postgresql.org/docs/9.2/static/errcodes-appendix.html static SQLSTATES: &'static [(&'static str, &'static str)] = &[ // Class 00 — Successful Completion ...
// Class 27 — Triggered Data Change Violation ("27000", "TriggeredDataChangeViolation"), // Class 28 — Invalid Authorization Specification ("28000", "InvalidAuthorizationSpecification"), ("28P01", "InvalidPassword"), // Class 2B — Dependent Privilege Descriptors Still E...
random_line_split
coverage.rs
use truetype::{GlyphID, Result, Tape, Value}; /// A coverage table. #[derive(Clone, Debug)] pub enum Coverage { /// Format 1. Format1(Coverage1), /// Format 2. Format2(Coverage2), } table! { #[doc = "A coverage table in format 1."] pub Coverage1 { // CoverageFormat1 format (u16), // Co...
} }
2 => Coverage::Format2(tape.take()?), _ => raise!("found an unknown format of the coverage table"), })
random_line_split
coverage.rs
use truetype::{GlyphID, Result, Tape, Value}; /// A coverage table. #[derive(Clone, Debug)] pub enum Coverage { /// Format 1. Format1(Coverage1), /// Format 2. Format2(Coverage2), } table! { #[doc = "A coverage table in format 1."] pub Coverage1 { // CoverageFormat1 format (u16), // Co...
} impl Value for Coverage { fn read<T: Tape>(tape: &mut T) -> Result<Self> { Ok(match tape.peek::<u16>()? { 1 => Coverage::Format1(tape.take()?), 2 => Coverage::Format2(tape.take()?), _ => raise!("found an unknown format of the coverage table"), }) } }
{ Coverage::Format1(Coverage1::default()) }
identifier_body
coverage.rs
use truetype::{GlyphID, Result, Tape, Value}; /// A coverage table. #[derive(Clone, Debug)] pub enum Coverage { /// Format 1. Format1(Coverage1), /// Format 2. Format2(Coverage2), } table! { #[doc = "A coverage table in format 1."] pub Coverage1 { // CoverageFormat1 format (u16), // Co...
() -> Self { Coverage::Format1(Coverage1::default()) } } impl Value for Coverage { fn read<T: Tape>(tape: &mut T) -> Result<Self> { Ok(match tape.peek::<u16>()? { 1 => Coverage::Format1(tape.take()?), 2 => Coverage::Format2(tape.take()?), _ => raise!("found a...
default
identifier_name
lib.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
extern crate core; pub mod macros; pub mod reader; pub mod values; pub mod writer; pub use self::reader::read; pub use self::values::{KeyType, SimpleValue, Value}; pub use self::writer::write;
extern crate alloc; #[cfg(feature = "std")]
random_line_split
image_action.rs
use super::action::Action; use super::image::Image; use crate::method::{Create, Get, List}; use crate::request::{ImageActionRequest, ImageRequest}; use crate::STATIC_URL_ERROR; use serde::Serialize; use std::fmt::Display; const IMAGE_ACTIONS_SEGMENT: &str = "actions"; impl ImageRequest<Get, Image> { /// [Digital ...
/// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#convert-an-image-to-a-snapshot) pub fn convert(mut self) -> ImageActionRequest<Create, Action> { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_S...
{ self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT); self.set_body(json!({ "type": "transfer", "region": region, })); self.transmute() }
identifier_body
image_action.rs
use super::action::Action; use super::image::Image; use crate::method::{Create, Get, List}; use crate::request::{ImageActionRequest, ImageRequest}; use crate::STATIC_URL_ERROR; use serde::Serialize; use std::fmt::Display; const IMAGE_ACTIONS_SEGMENT: &str = "actions"; impl ImageRequest<Get, Image> { /// [Digital ...
.path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT) .push(&id.to_string()); self.transmute() } }
pub fn action(mut self, id: usize) -> ImageActionRequest<Get, Action> { self.url_mut()
random_line_split
image_action.rs
use super::action::Action; use super::image::Image; use crate::method::{Create, Get, List}; use crate::request::{ImageActionRequest, ImageRequest}; use crate::STATIC_URL_ERROR; use serde::Serialize; use std::fmt::Display; const IMAGE_ACTIONS_SEGMENT: &str = "actions"; impl ImageRequest<Get, Image> { /// [Digital ...
(mut self, id: usize) -> ImageActionRequest<Get, Action> { self.url_mut() .path_segments_mut() .expect(STATIC_URL_ERROR) .push(IMAGE_ACTIONS_SEGMENT) .push(&id.to_string()); self.transmute() } }
action
identifier_name
tty.rs
use std::process::{Command, Stdio, ChildStderr, Child}; use std::ptr; use std::io::{Read, Error}; use std::fs::File; #[cfg(target_os = "linux")] pub fn get_tty(mut command: Command) -> Handle { use libc::{self, winsize, c_int, TIOCGWINSZ}; use std::os::unix::io::FromRawFd; use std::fs::File; let mut master: c_...
{ Pty {child: Child, fd: usize, file: File }, Stderr(ChildStderr) } impl Read for Handle { fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> { match *self { Handle::Pty{ref mut file,..} => file.read(buf), Handle::Stderr(ref mut stderr) => stderr.read(buf) } } } pub fn handle_err(handle: &mut...
Handle
identifier_name
tty.rs
use std::process::{Command, Stdio, ChildStderr, Child}; use std::ptr; use std::io::{Read, Error}; use std::fs::File; #[cfg(target_os = "linux")] pub fn get_tty(mut command: Command) -> Handle { use libc::{self, winsize, c_int, TIOCGWINSZ}; use std::os::unix::io::FromRawFd; use std::fs::File; let mut master: c_...
} panic!("Error: {:?}", err) } #[cfg(target_os = "linux")] pub fn get_handle(command: Command, tty: bool) -> Handle { if tty { return get_tty(command) } get_handle_base(command) } #[cfg(not(target_os = "linux"))] pub fn get_handle(mut command: Command, tty: bool) -> Handle { get_handle_base...
{ return true; }
conditional_block
tty.rs
use std::process::{Command, Stdio, ChildStderr, Child}; use std::ptr; use std::io::{Read, Error}; use std::fs::File; #[cfg(target_os = "linux")] pub fn get_tty(mut command: Command) -> Handle { use libc::{self, winsize, c_int, TIOCGWINSZ}; use std::os::unix::io::FromRawFd; use std::fs::File; let mut master: c_...
} pub fn handle_err(handle: &mut Handle, err: &Error) -> bool { if let Handle::Pty {ref mut child,..} = *handle { if child.try_wait().unwrap().is_some() { return true; } } panic!("Error: {:?}", err) } #[cfg(target_os = "linux")] pub fn get_handle(command: Command, tty: bool) -> Handle { if tty { ...
{ match *self { Handle::Pty{ref mut file, ..} => file.read(buf), Handle::Stderr(ref mut stderr) => stderr.read(buf) } }
identifier_body
tty.rs
use std::process::{Command, Stdio, ChildStderr, Child}; use std::ptr; use std::io::{Read, Error}; use std::fs::File; #[cfg(target_os = "linux")] pub fn get_tty(mut command: Command) -> Handle { use libc::{self, winsize, c_int, TIOCGWINSZ}; use std::os::unix::io::FromRawFd; use std::fs::File; let mut master: c_...
.spawn() .unwrap(); Handle::Stderr(child.stderr.unwrap()) }
get_handle_base(command) } fn get_handle_base(mut command: Command) -> Handle { let child = command.stderr(Stdio::piped())
random_line_split
lib.rs
//! The library allows to send data to carbon (also known as graphite) //! //! #Example //! //! ```ignore //! extern crate rotor; //! extern crate rotor_tools; //! //! use rotor_tools::loop_ext::LoopExt; //! //! let loopinst = rotor::Loop::new(&rotor::Config::new()).instantiate(()); //! let sink = loopinst.add_and_fetc...
//! } //! ``` //! //! If you need to format the metric name, use `format_args!` instead of //! `format!` as the former does not preallocate a buffer: //! ``` //! snd.add_int_at( //! format_args!("servers.{}.metrics.{}", hostname, metric), //! metric_value, timestamp); //! ``` //! extern crate rotor; extern crat...
//! sender.add_u64("some.value", 1234);
random_line_split
lib.rs
//! The library allows to send data to carbon (also known as graphite) //! //! #Example //! //! ```ignore //! extern crate rotor; //! extern crate rotor_tools; //! //! use rotor_tools::loop_ext::LoopExt; //! //! let loopinst = rotor::Loop::new(&rotor::Config::new()).instantiate(()); //! let sink = loopinst.add_and_fetc...
<C, S>(Arc<Mutex<Persistent<proto::CarbonProto<C, S>>>>, Notifier) where S: ActiveStream; /// The sender object, which has convenience methods to send the data /// /// Note ``Sender()`` holds lock on the underlying buffer and doesn't /// send data, until sender is dropped. This is useful for ...
Sink
identifier_name
compositor_task.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/. */ //! Communication with the compositor task. pub use windowing; pub use constellation::{FrameId, SendableFrameTree...
(&mut self, pipeline_id: PipelineId, paint_state: PaintState) { self.send(Msg::ChangePaintState(pipeline_id, paint_state)) } } /// Messages from the painting task and the constellation task to the compositor task. pub enum Msg { /// Requests that the compositor shut down. Exit(Sender<()>), ///...
set_paint_state
identifier_name
compositor_task.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/. */ //! Communication with the compositor task. pub use windowing; pub use constellation::{FrameId, SendableFrameTree...
} pub trait CompositorEventListener { fn handle_event(&mut self, event: WindowEvent) -> bool; fn repaint_synchronously(&mut self); fn shutdown(&mut self); fn pinch_zoom_level(&self) -> f32; /// Requests that the compositor send the title for the main frame as soon as possible. fn get_title_for...
{ match window { Some(window) => { box compositor::IOCompositor::create(window, sender, receiver, constellation_chan.clone(),...
identifier_body
compositor_task.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/. */ //! Communication with the compositor task. pub use windowing; pub use constellation::{FrameId, SendableFrameTree...
use std::rc::Rc; /// Sends messages to the compositor. This is a trait supplied by the port because the method used /// to communicate with the compositor may have to kick OS event loops awake, communicate cross- /// process, and so forth. pub trait CompositorProxy :'static + Send { /// Sends a message to the comp...
random_line_split
split_operation_metadata.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use fnv::FnvHashSet; use graphql_ir::{Argument, ConstantValue, Directive, Value}; use intern...
else { panic!("Expected parent sources to be a constant of list."); } } }
{ let parent_sources = source_definition_names .iter() .map(|val| { if let ConstantValue::String(name) = val { name } else { panic!("Expected item in the parent sources to be a StringKey."...
conditional_block
split_operation_metadata.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use fnv::FnvHashSet; use graphql_ir::{Argument, ConstantValue, Directive, Value}; use intern...
Self { derived_from, parent_sources, raw_response_type, } } else { panic!("Expected parent sources to be a constant of list."); } } }
} }) .cloned() .collect();
random_line_split
split_operation_metadata.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use fnv::FnvHashSet; use graphql_ir::{Argument, ConstantValue, Directive, Value}; use intern...
arguments.push(Argument { name: WithLocation::generated(*ARG_RAW_RESPONSE_TYPE), value: WithLocation::generated(Value::Constant(ConstantValue::Null())), }); } Directive { name: WithLocation::generated(*DIRECTIVE_SPLIT_OPERATION), ...
{ let mut arguments = vec![ Argument { name: WithLocation::generated(*ARG_DERIVED_FROM), value: WithLocation::generated(Value::Constant(ConstantValue::String( self.derived_from, ))), }, Argument { ...
identifier_body
split_operation_metadata.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use fnv::FnvHashSet; use graphql_ir::{Argument, ConstantValue, Directive, Value}; use intern...
(&self) -> Directive { let mut arguments = vec![ Argument { name: WithLocation::generated(*ARG_DERIVED_FROM), value: WithLocation::generated(Value::Constant(ConstantValue::String( self.derived_from, ))), }, A...
to_directive
identifier_name
test.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ unsafe { let data = data_create(MAGIC); assert_eq!(data_get(data), MAGIC); } }
identifier_body
test.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { unsafe { let data = data_create(MAGIC); assert_eq!(data_get(data), MAGIC); } }
main
identifier_name
test.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(extern_types)] #[link(name = "ctest", kind = "static")] extern { type da...
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
random_line_split
fnv.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/. */ //! This file stolen wholesale from rustc/src/librustc/util/nodemap.rs pub use std::hash::{Hash, Hasher, Writer};...
(u64); impl Hasher<FnvState> for FnvHasher { fn hash<Sized? T: Hash<FnvState>>(&self, t: &T) -> u64 { let mut state = FnvState(0xcbf29ce484222325); t.hash(&mut state); let FnvState(ret) = state; return ret; } } impl Writer for FnvState { fn write(&mut self, bytes: &[u8]) { ...
FnvState
identifier_name
fnv.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/. */ //! This file stolen wholesale from rustc/src/librustc/util/nodemap.rs pub use std::hash::{Hash, Hasher, Writer};...
let FnvState(ret) = state; return ret; } } impl Writer for FnvState { fn write(&mut self, bytes: &[u8]) { let FnvState(mut hash) = *self; for byte in bytes.iter() { hash = hash ^ (*byte as u64); hash = hash * 0x100000001b3; } *self = FnvSt...
random_line_split
table_caption.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! CSS table formatting contexts. use crate::block::BlockFlow; use crate::context::LayoutContext; use crate::di...
fn build_display_list(&mut self, state: &mut DisplayListBuildState) { debug!("build_display_list_table_caption: same process as block flow"); self.block_flow.build_display_list(state); } fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) { self.blo...
{ self.block_flow .update_late_computed_block_position_if_necessary(block_position) }
identifier_body
table_caption.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! CSS table formatting contexts. use crate::block::BlockFlow; use crate::context::LayoutContext; use crate::di...
} fn as_block(&self) -> &BlockFlow { &self.block_flow } fn bubble_inline_sizes(&mut self) { self.block_flow.bubble_inline_sizes(); } fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) { debug!( "assign_inline_sizes({}): assigning inline_size ...
fn as_mut_block(&mut self) -> &mut BlockFlow { &mut self.block_flow
random_line_split
table_caption.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! CSS table formatting contexts. use crate::block::BlockFlow; use crate::context::LayoutContext; use crate::di...
(&self) -> FlowClass { FlowClass::TableCaption } fn as_mut_block(&mut self) -> &mut BlockFlow { &mut self.block_flow } fn as_block(&self) -> &BlockFlow { &self.block_flow } fn bubble_inline_sizes(&mut self) { self.block_flow.bubble_inline_sizes(); } fn...
class
identifier_name
fun1.rs
fn sqr(x: f64) -> f64 { x * x } //absolute value fn abs(x: f64) -> f64 { if x > 0.0 { x } else { -x } } //ensure a number always falls in the given range fn clamp(x: f64, x1: f64, x2: f64) -> f64 { if x < x1 { x1 } else if x > x2 { x2 } else { x ...
() { let res = sqr(2.0); println!("square is {}", res); let num = -1.0; let abs1 = abs(num); println!("absolute value of {} is {}", num, abs1); let min = 5.0; let max = 18.0; let clamp_min = 1.0; let clamp_max = 99.0; let dont_clamp = 7.0; println!("clamping {}: {}", clamp_...
main
identifier_name
fun1.rs
fn sqr(x: f64) -> f64 { x * x } //absolute value fn abs(x: f64) -> f64 { if x > 0.0 { x } else
} //ensure a number always falls in the given range fn clamp(x: f64, x1: f64, x2: f64) -> f64 { if x < x1 { x1 } else if x > x2 { x2 } else { x } } fn main() { let res = sqr(2.0); println!("square is {}", res); let num = -1.0; let abs1 = abs(num); println!...
{ -x }
conditional_block
fun1.rs
fn sqr(x: f64) -> f64 { x * x } //absolute value fn abs(x: f64) -> f64 { if x > 0.0 { x } else { -x } } //ensure a number always falls in the given range fn clamp(x: f64, x1: f64, x2: f64) -> f64 { if x < x1 { x1 } else if x > x2 { x2 } else { x ...
{ let res = sqr(2.0); println!("square is {}", res); let num = -1.0; let abs1 = abs(num); println!("absolute value of {} is {}", num, abs1); let min = 5.0; let max = 18.0; let clamp_min = 1.0; let clamp_max = 99.0; let dont_clamp = 7.0; println!("clamping {}: {}", clamp_min...
identifier_body
fun1.rs
fn sqr(x: f64) -> f64 { x * x } //absolute value fn abs(x: f64) -> f64 { if x > 0.0 { x } else { -x } } //ensure a number always falls in the given range fn clamp(x: f64, x1: f64, x2: f64) -> f64 { if x < x1 { x1 } else if x > x2 { x2 } else { x ...
let dont_clamp = 7.0; println!("clamping {}: {}", clamp_min, clamp(clamp_min, min, max)); println!("clamping {}: {}", clamp_max, clamp(clamp_max, min, max)); println!("clamping {}: {}", dont_clamp, clamp(dont_clamp, min, max)); }
let min = 5.0; let max = 18.0; let clamp_min = 1.0; let clamp_max = 99.0;
random_line_split
commands.rs
use std::collections::VecDeque; use std::sync::{atomic, mpsc, Arc, Condvar, Mutex}; use std::{mem, ptr}; use context::CommandContext; use GliumCreationError; use glutin; const CLOSURES_MAX_SIZE: usize = 64; const MAX_QUEUE_SIZE: usize = 64; pub struct Sender { queue: Arc<Queue>, } pub struct Receiver { queu...
{ /// storage for the closure data: [usize; CLOSURES_MAX_SIZE], /// function used to execute the closure call_fn: fn([usize; CLOSURES_MAX_SIZE], CommandContext), } enum InternalMessage { EndFrame, Stop, Execute { /// storage for the closure data: [usize; CLOSURES_MAX_SIZE],...
Exec
identifier_name
commands.rs
use std::collections::VecDeque; use std::sync::{atomic, mpsc, Arc, Condvar, Mutex}; use std::{mem, ptr}; use context::CommandContext; use GliumCreationError; use glutin; const CLOSURES_MAX_SIZE: usize = 64; const MAX_QUEUE_SIZE: usize = 64; pub struct Sender { queue: Arc<Queue>, } pub struct Receiver { queu...
}
}
random_line_split
commands.rs
use std::collections::VecDeque; use std::sync::{atomic, mpsc, Arc, Condvar, Mutex}; use std::{mem, ptr}; use context::CommandContext; use GliumCreationError; use glutin; const CLOSURES_MAX_SIZE: usize = 64; const MAX_QUEUE_SIZE: usize = 64; pub struct Sender { queue: Arc<Queue>, } pub struct Receiver { queu...
} impl Receiver { pub fn pop(&self) -> Message { let mut lock = self.queue.queue.lock().unwrap(); loop { let msg = lock.pop_front(); self.queue.condvar.notify_one(); match msg { Some(InternalMessage::EndFrame) => return Message::EndFrame, ...
{ let mut lock = self.queue.queue.lock().unwrap(); lock.push_back(InternalMessage::Stop); self.queue.condvar.notify_one(); }
identifier_body
commands.rs
use std::collections::VecDeque; use std::sync::{atomic, mpsc, Arc, Condvar, Mutex}; use std::{mem, ptr}; use context::CommandContext; use GliumCreationError; use glutin; const CLOSURES_MAX_SIZE: usize = 64; const MAX_QUEUE_SIZE: usize = 64; pub struct Sender { queue: Arc<Queue>, } pub struct Receiver { queu...
} } } } impl Exec { pub fn execute(self, ctxt: CommandContext) { let f = self.call_fn; f(self.data, ctxt); } } #[cfg(test)] mod test { use super::{Message, channel}; #[test] fn simple() { let (sender, receiver) = channel(); let (tx, rx) = :...
{ if self.closed.load(atomic::Ordering::Acquire) { return Message::Stop; } lock = self.queue.condvar.wait(lock).unwrap(); }
conditional_block
simple.rs
use tracing::Level; mod yak_shave; fn main() { assert!(Level::TRACE > Level::DEBUG); assert!(Level::ERROR < Level::WARN); assert!(Level::INFO <= Level::DEBUG); // Global default collector if false
// Local collector { let collector = tracing_subscriber::fmt() .with_max_level(Level::TRACE) .finish(); tracing::collect::with_default(collector, ||{ tracing::info!("This will be logged to stdout"); }); tracing::info!("This will not be logged to stdo...
{ tracing_subscriber::fmt() // enable everything .with_max_level(Level::TRACE) // sets this to be the default, global collector for this application. .init(); let number_of_yaks = 3; // this creates a new event, outside of any spans. traci...
conditional_block
simple.rs
use tracing::Level; mod yak_shave; fn main()
"yak shaving completed." ); } // Local collector { let collector = tracing_subscriber::fmt() .with_max_level(Level::TRACE) .finish(); tracing::collect::with_default(collector, ||{ tracing::info!("This will be logged to stdout"); }); ...
{ assert!(Level::TRACE > Level::DEBUG); assert!(Level::ERROR < Level::WARN); assert!(Level::INFO <= Level::DEBUG); // Global default collector if false { tracing_subscriber::fmt() // enable everything .with_max_level(Level::TRACE) // sets this to be the d...
identifier_body
simple.rs
use tracing::Level; mod yak_shave; fn
() { assert!(Level::TRACE > Level::DEBUG); assert!(Level::ERROR < Level::WARN); assert!(Level::INFO <= Level::DEBUG); // Global default collector if false { tracing_subscriber::fmt() // enable everything .with_max_level(Level::TRACE) // sets this to be the...
main
identifier_name
simple.rs
use tracing::Level; mod yak_shave; fn main() { assert!(Level::TRACE > Level::DEBUG); assert!(Level::ERROR < Level::WARN); assert!(Level::INFO <= Level::DEBUG); // Global default collector if false { tracing_subscriber::fmt() // enable everything
let number_of_yaks = 3; // this creates a new event, outside of any spans. tracing::info!(number_of_yaks, "preparing to shave yaks"); let number_shaved = yak_shave::shave_all(number_of_yaks); tracing::info!( all_yaks_shaved = number_shaved == number_of_yaks, ...
.with_max_level(Level::TRACE) // sets this to be the default, global collector for this application. .init();
random_line_split
lib.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/. */ extern crate compiletest_rs as compiletest; use std::env; use std::path::PathBuf; pub fn
(mode: &'static str) { let mut config = compiletest::default_config(); let cfg_mode = mode.parse().ok().expect("Invalid mode"); config.mode = cfg_mode; config.src_base = PathBuf::from(format!("{}", mode)); let mut base_path = env::current_dir().expect("Current directory is invalid"); base_pat...
run_mode
identifier_name
lib.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/. */ extern crate compiletest_rs as compiletest; use std::env; use std::path::PathBuf; pub fn run_mode(mode: &'static...
{ let mut config = compiletest::default_config(); let cfg_mode = mode.parse().ok().expect("Invalid mode"); config.mode = cfg_mode; config.src_base = PathBuf::from(format!("{}", mode)); let mut base_path = env::current_dir().expect("Current directory is invalid"); base_path.pop(); base_pat...
identifier_body
lib.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/. */ extern crate compiletest_rs as compiletest; use std::env; use std::path::PathBuf; pub fn run_mode(mode: &'static...
compiletest::run_tests(&config); }
config.target_rustcflags = Some(format!("-L {} -L {}", debug_path.display(), deps_path.display()));
random_line_split
filesearch.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&self, f: |&Path| -> FileMatch) { let mut visited_dirs = HashSet::new(); let mut found = false; debug!("filesearch: searching additional lib search paths [{:?}]", self.addl_lib_search_paths.borrow().len()); for path in self.addl_lib_search_paths.borrow().iter() { ...
for_each_lib_search_path
identifier_name
filesearch.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
FileDoesntMatch => () } } visited_dirs.insert(tlib_path.as_vec().to_owned()); // Try RUST_PATH if!found { let rustpath = rust_path(); for path in rustpath.iter() { let tlib_path = make_rustpkg_lib_path( ...
{ let mut visited_dirs = HashSet::new(); let mut found = false; debug!("filesearch: searching additional lib search paths [{:?}]", self.addl_lib_search_paths.borrow().len()); for path in self.addl_lib_search_paths.borrow().iter() { match f(path) { ...
identifier_body
filesearch.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
Some(mut p) => { p.pop(); p.pop(); p } None => fail!("can't determine value for sysroot") } } #[cfg(windows)] static PATH_ENTRY_SEPARATOR: &'static str = ";"; #[cfg(not(windows))] static PATH_ENTRY_SEPARATOR: &'static str = ":"; /// Returns RUST_PATH as a string, without default paths added pub fn...
match canonicalize(os::self_exe_name()) {
random_line_split
mod.rs
mod case; mod functions; mod parse; mod splitter; pub(crate) use self::{ parse::parse, splitter::{StatementError, StatementSplitter}, }; use shell::flow_control::Statement; /// Parses a given statement string and return's the corresponding mapped /// `Statement` pub(crate) fn parse_and_validate<'a>(statement:...
}
{ let (args, description) = split_pattern("a:int b:bool -- a comment", "--"); assert_eq!(args, "a:int b:bool"); assert_eq!(description, Some("a comment")); let (args, description) = split_pattern("a --", "--"); assert_eq!(args, "a"); assert_eq!(description, None); ...
identifier_body
mod.rs
mod case; mod functions; mod parse; mod splitter; pub(crate) use self::{ parse::parse, splitter::{StatementError, StatementSplitter}, }; use shell::flow_control::Statement; /// Parses a given statement string and return's the corresponding mapped /// `Statement` pub(crate) fn parse_and_validate<'a>(statement:...
() { let (args, description) = split_pattern("a:int b:bool -- a comment", "--"); assert_eq!(args, "a:int b:bool"); assert_eq!(description, Some("a comment")); let (args, description) = split_pattern("a --", "--"); assert_eq!(args, "a"); assert_eq!(description, None); ...
statement_pattern_splitting
identifier_name