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
mod.rs
//! A buffer is a memory location accessible to the video card. //! //! The purpose of buffers is to serve as a space where the GPU can read from or write data to. //! It can contain a list of vertices, indices, uniform data, etc. //! //! # Buffers management in glium //! //! There are three levels of abstraction in gl...
{ ArrayBuffer, PixelPackBuffer, PixelUnpackBuffer, UniformBuffer, CopyReadBuffer, CopyWriteBuffer, AtomicCounterBuffer, DispatchIndirectBuffer, DrawIndirectBuffer, QueryBuffer, ShaderStorageBuffer, TextureBuffer, TransformFeedbackBuffer, ElementArrayBuffer, } im...
BufferType
identifier_name
mod.rs
//! A buffer is a memory location accessible to the video card. //! //! The purpose of buffers is to serve as a space where the GPU can read from or write data to. //! It can contain a list of vertices, indices, uniform data, etc. //! //! # Buffers management in glium //! //! There are three levels of abstraction in gl...
} /// Type of a buffer. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum BufferType { ArrayBuffer, PixelPackBuffer, PixelUnpackBuffer, UniformBuffer, CopyReadBuffer, CopyWriteBuffer, AtomicCounterBuffer, DispatchIndirectBuffer, DrawIndirectBuffer, QueryBuffer, ShaderSt...
{ BufferMode::Default }
identifier_body
coerce-reborrow-mut-vec-arg.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let mut the_vec = vec!(1, 2, 3, 100); bar(&mut the_vec); assert_eq!(the_vec, [100, 3, 2, 1]); }
pub fn main() {
random_line_split
coerce-reborrow-mut-vec-arg.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 ...
(v: &mut [usize]) { v.reverse(); } fn bar(v: &mut [usize]) { reverse(v); reverse(v); reverse(v); } pub fn main() { let mut the_vec = vec!(1, 2, 3, 100); bar(&mut the_vec); assert_eq!(the_vec, [100, 3, 2, 1]); }
reverse
identifier_name
coerce-reborrow-mut-vec-arg.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 ...
fn bar(v: &mut [usize]) { reverse(v); reverse(v); reverse(v); } pub fn main() { let mut the_vec = vec!(1, 2, 3, 100); bar(&mut the_vec); assert_eq!(the_vec, [100, 3, 2, 1]); }
{ v.reverse(); }
identifier_body
new-unicode-escapes.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 ...
assert_eq!(s, correct_s); }
random_line_split
new-unicode-escapes.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let s = "\u{2603}"; assert_eq!(s, "☃"); let s = "\u{2a10}\u{2A01}\u{2Aa0}"; assert_eq!(s, "⨐⨁⪠"); let s = "\\{20}"; let mut correct_s = String::from_str("\\"); correct_s.push_str("{20}"); assert_eq!(s, correct_s); }
main
identifier_name
new-unicode-escapes.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let s = "\u{2603}"; assert_eq!(s, "☃"); let s = "\u{2a10}\u{2A01}\u{2Aa0}"; assert_eq!(s, "⨐⨁⪠"); let s = "\\{20}"; let mut correct_s = String::from_str("\\"); correct_s.push_str("{20}"); assert_eq!(s, correct_s); }
identifier_body
main.rs
#![feature(proc_macro)] extern crate hyper; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate ansi_term; extern crate rocksdb; extern crate clap; #[macro_use(o, slog_log, slog_trace, slog_debug, slog_info, slog_warn, slog_error)] extern crate slog; extern crate slog_term; // #[macro_use...
identifier_body
main.rs
#![feature(proc_macro)] extern crate hyper; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate ansi_term; extern crate rocksdb; extern crate clap; #[macro_use(o, slog_log, slog_trace, slog_debug, slog_info, slog_warn, slog_error)] extern crate slog; extern crate slog_term; // #[macro_use...
(query: &str, cache_db: &DB, update_cache: bool, logger: &slog::Logger) -> Result<String, YDCVError> { let mut request_url = REQUEST_BASE.to_string(); request_url.push_str(query); let client = Client::new(); slog_debug!(logger, "开始从网络获取翻译结果"); let mut res = client.get(&request_url).header(Connec...
get_remote_json_translation
identifier_name
main.rs
#![feature(proc_macro)] extern crate hyper; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate ansi_term; extern crate rocksdb; extern crate clap; #[macro_use(o, slog_log, slog_trace, slog_debug, slog_info, slog_warn, slog_error)] extern crate slog; extern crate slog_term; // #[macro_use...
)) } fn main() { slog_envlogger::init().unwrap(); let drain = slog_term::streamer().compact().build().fuse(); let root_log = slog::Logger::root(drain, o!("version" => "0.3.0")); let matches = App::new("YDCV") .version("0.3.0") .author("Greedwolf DSS <greedwolf.dss@gmail.com>") .ab...
地缓存"); cache_db.put(query.as_bytes(), trans_result.translation_description().as_bytes())?; } Ok(trans_result.translation_description(
conditional_block
main.rs
#![feature(proc_macro)] extern crate hyper; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate ansi_term; extern crate rocksdb; extern crate clap; #[macro_use(o, slog_log, slog_trace, slog_debug, slog_info, slog_warn, slog_error)] extern crate slog; extern crate slog_term; // #[macro_use...
}, }; slog_debug!(root_log, "cache path: {}", cache_path); let db = match DB::open_default(cache_path.as_str()) { Ok(db) => db, Err(err) => { slog_error!(root_log, "无法创建RocksDB的存储目录 error: {}", err); return; } }; let db_key = trans.as_bytes()...
Some(path) => path, None => { slog_error!(root_log, "没有缓存路径"); return;
random_line_split
main.rs
use bracket_lib::prelude::*; enum GameMode { Menu, Playing, End, } struct Player { x: i32, y: i32, velocity: f32, } impl Player { fn new(x: i32, y: i32) -> Self { Player { x, y, velocity: 0.0, } } fn render(&mut self, ctx: &mut ...
} fn render(&mut self, ctx: &mut BTerm, player_x: i32) { let screen_x = self.x - player_x; let half_size = self.size / 2; // Draw the top half of the ovstacle for y in 0..self.gap_y - half_size { ctx.set( screen_x, y, ...
}
random_line_split
main.rs
use bracket_lib::prelude::*; enum GameMode { Menu, Playing, End, } struct Player { x: i32, y: i32, velocity: f32, } impl Player { fn new(x: i32, y: i32) -> Self { Player { x, y, velocity: 0.0, } } fn render(&mut self, ctx: &mut ...
} fn restart(&mut self) { self.player = Player::new(5, 25); self.frame_time = 0.0; self.mode = GameMode::Playing; } } impl GameState for State { fn tick(&mut self, ctx: &mut BTerm) { match self.mode { GameMode::Menu => self.main_menu(ctx), Ga...
{ match key { VirtualKeyCode::P => self.restart(), VirtualKeyCode::Q => ctx.quitting = true, _ => {} } }
conditional_block
main.rs
use bracket_lib::prelude::*; enum GameMode { Menu, Playing, End, } struct Player { x: i32, y: i32, velocity: f32, } impl Player { fn new(x: i32, y: i32) -> Self { Player { x, y, velocity: 0.0, } } fn render(&mut self, ctx: &mut ...
(&mut self) { self.velocity = -2.0; } } struct State { player: Player, frame_time: f32, obstacle: Obstacle, mode: GameMode, } impl State { fn new() -> Self { State { player: Player::new(5, 25), frame_time: 0.0, obstacle: Obstacle::new(SCREEN_...
flap
identifier_name
main.rs
use bracket_lib::prelude::*; enum GameMode { Menu, Playing, End, } struct Player { x: i32, y: i32, velocity: f32, } impl Player { fn new(x: i32, y: i32) -> Self { Player { x, y, velocity: 0.0, } } fn render(&mut self, ctx: &mut ...
} struct State { player: Player, frame_time: f32, obstacle: Obstacle, mode: GameMode, } impl State { fn new() -> Self { State { player: Player::new(5, 25), frame_time: 0.0, obstacle: Obstacle::new(SCREEN_WIDTH, 0), mode: GameMode::Menu, ...
{ self.velocity = -2.0; }
identifier_body
mod.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub use alloc::arc::{Arc, Weak}; pub use core::atomic; pub use self::barrier::{Barrier, BarrierWaitResult}; pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT}; pub use self::mutex::MUTEX_INIT; pub use self::mutex::{Mutex, MutexGuard, StaticMutex}; pub use self::once::{Once, ONCE_INIT}; pub use sys_common::p...
//! and/or blocking at all, but rather provide the necessary tools to build //! other types of concurrent primitives. #![stable(feature = "rust1", since = "1.0.0")]
random_line_split
date_and_time.rs
use expression::{Expression, SelectableExpression}; use query_builder::{QueryBuilder, BuildQueryResult}; use types::{Timestamp, VarChar}; pub struct AtTimeZone<Ts, Tz> { timestamp: Ts, timezone: Tz, } impl<Ts, Tz> AtTimeZone<Ts, Tz> { pub fn new(timestamp: Ts, timezone: Tz) -> Self { AtTimeZone { ...
(&self, out: &mut QueryBuilder) -> BuildQueryResult { try!(self.timestamp.to_sql(out)); out.push_sql(" AT TIME ZONE "); self.timezone.to_sql(out) } } impl<Ts, Tz, Qs> SelectableExpression<Qs> for AtTimeZone<Ts, Tz> where AtTimeZone<Ts, Tz>: Expression, {}
to_sql
identifier_name
date_and_time.rs
use expression::{Expression, SelectableExpression}; use query_builder::{QueryBuilder, BuildQueryResult}; use types::{Timestamp, VarChar}; pub struct AtTimeZone<Ts, Tz> { timestamp: Ts, timezone: Tz, } impl<Ts, Tz> AtTimeZone<Ts, Tz> { pub fn new(timestamp: Ts, timezone: Tz) -> Self { AtTimeZone { ...
} impl<Ts, Tz, Qs> SelectableExpression<Qs> for AtTimeZone<Ts, Tz> where AtTimeZone<Ts, Tz>: Expression, {}
{ try!(self.timestamp.to_sql(out)); out.push_sql(" AT TIME ZONE "); self.timezone.to_sql(out) }
identifier_body
date_and_time.rs
use expression::{Expression, SelectableExpression}; use query_builder::{QueryBuilder, BuildQueryResult}; use types::{Timestamp, VarChar}; pub struct AtTimeZone<Ts, Tz> { timestamp: Ts, timezone: Tz, }
} } } impl<Ts, Tz> Expression for AtTimeZone<Ts, Tz> where Ts: Expression<SqlType=Timestamp>, Tz: Expression<SqlType=VarChar>, { // FIXME: This should be Timestamptz when we support that type type SqlType = Timestamp; fn to_sql(&self, out: &mut QueryBuilder) -> BuildQueryResult { ...
impl<Ts, Tz> AtTimeZone<Ts, Tz> { pub fn new(timestamp: Ts, timezone: Tz) -> Self { AtTimeZone { timestamp: timestamp, timezone: timezone,
random_line_split
mod.rs
extern crate portaudio; extern crate vorbis; pub use self::portaudio::PortAudio; mod file { use super::vorbis::*; use std::path::Path; use std::fs::File; use std::io::{Read, Seek}; pub const MUSIC_PATH: &'static str = "../../sound/music.ogg"; pub fn
(path: &Path) -> Decoder<File> { let file = File::open(path).unwrap(); Decoder::new(file).unwrap() } pub fn read_consolidated_packet<R: Read + Seek>(decoder: Decoder<R>) -> Option<Packet> { let mut iter = decoder.into_packets().map(|item| { item.unwrap() }); match iter.next() { ...
open_file
identifier_name
mod.rs
extern crate portaudio; extern crate vorbis; pub use self::portaudio::PortAudio; mod file { use super::vorbis::*;
use std::fs::File; use std::io::{Read, Seek}; pub const MUSIC_PATH: &'static str = "../../sound/music.ogg"; pub fn open_file(path: &Path) -> Decoder<File> { let file = File::open(path).unwrap(); Decoder::new(file).unwrap() } pub fn read_consolidated_packet<R: Read + Seek>(decode...
use std::path::Path;
random_line_split
mod.rs
extern crate portaudio; extern crate vorbis; pub use self::portaudio::PortAudio; mod file { use super::vorbis::*; use std::path::Path; use std::fs::File; use std::io::{Read, Seek}; pub const MUSIC_PATH: &'static str = "../../sound/music.ogg"; pub fn open_file(path: &Path) -> Decoder<File> { ...
else { try!(stream.start()); } self.stream = Some(stream); Ok(()) } else { use std::path::Path; let packet = file::read_consolidated_packet(file::open_file(Path::new(file::MUSIC_PATH))).unwrap(); let (data, out_settings, ch...
{ try!(stream.stop()); }
conditional_block
mod.rs
extern crate portaudio; extern crate vorbis; pub use self::portaudio::PortAudio; mod file { use super::vorbis::*; use std::path::Path; use std::fs::File; use std::io::{Read, Seek}; pub const MUSIC_PATH: &'static str = "../../sound/music.ogg"; pub fn open_file(path: &Path) -> Decoder<File> { ...
pub fn is_playing(&self) -> Result<bool, portaudio::Error> { if let Some(stream) = self.stream.as_ref() { stream.is_active() } else { Ok(false) } } }
{ if let Some(mut stream) = self.stream.take() { try!(stream.stop()); stream.close() } else { Ok(()) } }
identifier_body
rtio.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ /// Path to file to be opened pub path: Path, /// Flags for file access mode (as per open(2)) pub flags: int, /// File creation mode, ignored unless O_CREAT is passed as part of flags pub mode: int } /// Description of what to do when a file handle is closed pub enum CloseBehavior { /// ...
FileOpenConfig
identifier_name
rtio.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// option. This file may not be copied, modified, or distributed // except according to those terms. //! The EventLoop and internal synchronous I/O interface. use c_str::CString; use comm::{Sender, Receiver}; use kinds::Send; use libc::c_int; use libc; use mem; use ops::Drop; use option::{Option, Some, None}; use own...
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
next.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; 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::I...
// type Item = U::Item; // // #[inline] // fn next(&mut self) -> Option<U::Item> { // loop { // if let Some(ref mut inner) = self.frontiter { // if let Some(x) = inner.by_ref().next() { // return Some(x) // ...
// impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F> // where F: FnMut(I::Item) -> U, // {
random_line_split
next.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; 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::I...
}
{ let a: A<T> = A { begin: 0, end: 10 }; let f: F = F; let mut flat_map: FlatMap<A<T>, U, F> = a.flat_map::<U, F>(f); for n in 0 .. 10 { for i in 0..n { let x: Option<<U as IntoIterator>::Item> = flat_map.next(); match x { Some(v) => { assert_eq!(v, i); } None => { assert!(false); } } }...
identifier_body
next.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct
<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 self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } els...
A
identifier_name
next.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; 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::I...
None => { assert!(false); } } } } assert_eq!(flat_map.next(), None::<Item>); } }
{ assert_eq!(v, i); }
conditional_block
issue-5554.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ constants!(); }
identifier_body
issue-5554.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T> { a: T, } // reordering these bounds stops the ICE // // nmatsakis: This test used to have the bounds Default + PartialEq + // Default, but having duplicate bounds became illegal. impl<T: Default + PartialEq> Default for X<T> { fn default() -> X<T> { X { a: Default::default() } } } macro_rules...
X
identifier_name
issue-5554.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// Default, but having duplicate bounds became illegal. impl<T: Default + PartialEq> Default for X<T> { fn default() -> X<T> { X { a: Default::default() } } } macro_rules! constants { () => { let _ : X<isize> = Default::default(); } } pub fn main() { constants!(); }
// reordering these bounds stops the ICE // // nmatsakis: This test used to have the bounds Default + PartialEq +
random_line_split
values.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/. */ //! Helper types and traits for the handling of CSS values. use app_units::Au; use cssparser::{ParseError, Parser...
match *self { AllowedNumericType::All => true, AllowedNumericType::NonNegative => val >= 0.0, AllowedNumericType::AtLeastOne => val >= 1.0, } } /// Clamp the value following the rules of this numeric type. #[inline] ...
{ return true; }
conditional_block
values.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/. */ //! Helper types and traits for the handling of CSS values. use app_units::Au; use cssparser::{ParseError, Parser...
(&self, parsing_mode: ParsingMode, val: f32) -> bool { if parsing_mode.allows_all_numeric_values() { return true; } match *self { AllowedNumericType::All => true, AllowedNumericType::NonNegative => val >= 0.0, AllowedNum...
is_ok
identifier_name
values.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/. */ //! Helper types and traits for the handling of CSS values. use app_units::Au; use cssparser::{ParseError, Parser...
} impl ToCss for str { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { serialize_string(self, dest) } } impl ToCss for String { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { serialize_string(self, dest...
{ (*self).to_css(dest) }
identifier_body
values.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/. */ //! Helper types and traits for the handling of CSS values. use app_units::Au; use cssparser::{ParseError, Parser...
where W: Write, { (**self).to_css(dest) } } impl<T> ToCss for Arc<T> where T:?Sized + ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { (**self).to_css(dest) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut CssWriter<W>)...
} } impl<T> ToCss for Box<T> where T: ?Sized + ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
random_line_split
help.rs
use super::{cd, ls, echo}; pub fn
(args: Vec<String>) { if args.len() > 0 { match args[0].as_ref() { "cd" => cd::help(), "ls" => ls::help(), "echo" => echo::help(), _ => println!("Command not found") } } else { println!(" I wrote this program to learn Rust.\n\n use help...
exec
identifier_name
help.rs
use super::{cd, ls, echo}; pub fn exec(args: Vec<String>)
Anything that's not an option, is a parameter\n\n Complex things like pipes are not implemented.\n Commands:\n cd, ls, pwd\n"); } }
{ if args.len() > 0 { match args[0].as_ref() { "cd" => cd::help(), "ls" => ls::help(), "echo" => echo::help(), _ => println!("Command not found") } } else { println!(" I wrote this program to learn Rust.\n\n use help <command> for info ...
identifier_body
help.rs
use super::{cd, ls, echo}; pub fn exec(args: Vec<String>) { if args.len() > 0 { match args[0].as_ref() { "cd" => cd::help(), "ls" => ls::help(), "echo" => echo::help(), _ => println!("Command not found") } } else { println!(" I wrote th...
Commands:\n cd, ls, pwd\n"); } }
Parameters:\n Anything that's not an option, is a parameter\n\n Complex things like pipes are not implemented.\n
random_line_split
animation.rs
use crate::ipc_protocol::{ServerOneshotSender, ServerResponse, RotationDirection}; use crate::radians::Radians; use crate::{Distance, Point}; use super::HandlerError; use super::super::{ event_loop_notifier::EventLoopNotifier, state::TurtleState, app::{TurtleId, App}, animation::{MoveAnimation, RotateA...
Ok(()) } pub(crate) fn rotate_in_place( conn: ServerOneshotSender, app: &mut App, event_loop: &EventLoopNotifier, anim_runner: &AnimationRunner, id: TurtleId, angle: Radians, direction: RotationDirection, ) -> Result<(), HandlerError> { let turtle = app.turtle_mut(id); let an...
{ // Instant animations complete right away and don't need to be queued // Signal the main thread that the image has changed event_loop.request_redraw()?; conn.send(ServerResponse::AnimationComplete(id))?; }
conditional_block
animation.rs
use crate::ipc_protocol::{ServerOneshotSender, ServerResponse, RotationDirection}; use crate::radians::Radians; use crate::{Distance, Point}; use super::HandlerError; use super::super::{ event_loop_notifier::EventLoopNotifier, state::TurtleState, app::{TurtleId, App}, animation::{MoveAnimation, RotateA...
event_loop.request_redraw()?; conn.send(ServerResponse::AnimationComplete(id))?; } Ok(()) } pub(crate) fn rotate_in_place( conn: ServerOneshotSender, app: &mut App, event_loop: &EventLoopNotifier, anim_runner: &AnimationRunner, id: TurtleId, angle: Radians, directi...
// Instant animations complete right away and don't need to be queued // Signal the main thread that the image has changed
random_line_split
animation.rs
use crate::ipc_protocol::{ServerOneshotSender, ServerResponse, RotationDirection}; use crate::radians::Radians; use crate::{Distance, Point}; use super::HandlerError; use super::super::{ event_loop_notifier::EventLoopNotifier, state::TurtleState, app::{TurtleId, App}, animation::{MoveAnimation, RotateA...
( conn: ServerOneshotSender, app: &mut App, display_list: &mut DisplayList, event_loop: &EventLoopNotifier, anim_runner: &AnimationRunner, id: TurtleId, distance: Distance, ) -> Result<(), HandlerError> { let turtle = app.turtle_mut(id); let TurtleState {position, heading,..} = turt...
move_forward
identifier_name
animation.rs
use crate::ipc_protocol::{ServerOneshotSender, ServerResponse, RotationDirection}; use crate::radians::Radians; use crate::{Distance, Point}; use super::HandlerError; use super::super::{ event_loop_notifier::EventLoopNotifier, state::TurtleState, app::{TurtleId, App}, animation::{MoveAnimation, RotateA...
pub(crate) fn rotate_in_place( conn: ServerOneshotSender, app: &mut App, event_loop: &EventLoopNotifier, anim_runner: &AnimationRunner, id: TurtleId, angle: Radians, direction: RotationDirection, ) -> Result<(), HandlerError> { let turtle = app.turtle_mut(id); let anim = RotateAni...
{ let turtle = app.turtle_mut(id); let anim = MoveAnimation::new(turtle, display_list, target_pos); if anim.is_running() { anim_runner.play(id, anim, conn.client_id()); } else { // Instant animations complete right away and don't need to be queued // Signal the main thread tha...
identifier_body
statistics.rs
/* Copyright 2013 Leon Sixt * * 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 wr...
} } fn leafs(&self) -> uint { self.leafs.load(Relaxed) } fn inc_leafs(&self) { unsafe { cast::transmute_mut(&self.leafs).fetch_add(1, Relaxed); } } fn dec_leafs(&self){ unsafe { cast::transmute_mut(&self.leafs).fetch_sub(1, Relaxed...
unsafe { cast::transmute_mut(&self.inodes).fetch_sub(1, Relaxed);
random_line_split
statistics.rs
/* Copyright 2013 Leon Sixt * * 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 wr...
fn inc_elements(&self){ unsafe { cast::transmute_mut(&self.elements).fetch_add(1, Relaxed); } } fn dec_elements(&self){ unsafe { cast::transmute_mut(&self.elements).fetch_sub(1, Relaxed); } } fn insertions(&self) -> uint { self.inserti...
{ self.elements.load(Relaxed) }
identifier_body
statistics.rs
/* Copyright 2013 Leon Sixt * * 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 wr...
(&self) { unsafe { cast::transmute_mut(&self.insertions).fetch_add(1, Relaxed); } } fn deletions(&self) -> uint { self.deletions.load(Relaxed) } fn inc_deletions(&self) { unsafe { cast::transmute_mut(&self.deletions).fetch_add(1, Relaxed); ...
inc_insertions
identifier_name
main.rs
#[derive(Debug)] struct Item { name: String, price: usize, damage: usize, armor: usize, } impl Item { fn
(name: &str, price: usize, damage: usize, armor: usize) -> Item { Item { name: name.to_string(), price: price, damage: damage, armor: armor } } } fn players_wins(inventory: &[&Item]) -> bool { let enemy_hit_points = 109; let enemy_damage = 8; let enemy_armor = 2; let player_hit_points = 10...
new
identifier_name
main.rs
#[derive(Debug)] struct Item { name: String, price: usize, damage: usize, armor: usize, } impl Item { fn new(name: &str, price: usize, damage: usize, armor: usize) -> Item { Item { name: name.to_string(), price: price, damage: damage, armor: armor } } } fn players_wins(inventory: &[&It...
println!("Smallest amount to win: {}", min_price); println!("Biggest amount to lose: {}", max_price); }
} }
random_line_split
main.rs
#[derive(Debug)] struct Item { name: String, price: usize, damage: usize, armor: usize, } impl Item { fn new(name: &str, price: usize, damage: usize, armor: usize) -> Item { Item { name: name.to_string(), price: price, damage: damage, armor: armor } } } fn players_wins(inventory: &[&It...
; let rounds_for_player_to_win = 1 + (enemy_hit_points - 1) / actual_player_damage; let rounds_for_enemy_to_win = 1 + (player_hit_points - 1) / actual_enemy_damage; rounds_for_player_to_win <= rounds_for_enemy_to_win } fn total_price(inventory: &[&Item]) -> usize { inventory.iter().map(|item| item.pr...
{ 1 }
conditional_block
main.rs
#[derive(Debug)] struct Item { name: String, price: usize, damage: usize, armor: usize, } impl Item { fn new(name: &str, price: usize, damage: usize, armor: usize) -> Item
} fn players_wins(inventory: &[&Item]) -> bool { let enemy_hit_points = 109; let enemy_damage = 8; let enemy_armor = 2; let player_hit_points = 100; let player_damage = inventory.iter().map(|item| item.damage).fold(0, |acc, x| acc + x); let player_armor = inventory.iter().map(|item| item.armo...
{ Item { name: name.to_string(), price: price, damage: damage, armor: armor } }
identifier_body
htmlframeelement.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::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrame...
<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
reflector
identifier_name
htmlframeelement.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::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrame...
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFrameElementTypeId)) } } impl HTMLFrameElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLFrameElement { HTMLFrameElement { htmlelement: HTMLElement::new_inherited(HTMLFrameElementTypeId, loc...
impl HTMLFrameElementDerived for EventTarget { fn is_htmlframeelement(&self) -> bool {
random_line_split
htmlframeelement.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::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrame...
} impl HTMLFrameElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLFrameElement { HTMLFrameElement { htmlelement: HTMLElement::new_inherited(HTMLFrameElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JSRef<...
{ self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFrameElementTypeId)) }
identifier_body
rocksdb_engine.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt::{self, Debug, Display, Formatter}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use engine_rocks::file_system::get_env as get_inspected_env; use engine_rocks::raw::DBOptions; use en...
/// /// This is intended for **testing use only**. #[derive(Clone)] pub struct RocksEngine { core: Arc<Mutex<RocksEngineCore>>, sched: Scheduler<Task>, engines: Engines<BaseRocksEngine, BaseRocksEngine>, not_leader: Arc<AtomicBool>, } impl RocksEngine { pub fn new( path: &str, cfs: ...
} } /// The RocksEngine is based on `RocksDB`.
random_line_split
rocksdb_engine.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt::{self, Debug, Display, Formatter}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use engine_rocks::file_system::get_env as get_inspected_env; use engine_rocks::raw::DBOptions; use en...
fn async_write_ext( &self, _: &Context, batch: WriteData, cb: Callback<()>, proposed_cb: Option<ExtCallback>, committed_cb: Option<ExtCallback>, ) -> Result<()> { fail_point!("rockskv_async_write", |_| Err(box_err!("write failed"))); if batch.mo...
{ self.async_write_ext(ctx, batch, cb, None, None) }
identifier_body
rocksdb_engine.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt::{self, Debug, Display, Formatter}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use engine_rocks::file_system::get_env as get_inspected_env; use engine_rocks::raw::DBOptions; use en...
(&mut self, t: Task) { match t { Task::Write(modifies, cb) => { cb((CbContext::new(), write_modifies(&self.0.kv, modifies))) } Task::Snapshot(cb) => cb((CbContext::new(), Ok(Arc::new(self.0.kv.snapshot())))), Task::Pause(dur) => std::thread::sleep(...
run
identifier_name
error.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // 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) any // later version. // Th...
{ /// Code pub code: ErrorCode, /// Message pub message: String, /// Optional data #[serde(skip_serializing_if = "Option::is_none")] pub data: Option<Value>, } impl Error { /// Wraps given `ErrorCode` pub fn new(code: ErrorCode) -> Self { Error { message: code.d...
Error
identifier_name
error.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // 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) any // later version. // Th...
/// JSONRPC error code #[derive(Debug, PartialEq, Clone)] pub enum ErrorCode { /// Invalid JSON was received by the server. /// An error occurred on the server while parsing the JSON text. ParseError, /// The JSON sent is not a valid Request object. InvalidRequest, /// The method does not exist ...
random_line_split
profile.rs
//! # profile //! //! Profile related utility functions //! #[cfg(test)] #[path = "profile_test.rs"] mod profile_test; use envmnt; static PROFILE_ENV_KEY: &str = "CARGO_MAKE_PROFILE"; static ADDITIONAL_PROFILES_ENV_KEY: &str = "CARGO_MAKE_ADDITIONAL_PROFILES"; pub(crate) static DEFAULT_PROFILE: &str = "development";...
envmnt::get_or(PROFILE_ENV_KEY, DEFAULT_PROFILE) } pub(crate) fn set(profile: &str) -> String { let mut profile_normalized = normalize_profile(&profile); if profile_normalized.len() == 0 { profile_normalized = DEFAULT_PROFILE.to_string(); } envmnt::set(PROFILE_ENV_KEY, &profile_normalized...
random_line_split
profile.rs
//! # profile //! //! Profile related utility functions //! #[cfg(test)] #[path = "profile_test.rs"] mod profile_test; use envmnt; static PROFILE_ENV_KEY: &str = "CARGO_MAKE_PROFILE"; static ADDITIONAL_PROFILES_ENV_KEY: &str = "CARGO_MAKE_ADDITIONAL_PROFILES"; pub(crate) static DEFAULT_PROFILE: &str = "development";...
envmnt::set(PROFILE_ENV_KEY, &profile_normalized); get() } pub(crate) fn set_additional(profiles: &Vec<String>) { let nomralized_profiles = normalize_additional_profiles(&profiles); envmnt::set_list(ADDITIONAL_PROFILES_ENV_KEY, &nomralized_profiles); }
{ profile_normalized = DEFAULT_PROFILE.to_string(); }
conditional_block
profile.rs
//! # profile //! //! Profile related utility functions //! #[cfg(test)] #[path = "profile_test.rs"] mod profile_test; use envmnt; static PROFILE_ENV_KEY: &str = "CARGO_MAKE_PROFILE"; static ADDITIONAL_PROFILES_ENV_KEY: &str = "CARGO_MAKE_ADDITIONAL_PROFILES"; pub(crate) static DEFAULT_PROFILE: &str = "development";...
(profile: &str) -> String { let mut profile_normalized = normalize_profile(&profile); if profile_normalized.len() == 0 { profile_normalized = DEFAULT_PROFILE.to_string(); } envmnt::set(PROFILE_ENV_KEY, &profile_normalized); get() } pub(crate) fn set_additional(profiles: &Vec<String>) { ...
set
identifier_name
profile.rs
//! # profile //! //! Profile related utility functions //! #[cfg(test)] #[path = "profile_test.rs"] mod profile_test; use envmnt; static PROFILE_ENV_KEY: &str = "CARGO_MAKE_PROFILE"; static ADDITIONAL_PROFILES_ENV_KEY: &str = "CARGO_MAKE_ADDITIONAL_PROFILES"; pub(crate) static DEFAULT_PROFILE: &str = "development";...
{ let nomralized_profiles = normalize_additional_profiles(&profiles); envmnt::set_list(ADDITIONAL_PROFILES_ENV_KEY, &nomralized_profiles); }
identifier_body
p_1_2_3_04.rs
// P_1_2_3_04 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung....
color_count: usize, hue_values: Vec<f32>, saturation_values: Vec<f32>, brightness_values: Vec<f32>, alpha_value: f32, act_random_seed: u64, clicked: bool, clicked_frame: u64, } fn model(app: &App) -> Model { let _window = app .new_window() .size(1280, 720) .view...
el {
identifier_name
p_1_2_3_04.rs
// P_1_2_3_04 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung....
// how many fragments let mut part_count = i + 1; let mut parts = Vec::new(); for _ in 0..part_count { // sub fragment of not? if rng.gen::<f32>() < 0.075 { // take care of big values let fragments =...
let row_count = rng.gen_range(5, 30); let row_height = (app.window_rect().h() as i32 / row_count) as i32; // seperate each line in parts for i in (0..=row_count).rev() {
random_line_split
p_1_2_3_04.rs
// P_1_2_3_04 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung....
app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } }
conditional_block
lib.rs
// Copyright 2014 Colin Sherratt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
input::WindowEvent::Position(x, y) => { self.position = (x, y); } input::WindowEvent::MouseOver(mouse) => { self.mouse_over = mouse; } } } } pub trait GetIoState { /// Apply an `WindowEvent` to the system, this will update...
{ self.size = (x, y); }
conditional_block
lib.rs
// Copyright 2014 Colin Sherratt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
(glfw :&mut Glfw, width: u32, height: u32, name: &str, mode: glfw::WindowMode) -> Option<(glfw::Window, Receiver<(f64, glfw::WindowEvent)>)> { nice_glfw::WindowBuilder::new(glfw) .try_modern_context_hints() .size(width, height) .title(name) .mode(mode) .create() } impl I...
create_window_context
identifier_name
lib.rs
// Copyright 2014 Colin Sherratt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
pub fn set_window_position(&mut self, window: &Window, pos: (i32, i32)) { let (w, h) = pos; match self.windows.get_mut(&window.handle.handle) { Some(win) => win.window.set_pos(w, h), None => () } } pub fn get_framebuffer_size(&mut self, window: &Window) -> ...
{ if self.ovr.is_some() && self.ovr.as_ref().unwrap().detect() > 0 { return true; } if self.ovr.is_none() { self.ovr = ovr::Ovr::init(); } self.ovr.is_some() && self.ovr.as_ref().unwrap().detect() > 0 }
identifier_body
lib.rs
// Copyright 2014 Colin Sherratt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
return Some((window, events)); } None }) } pub fn hmd(&mut self) -> Option<Window> { if!self.setup_ovr() { return None; } let (window, events, rc, hmd) = { let hmd = match self.ovr.as_ref().unwrap().first_hmd() { ...
Some((window, events)) => (window, events), None => return None };
random_line_split
synth.rs
use std::i16; use std::mem; pub trait Generator { fn amp(&self, t: f64) -> f64; fn map<'r>(self, f: |f64|:'static -> f64) -> MappedGenerator<Self> { MappedGenerator { g: self, f: f } } } pub struct MappedGenerator<G> { g: G, f: |f64|:'static -> f64 } impl<'r, G: Generator> Generator for MappedGenerato...
{ notes: Vec<Note> } impl Melody { pub fn new(notes: Vec<Note>) -> Melody { Melody { notes: notes } } pub fn duration(&self) -> f64 { self.notes.iter().fold(0.0, |a, &Note(_,d)| { a + d }) } } impl ::Generator for Melody { fn amp(&self, t: f64) -> f64 { let mut a = ...
Melody
identifier_name
synth.rs
use std::i16; use std::mem; pub trait Generator { fn amp(&self, t: f64) -> f64; fn map<'r>(self, f: |f64|:'static -> f64) -> MappedGenerator<Self> { MappedGenerator { g: self, f: f } } } pub struct MappedGenerator<G> { g: G, f: |f64|:'static -> f64 } impl<'r, G: Generator> Generator for MappedGenerato...
(generator.amp(t) * (i16::MAX - 1) as f64) as i16 }) }
random_line_split
synth.rs
use std::i16; use std::mem; pub trait Generator { fn amp(&self, t: f64) -> f64; fn map<'r>(self, f: |f64|:'static -> f64) -> MappedGenerator<Self>
} pub struct MappedGenerator<G> { g: G, f: |f64|:'static -> f64 } impl<'r, G: Generator> Generator for MappedGenerator<G> { fn amp(&self, t: f64) -> f64 { let f: &mut |f64|:'static -> f64 = unsafe { mem::transmute(&self.f) }; (*f)(self.g.amp(t)) } } pub mod waves { use std::f64::consts::PI; pub...
{ MappedGenerator { g: self, f: f } }
identifier_body
performance_timeline.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/. */ // XXX The spec says that the performance timeline task source should be // a low priority task and it should ...
} impl TaskSource for PerformanceTimelineTaskSource { fn queue_with_canceller<T>( &self, task: T, canceller: &TaskCanceller, ) -> Result<(), ()> where T: TaskOnce +'static, { let msg = CommonScriptMsg::Task( ScriptThreadEventCategory::PerformanceTime...
{ write!(f, "PerformanceTimelineTaskSource(...)") }
identifier_body
performance_timeline.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/. */ // XXX The spec says that the performance timeline task source should be // a low priority task and it should ...
(&self) -> PerformanceTimelineTaskSource { PerformanceTimelineTaskSource(self.0.clone()) } } impl fmt::Debug for PerformanceTimelineTaskSource { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "PerformanceTimelineTaskSource(...)") } } impl TaskSource for PerformanceTimelin...
clone
identifier_name
performance_timeline.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/. */ // XXX The spec says that the performance timeline task source should be // a low priority task and it should ...
{ let msg = CommonScriptMsg::Task( ScriptThreadEventCategory::PerformanceTimelineTask, Box::new(canceller.wrap_task(task)) ); self.0.send(msg).map_err(|_| ()) } } impl PerformanceTimelineTaskSource { pub fn queue_notification(&self, global: &GlobalScope) { ...
random_line_split
core.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use fnv::FnvHasher; use std::ops::Deref; use std::sync::Arc; use std::{fmt, hash}; use crate::externs; use crate::handles::Handle; use smallvec::{smallvec, SmallVec}; pub type FNV = ...
(pub Key); impl Function { fn pretty_print(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Function(key) = self; let name = externs::project_str(&externs::val_for(&key), "__name__"); write!(f, "{}()", name) } } impl fmt::Display for Function { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt...
Function
identifier_name
core.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use fnv::FnvHasher; use std::ops::Deref; use std::sync::Arc; use std::{fmt, hash}; use crate::externs; use crate::handles::Handle; use smallvec::{smallvec, SmallVec}; pub type FNV = ...
fn binary_search(&self, type_id: TypeId) -> Result<usize, usize> { self .0 .binary_search_by(|probe| probe.type_id().cmp(&type_id)) } pub fn type_ids<'a>(&'a self) -> impl Iterator<Item = TypeId> + 'a { self.0.iter().map(|k| *k.type_id()) } /// /// Given a set of either param type or pa...
pub fn find(&self, type_id: TypeId) -> Option<&Key> { self.binary_search(type_id).ok().map(|idx| &self.0[idx]) }
random_line_split
core.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use fnv::FnvHasher; use std::ops::Deref; use std::sync::Arc; use std::{fmt, hash}; use crate::externs; use crate::handles::Handle; use smallvec::{smallvec, SmallVec}; pub type FNV = ...
} impl Deref for Value { type Target = Handle; fn deref(&self) -> &Handle { &self.0 } } impl fmt::Debug for Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::val_to_str(&self)) } } /// /// Creates a Handle (which represents exclusive access) from a Value ...
{ Value(Arc::new(handle)) }
identifier_body
mod.rs
use std::collections::BTreeMap; use std::error; use std::fmt; use std::mem; use {Value, Table}; #[cfg(feature = "rustc-serialize")] mod rustc_serialize; #[cfg(feature = "serde")] mod serde; /// A structure to transform Rust values into TOML values. /// /// This encoder implements the serialization `Encoder` interfac...
<T: ::serde::Serialize>(t: &T) -> Value { let mut e = Encoder::new(); t.serialize(&mut e).unwrap(); Value::Table(e.toml) } /// Encodes an encodable value into a TOML string. /// /// This function expects the type given to represent a TOML table in some form. /// If encoding encounters an error, then this f...
encode
identifier_name
mod.rs
use std::collections::BTreeMap; use std::error; use std::fmt; use std::mem; use {Value, Table}; #[cfg(feature = "rustc-serialize")] mod rustc_serialize; #[cfg(feature = "serde")] mod serde; /// A structure to transform Rust values into TOML values. /// /// This encoder implements the serialization `Encoder` interfac...
/// If encoding encounters an error, then this function will fail the task. #[cfg(feature = "rustc-serialize")] pub fn encode<T: ::rustc_serialize::Encodable>(t: &T) -> Value { let mut e = Encoder::new(); t.encode(&mut e).unwrap(); Value::Table(e.toml) } /// Encodes an encodable value into a TOML value. //...
/// /// This function expects the type given to represent a TOML table in some form.
random_line_split
mod.rs
use std::collections::BTreeMap; use std::error; use std::fmt; use std::mem; use {Value, Table}; #[cfg(feature = "rustc-serialize")] mod rustc_serialize; #[cfg(feature = "serde")] mod serde; /// A structure to transform Rust values into TOML values. /// /// This encoder implements the serialization `Encoder` interfac...
State::Start => f(self), State::NextMapKey => Err(Error::InvalidMapKeyLocation), } } fn table_key<F>(&mut self, f: F) -> Result<(), Error> where F: FnOnce(&mut Encoder) -> Result<(), Error> { match mem::replace(&mut self.state, State::NextMapKey) { ...
{ let mut nested = Encoder::new(); try!(f(&mut nested)); arr.push(Value::Table(nested.toml)); self.state = State::NextArray(arr); Ok(()) }
conditional_block
mod.rs
use std::collections::BTreeMap; use std::error; use std::fmt; use std::mem; use {Value, Table}; #[cfg(feature = "rustc-serialize")] mod rustc_serialize; #[cfg(feature = "serde")] mod serde; /// A structure to transform Rust values into TOML values. /// /// This encoder implements the serialization `Encoder` interfac...
}
{ "TOML encoding error" }
identifier_body
lib.rs
use std::collections::{HashMap, /* VecMap,*/ BTreeMap}; use std::hash::Hash; use std::iter::FromIterator; /// Conversion from an `Iterator` of pairs. pub trait Groupable<K, V> { /// Loops through the entire iterator, grouping all keys into a container /// implementing `FromKeyedIterator` with a container of v...
<B: FromKeyedIterator<K, V>>(&mut self) -> B { FromKeyedIterator::from_keyed_iter(self.by_ref()) } } /// Conversion from an `Iterator` of key-value pairs. pub trait FromKeyedIterator<K, V> { /// Build a container with groups of elements from an external iterator. fn from_keyed_iter<I: Iterator<Item...
group
identifier_name
lib.rs
use std::collections::{HashMap, /* VecMap,*/ BTreeMap}; use std::hash::Hash; use std::iter::FromIterator; /// Conversion from an `Iterator` of pairs. pub trait Groupable<K, V> { /// Loops through the entire iterator, grouping all keys into a container /// implementing `FromKeyedIterator` with a container of v...
/// /// ```rust /// use std::collections::HashMap; /// use groupable::Groupable; /// /// let evens = (0..10).map(|i| (i % 2 == 0, i)) /// .group::<HashMap<bool, Vec<usize>>>(); /// /// assert_eq!(evens[&true], [0, 2, 4, 6, 8]); /// assert_eq!(evens[&false], [1, ...
/// The values will be aggregated per key into a container implementing /// `Extend` for the value type. /// /// # Example
random_line_split
lib.rs
use std::collections::{HashMap, /* VecMap,*/ BTreeMap}; use std::hash::Hash; use std::iter::FromIterator; /// Conversion from an `Iterator` of pairs. pub trait Groupable<K, V> { /// Loops through the entire iterator, grouping all keys into a container /// implementing `FromKeyedIterator` with a container of v...
} /// Conversion from an `Iterator` of key-value pairs. pub trait FromKeyedIterator<K, V> { /// Build a container with groups of elements from an external iterator. fn from_keyed_iter<I: Iterator<Item=(K, V)>>(I) -> Self; } macro_rules! group_into( ($iter:ident, $map:ident) => ( for (key, val) in...
{ FromKeyedIterator::from_keyed_iter(self.by_ref()) }
identifier_body
function_def.rs
// http://rosettacode.org/wiki/Function_definition use std::ops::Mul; // Function taking 2 ints, multply them and return the value fn multiply(x: i32, y: i32) -> i32 { // In Rust a statement is a expression. An expression at the end of a // function without semicolon is a return expression x * y //equivalent "r...
fn test_multiply_gen() { assert_eq!(multiply_gen(2i32,2), 4); } #[test] fn test_multiply() { assert_eq!(multiply(2i32,2), 4); } #[cfg(not(test))] fn main() { println!("2 multiply 4 = {}", multiply(2i32,4)); println!("2.0 multiply 4.0 = {}", multiply_gen(2.0f32, 4.0)); println!("5.0 multiply 7.0 is {}", mult...
random_line_split
function_def.rs
// http://rosettacode.org/wiki/Function_definition use std::ops::Mul; // Function taking 2 ints, multply them and return the value fn multiply(x: i32, y: i32) -> i32 { // In Rust a statement is a expression. An expression at the end of a // function without semicolon is a return expression x * y //equivalent "r...
() { assert_eq!(multiply(2i32,2), 4); } #[cfg(not(test))] fn main() { println!("2 multiply 4 = {}", multiply(2i32,4)); println!("2.0 multiply 4.0 = {}", multiply_gen(2.0f32, 4.0)); println!("5.0 multiply 7.0 is {}", multiply_gen(5.0 as f32, 7.0 as f32)); }
test_multiply
identifier_name
function_def.rs
// http://rosettacode.org/wiki/Function_definition use std::ops::Mul; // Function taking 2 ints, multply them and return the value fn multiply(x: i32, y: i32) -> i32 { // In Rust a statement is a expression. An expression at the end of a // function without semicolon is a return expression x * y //equivalent "r...
#[cfg(not(test))] fn main() { println!("2 multiply 4 = {}", multiply(2i32,4)); println!("2.0 multiply 4.0 = {}", multiply_gen(2.0f32, 4.0)); println!("5.0 multiply 7.0 is {}", multiply_gen(5.0 as f32, 7.0 as f32)); }
{ assert_eq!(multiply(2i32,2), 4); }
identifier_body
transact.rs
//! Implementation of reversible insertions on maps and sets. //! //! These utility data structures are useful when several hashmaps/hashsets need to be kept //! synchronized. For instance, maps a data structure needs to be added to maps `a`, `b`, `c` //! but the entire operation needs to be cancelled if there is a col...
Entry::Vacant(entry) => { entry.insert(v); keys.push(k) } } } match conflict { None => Ok(InsertInMap { map: map, keys: keys, commit...
match map.entry(k.clone()) { Entry::Occupied(_) => { conflict = Some(k); break; },
random_line_split
transact.rs
//! Implementation of reversible insertions on maps and sets. //! //! These utility data structures are useful when several hashmaps/hashsets need to be kept //! synchronized. For instance, maps a data structure needs to be added to maps `a`, `b`, `c` //! but the entire operation needs to be cancelled if there is a col...
} } /// Commit the transaction. Once this is done, the value may be dropped without cancelling /// the insertion. pub fn commit(mut self) { self.committed = true } } impl<'a, K, V> Drop for InsertInMap<'a, K, V> where K:'a + Clone + Hash + Eq, V: 'a { /// If this object is dro...
{ // We need to rollback everything we have inserted so far. for k in keys { map.remove(&k); } Err(k) }
conditional_block
transact.rs
//! Implementation of reversible insertions on maps and sets. //! //! These utility data structures are useful when several hashmaps/hashsets need to be kept //! synchronized. For instance, maps a data structure needs to be added to maps `a`, `b`, `c` //! but the entire operation needs to be cancelled if there is a col...
{ InsertInMap::start(&mut map, vec![(6, 6), (7, 7), (8, 8)]).unwrap(); // Transaction is not committed. assert_eq!(map, reference_map); } println!("Inserting and committing"); { { let transaction = InsertInMap::start(&mut map, vec![(6, 6), (7, 7), (8, 8)]).un...
{ println!("Initializing a map"); let mut map = HashMap::new(); for i in 1..6 { map.insert(i, i); } let reference_map = map.clone(); println!("Failing to insert due to collision"); { if let Err(i) = InsertInMap::start(&mut map, vec![(6, 6), (7, 7), (8, 8), (4, 10)]) { ...
identifier_body
transact.rs
//! Implementation of reversible insertions on maps and sets. //! //! These utility data structures are useful when several hashmaps/hashsets need to be kept //! synchronized. For instance, maps a data structure needs to be added to maps `a`, `b`, `c` //! but the entire operation needs to be cancelled if there is a col...
<'a, K, V> where K: 'a + Clone + Hash + Eq, V: 'a { map: &'a mut HashMap<K, V>, committed: bool, keys: Vec<K>, } impl<'a, K, V> InsertInMap<'a, K, V> where K:'a + Clone + Hash + Eq, V: 'a { /// Insert (key, value) pairs in a map, reversibly, and without overwriting. /// /// If one of the keys `k...
InsertInMap
identifier_name
mod.rs
// Copyright 2012-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-MI...
//- #[cfg(target_os = "fuchsia")] pub mod fuchsia; //- //- #[cfg(any(target_os = "redox", unix))] //- #[stable(feature = "rust1", since = "1.0.0")] //- pub use sys::ext as unix; //- //- #[cfg(windows)] //- #[stable(feature = "rust1", since = "1.0.0")] //- pub u...
//- #[cfg(target_os = "emscripten")] pub mod emscripten;
random_line_split
mod.rs
/*! In order to draw, you need to provide a source of indices which is used to link the vertices together into *primitives*. There are eleven types of primitives, each one with a corresponding struct: - `PointsList` - `LinesList` - `LinesListAdjacency` - `LineStrip` - `LineStripAdjacency` - `TrianglesList` - `...
} /// List of available primitives. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PrimitiveType { /// Points, /// LinesList, /// LinesListAdjacency, /// LineStrip, /// LineStripAdjacency, /// TrianglesList, /// TrianglesListAdjacency, /// Triangl...
{ match self { &IndicesSource::IndexBuffer { ref buffer, .. } => buffer.get_primitives_type(), &IndicesSource::Buffer { primitives, .. } => primitives, &IndicesSource::NoIndices { primitives } => primitives, } }
identifier_body
mod.rs
/*! In order to draw, you need to provide a source of indices which is used to link the vertices together into *primitives*. There are eleven types of primitives, each one with a corresponding struct: - `PointsList` - `LinesList` - `LinesListAdjacency` - `LineStrip` - `LineStripAdjacency` - `TrianglesList` - `...
/// Don't use indices. Assemble primitives by using the order in which the vertices are in /// the vertices source. NoIndices { /// Type of primitives contained in the vertex source. primitives: PrimitiveType, }, } impl<'a, T> IndicesSource<'a, T> where T: Index { /// Returns the ty...
/// Number of elements in the buffer to use. length: usize, },
random_line_split
mod.rs
/*! In order to draw, you need to provide a source of indices which is used to link the vertices together into *primitives*. There are eleven types of primitives, each one with a corresponding struct: - `PointsList` - `LinesList` - `LinesListAdjacency` - `LineStrip` - `LineStripAdjacency` - `TrianglesList` - `...
(&self) -> gl::types::GLenum { *self as gl::types::GLenum } } /// An index from the index buffer. pub unsafe trait Index: Copy + Send +'static { /// Returns the `IndexType` corresponding to this type. fn get_type() -> IndexType; } unsafe impl Index for u8 { fn get_type() -> IndexType { ...
to_glenum
identifier_name
main.rs
extern crate rusoto_core; extern crate rusoto_rds; use std::{thread, time}; use rusoto_rds::{Rds, RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage}; use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client}; fn
() { let database_instance_name = "rusototester2"; let credentials = DefaultCredentialsProvider::new().expect("Couldn't create AWS credentials provider."); // Security groups in the default VPC will need modification to let you access this from the internet: let rds_client = RdsClient::new(default_tls...
main
identifier_name
main.rs
extern crate rusoto_core; extern crate rusoto_rds; use std::{thread, time}; use rusoto_rds::{Rds, RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage}; use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client}; fn main()
}; println!("Going to make the database instance."); let db_call_result = rds_client.create_db_instance(&create_db_instance_request); if db_call_result.is_err() { // This `unwrap` on the `err()` call will show us the error we know is there: println!("Didn't successfully make the DB inst...
{ let database_instance_name = "rusototester2"; let credentials = DefaultCredentialsProvider::new().expect("Couldn't create AWS credentials provider."); // Security groups in the default VPC will need modification to let you access this from the internet: let rds_client = RdsClient::new(default_tls_cl...
identifier_body
main.rs
extern crate rusoto_core; extern crate rusoto_rds; use std::{thread, time}; use rusoto_rds::{Rds, RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage}; use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client}; fn main() { let database_instance_name = "rusototester2"; let credentia...
, }; } let endpoint_address = endpoint.address.expect("Endpoint address not available"); let endpoint_port = endpoint.port.expect("Endpoint port not available"); println!("\n\nendpoint: {:?}", format!("{}:{}", endpoint_address, endpoint_port)); }
{ println!("Waiting for db to be available..."); thread::sleep(ten_seconds); continue; }
conditional_block