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
simd-generics.rs
// 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(simd)] use std::ops; #[simd] struct f32x4(f32, f32, f32, f32); fn add<T: ...
// Copyright 2013-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
random_line_split
simd-generics.rs
// Copyright 2013-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...
<T: ops::Add<T, T>>(lhs: T, rhs: T) -> T { lhs + rhs } impl ops::Add<f32x4, f32x4> for f32x4 { fn add(&self, rhs: &f32x4) -> f32x4 { *self + *rhs } } pub fn main() { let lr = f32x4(1.0f32, 2.0f32, 3.0f32, 4.0f32); // lame-o let f32x4(x, y, z, w) = add(lr, lr); assert_eq!(x, 2.0f32...
add
identifier_name
pointing.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_...
<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<computed_value::Image, ParseError<'i>> { Ok(computed_value::Image { url: SpecifiedUrl::parse(context, input)?, hotspot: match input.try(|input| input.expect_number()) { Ok(n...
parse_image
identifier_name
pointing.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_...
</%helpers:longhand> // NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact) // is nonstandard, slated for CSS4-UI. // TODO(pcwalton): SVG-only values. ${helpers.single_keyword("pointer-events", "auto none", animation_value_type="discrete", extra_gecko_v...
random_line_split
issue-1655.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
)]
random_line_split
capture.rs
use std::fmt; use std::mem; use std::os::raw::c_void; use std::path::{Path, PathBuf}; use {trace, resolve, SymbolName}; // Ok so the `//~ HACK` directives here are, well, hacks. Right now we want to // compile on stable for serde support, but we also want to use // #[derive(Serialize, Deserialize)] macros *along* wit...
(&self) -> Option<*mut c_void> { self.addr.map(|s| s as *mut c_void) } /// Same as `Symbol::filename` pub fn filename(&self) -> Option<&Path> { self.filename.as_ref().map(|p| &**p) } /// Same as `Symbol::lineno` pub fn lineno(&self) -> Option<u32> { self.lineno } } ...
addr
identifier_name
capture.rs
use std::fmt; use std::mem; use std::os::raw::c_void; use std::path::{Path, PathBuf}; use {trace, resolve, SymbolName}; // Ok so the `//~ HACK` directives here are, well, hacks. Right now we want to // compile on stable for serde support, but we also want to use // #[derive(Serialize, Deserialize)] macros *along* wit...
} impl BacktraceFrame { /// Returns the list of symbols that this frame corresponds to. /// /// Normally there is only one symbol per frame, but sometimes if a number /// of functions are inlined into one frame then multiple symbols will be /// returned. The first symbol listed is the "innermost f...
{ self.symbol_address as *mut c_void }
identifier_body
capture.rs
use std::fmt; use std::mem; use std::os::raw::c_void; use std::path::{Path, PathBuf}; use {trace, resolve, SymbolName}; // Ok so the `//~ HACK` directives here are, well, hacks. Right now we want to // compile on stable for serde support, but we also want to use // #[derive(Serialize, Deserialize)] macros *along* wit...
trace(|frame| { let mut symbols = Vec::new(); resolve(frame.ip(), |symbol| { symbols.push(BacktraceSymbol { name: symbol.name().map(|m| m.as_bytes().to_vec()), addr: symbol.addr().map(|a| a as usize), filename: s...
/// let current_backtrace = Backtrace::new(); /// ``` pub fn new() -> Backtrace { let mut frames = Vec::new();
random_line_split
capture.rs
use std::fmt; use std::mem; use std::os::raw::c_void; use std::path::{Path, PathBuf}; use {trace, resolve, SymbolName}; // Ok so the `//~ HACK` directives here are, well, hacks. Right now we want to // compile on stable for serde support, but we also want to use // #[derive(Serialize, Deserialize)] macros *along* wit...
} } Ok(()) } } impl Default for Backtrace { fn default() -> Backtrace { Backtrace::new() } }
{ try!(write!(fmt, "\n {:3$}at {}:{}", "", file.display(), line, hex_width)); }
conditional_block
regions-trait-2.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...
() { make_gc().get_ctxt().v; }
main
identifier_name
regions-trait-2.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...
let ctxt = ctxt { v: 22 }; let hc = has_ctxt { c: &ctxt }; return @hc as @get_ctxt; //~^ ERROR source contains reference } fn main() { make_gc().get_ctxt().v; }
impl<'a> get_ctxt for has_ctxt<'a> { fn get_ctxt(&self) -> &'a ctxt { self.c } } fn make_gc() -> @get_ctxt {
random_line_split
ast.rs
#[derive(Debug, PartialEq, Clone)] pub enum Expr { Binary(Box<Expr>, Op, Box<Expr>), Number(f64), Str(String), Name(String), Call(Box<Expr>, Vec<Box<Expr>>), Lambda(Vec<String>, Box<Expr>), Pull, FinishedPipe, Block(Vec<Box<Expr>>), If(Box<Expr>, Box<Expr>, Box<Expr>), While(...
{ pub prototype: Prototype, pub body: Box<Expr>, } impl Definition { pub fn new(prototype: Prototype, body: Box<Expr>) -> Definition { Definition { prototype: prototype, body: body, } } }
Definition
identifier_name
ast.rs
#[derive(Debug, PartialEq, Clone)] pub enum Expr { Binary(Box<Expr>, Op, Box<Expr>), Number(f64), Str(String), Name(String), Call(Box<Expr>, Vec<Box<Expr>>), Lambda(Vec<String>, Box<Expr>), Pull, FinishedPipe, Block(Vec<Box<Expr>>), If(Box<Expr>, Box<Expr>, Box<Expr>), While(...
#[derive(Debug, PartialEq, Clone)] pub struct Definition { pub prototype: Prototype, pub body: Box<Expr>, } impl Definition { pub fn new(prototype: Prototype, body: Box<Expr>) -> Definition { Definition { prototype: prototype, body: body, } } }
random_line_split
reader.rs
use std::path::Component; use migration::Migration; pub fn read_migrations(pattern: &str) -> Result<HashMap<String, Vec<Migration>>, String> { let mut migration_files = HashMap::new(); let entries = glob(pattern).map_err(|err| format!("Failed to read {} due {}", pattern, err))?; for entry in entries { ...
use glob::glob; use std::collections::HashMap; use std::error::Error;
random_line_split
reader.rs
use glob::glob; use std::collections::HashMap; use std::error::Error; use std::path::Component; use migration::Migration; pub fn read_migrations(pattern: &str) -> Result<HashMap<String, Vec<Migration>>, String>
.to_str() .map(|k| k.to_string()) .ok_or(format!("Couldn't make string out of {:?}", keyspace)), _ => Err(format!( "There is no keyspace folder in path {}", path.display() )), }?; info!("File {:?} in ke...
{ let mut migration_files = HashMap::new(); let entries = glob(pattern).map_err(|err| format!("Failed to read {} due {}", pattern, err))?; for entry in entries { let path = entry.map_err(|err| { format!( "Failed to read entry {} in {}", err.description(),...
identifier_body
reader.rs
use glob::glob; use std::collections::HashMap; use std::error::Error; use std::path::Component; use migration::Migration; pub fn
(pattern: &str) -> Result<HashMap<String, Vec<Migration>>, String> { let mut migration_files = HashMap::new(); let entries = glob(pattern).map_err(|err| format!("Failed to read {} due {}", pattern, err))?; for entry in entries { let path = entry.map_err(|err| { format!( ...
read_migrations
identifier_name
color.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/. */ //! Specified color values. use cssparser::{Color as CSSParserColor, Parser, RGBA, Token, BasicParseError}; #[cfg...
} /// Specified color value, but resolved to just RGBA for computed value /// with value from color property at the same context. #[derive(Clone, Debug, PartialEq, ToCss)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct RGBAColor(pub Color); no_viewport_percentage!(RGBAColor); impl Parse for RGBAColor...
{ if computed.is_numeric() { Color::rgba(computed.color) } else if computed.is_currentcolor() { Color::currentcolor() } else { Color::Complex(*computed) } }
identifier_body
color.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/. */ //! Specified color values. use cssparser::{Color as CSSParserColor, Parser, RGBA, Token, BasicParseError}; #[cfg...
(rgba: RGBA) -> Self { Color::Numeric { parsed: rgba, authored: None, } } /// Parse a color, with quirks. /// /// https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk pub fn parse_quirky<'i, 't>(context: &ParserContext, ...
rgba
identifier_name
color.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Color as CSSParserColor, Parser, RGBA, Token, BasicParseError}; #[cfg(feature = "gecko")] use gecko_bindings::structs::nscolor; use itoa; use parser::{ParserContext, Parse}; #[cfg(feature = "gecko")] use properties::longhands::color::SystemColor; use std::fmt; use std::io::Write; use style_traits::{ToCs...
//! Specified color values.
random_line_split
treegen.rs
use anyhow::{Context, Result}; use openat_ext::{FileExt, OpenatDirExt}; use rand::Rng; use sh_inline::bash; use std::fs::File; use std::io::prelude::*; use std::os::unix::fs::FileExt as UnixFileExt; use std::path::Path; use crate::test::*; /// Each time this is invoked it changes file contents /// in the target root,...
; mkvroot(p, v) } // Like mkroot but supports an explicit version pub(crate) fn mkvroot<P: AsRef<Path>>(p: P, v: u32) -> Result<()> { let p = p.as_ref(); for v in &["usr/bin", "etc"] { std::fs::create_dir_all(p.join(v))?; } let verpath = p.join("etc/.mkrootversion"); write_file(&verpath...
{ 0 }
conditional_block
treegen.rs
use anyhow::{Context, Result}; use openat_ext::{FileExt, OpenatDirExt}; use rand::Rng; use sh_inline::bash; use std::fs::File; use std::io::prelude::*; use std::os::unix::fs::FileExt as UnixFileExt; use std::path::Path; use crate::test::*; /// Each time this is invoked it changes file contents /// in the target root,...
) -> Result<()> { let mut destf = dest .write_file(name, 0o755) .context("Failed to open for write")?; f.copy_to(&destf).context("Failed to copy")?; // ELF is OK with us just appending some junk let extra = rand::thread_rng() .sample_iter(&rand::distributions::Alphanumeric) ....
pub(crate) fn mutate_one_executable_to( f: &mut File, name: &std::ffi::OsStr, dest: &openat::Dir,
random_line_split
treegen.rs
use anyhow::{Context, Result}; use openat_ext::{FileExt, OpenatDirExt}; use rand::Rng; use sh_inline::bash; use std::fs::File; use std::io::prelude::*; use std::os::unix::fs::FileExt as UnixFileExt; use std::path::Path; use crate::test::*; /// Each time this is invoked it changes file contents /// in the target root,...
( src: &openat::Dir, dest: &openat::Dir, percentage: u32, ) -> Result<u32> { use nix::sys::stat::Mode as NixMode; assert!(percentage > 0 && percentage <= 100); let mut mutated = 0; for entry in src.list_dir(".")? { let entry = entry?; if src.get_file_type(&entry)?!= openat::S...
mutate_executables_to
identifier_name
treegen.rs
use anyhow::{Context, Result}; use openat_ext::{FileExt, OpenatDirExt}; use rand::Rng; use sh_inline::bash; use std::fs::File; use std::io::prelude::*; use std::os::unix::fs::FileExt as UnixFileExt; use std::path::Path; use crate::test::*; /// Each time this is invoked it changes file contents /// in the target root,...
pub(crate) fn mutate_one_executable_to( f: &mut File, name: &std::ffi::OsStr, dest: &openat::Dir, ) -> Result<()> { let mut destf = dest .write_file(name, 0o755) .context("Failed to open for write")?; f.copy_to(&destf).context("Failed to copy")?; // ELF is OK with us just appendi...
{ let mut buf = [0; 5]; let n = f.read_at(&mut buf, 0)?; if n < buf.len() { anyhow::bail!("Failed to read expected {} bytes", buf.len()); } Ok(buf[0] == 0x7F && &buf[1..4] == b"ELF") }
identifier_body
main.rs
use std::io::Read; use std::fs::File; fn part_1(input: &String) { let total = input.lines() .map(|l| l .trim() .split_whitespace()
.filter(|v| v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max().unwrap() ) .collect::<Vec<_>>() .len(); println!("Part 1: Total was {}", total); } fn part_2(input: &String) { //I am not skill enough with iterator adaptors to use.as_slice().chunks(3) //so we will do things the lazy ...
.map(|v| v.parse::<i32>().unwrap()) .collect::<Vec<_>>())
random_line_split
main.rs
use std::io::Read; use std::fs::File; fn part_1(input: &String) { let total = input.lines() .map(|l| l .trim() .split_whitespace() .map(|v| v.parse::<i32>().unwrap()) .collect::<Vec<_>>()) .filter(|v| v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max()....
} println!("Part 2: there are {} good triangles", total); } fn main() { let mut file = File::open("./data").expect("could not open file"); let mut input = String::new(); file.read_to_string(&mut input).expect("could not read file"); part_1(&input); part_2(&input); }
{ //process our triangles let good = triangles .iter() .filter(|v| { //println!("filtering {:?}", v); v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max().unwrap() } ) .collect::<Vec<_>>(...
conditional_block
main.rs
use std::io::Read; use std::fs::File; fn part_1(input: &String) { let total = input.lines() .map(|l| l .trim() .split_whitespace() .map(|v| v.parse::<i32>().unwrap()) .collect::<Vec<_>>()) .filter(|v| v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max()....
(input: &String) { //I am not skill enough with iterator adaptors to use.as_slice().chunks(3) //so we will do things the lazy way. sad let mut triangles = vec![vec![0; 3]; 3]; let mut read_lines = 3; let mut total = 0; //total good triangles for line in input.lines().map(|l| l.to_string()).colle...
part_2
identifier_name
main.rs
use std::io::Read; use std::fs::File; fn part_1(input: &String) { let total = input.lines() .map(|l| l .trim() .split_whitespace() .map(|v| v.parse::<i32>().unwrap()) .collect::<Vec<_>>()) .filter(|v| v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max()....
) .collect::<Vec<_>>() .len(); //println!("Found {} good ones from this set", good); total = total + good; read_lines = 3; //reset } } println!("Part 2: there are {} good triangles", total); } fn main() { let mut...
{ //I am not skill enough with iterator adaptors to use .as_slice().chunks(3) //so we will do things the lazy way. sad let mut triangles = vec![vec![0; 3]; 3]; let mut read_lines = 3; let mut total = 0; //total good triangles for line in input.lines().map(|l| l.to_string()).collect::<Vec<String>...
identifier_body
encryption_session.rs
// Copyright 2015-2017 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 lat...
fn id(&self) -> SessionId { self.id.clone() } fn is_finished(&self) -> bool { let data = self.data.lock(); data.state == SessionState::Failed || data.state == SessionState::Finished } fn on_node_timeout(&self, node: &NodeId) { let mut data = self.data.lock(); warn!("{}: encryption session failed ...
{ "encryption" }
identifier_body
encryption_session.rs
// Copyright 2015-2017 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 lat...
use key_server_cluster::cluster_sessions::ClusterSession; use key_server_cluster::message::{Message, EncryptionMessage, InitializeEncryptionSession, ConfirmEncryptionInitialization, EncryptionSessionError}; /// Encryption session API. pub trait Session: Send + Sync +'static { /// Get encryption session state. fn st...
use parking_lot::{Condvar, Mutex}; use ethkey::{self, Public, Signature}; use key_server_cluster::{Error, NodeId, SessionId, KeyStorage, DocumentKeyShare}; use key_server_cluster::cluster::Cluster;
random_line_split
encryption_session.rs
// Copyright 2015-2017 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 lat...
// start initialization if data.nodes.len() > 1 { self.cluster.broadcast(Message::Encryption(EncryptionMessage::InitializeEncryptionSession(InitializeEncryptionSession { session: self.id.clone().into(), session_nonce: self.nonce, requestor_signature: requestor_signature.into(), common_point: co...
{ // check that the requester is the author of the encrypted data let requestor_public = ethkey::recover(&requestor_signature, &self.id)?; if encrypted_data.author != requestor_public { return Err(Error::AccessDenied); } encrypted_data.common_point = Some(common_point.clone()); encrypted_data.enc...
conditional_block
encryption_session.rs
// Copyright 2015-2017 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 lat...
(&self) -> &NodeId { &self.self_node_id } /// Start new session initialization. This must be called on master node. pub fn initialize(&self, requestor_signature: Signature, common_point: Public, encrypted_point: Public) -> Result<(), Error> { let mut data = self.data.lock(); // check state if data.state!= ...
node
identifier_name
pipe.rs
use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::sys::fd::FileDesc; use crate::sys::{cvt, cvt_r}; use crate::sys_common::IntoInner; //////////////////////////////////////////////////////////////////////////////// /...
(self) -> RawFd { self.0.into_raw_fd() } } impl FromRawFd for AnonPipe { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { Self(FromRawFd::from_raw_fd(raw_fd)) } }
into_raw_fd
identifier_name
pipe.rs
use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::sys::fd::FileDesc; use crate::sys::{cvt, cvt_r}; use crate::sys_common::IntoInner; //////////////////////////////////////////////////////////////////////////////// /...
target_os = "freebsd", target_os = "linux", target_os = "netbsd", target_os = "openbsd", target_os = "redox" ))] { unsafe { cvt(libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC))?; Ok((AnonPipe(FileDesc::from_ra...
cfg_if::cfg_if! { if #[cfg(any( target_os = "dragonfly",
random_line_split
pipe.rs
use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::sys::fd::FileDesc; use crate::sys::{cvt, cvt_r}; use crate::sys_common::IntoInner; //////////////////////////////////////////////////////////////////////////////// /...
} impl IntoRawFd for AnonPipe { fn into_raw_fd(self) -> RawFd { self.0.into_raw_fd() } } impl FromRawFd for AnonPipe { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { Self(FromRawFd::from_raw_fd(raw_fd)) } }
{ self.0.as_fd() }
identifier_body
net.rs
use pongo::ui::{Drawable,Ui}; use sdl2::pixels::Color; use sdl2::rect::Rect; pub struct Net { pub color: Color, pub x: f32, // x pixel coordinate of top left corner pub dot_width: f32, pub dot_height: f32, pub num_dots: i32 } impl Net { pub fn new(color: Color, x: f32, do...
} } }
{ let dot_y = i as f32 * self.dot_height; ui.renderer.set_draw_color(self.color); let dot_rect = Rect::new_unwrap(dot_x as i32, dot_y as i32, self.dot_width as u32, self.dot...
conditional_block
net.rs
use pongo::ui::{Drawable,Ui}; use sdl2::pixels::Color; use sdl2::rect::Rect; pub struct Net { pub color: Color, pub x: f32, // x pixel coordinate of top left corner pub dot_width: f32, pub dot_height: f32, pub num_dots: i32 } impl Net { pub fn new(color: Color, x: f32, do...
} } }
random_line_split
net.rs
use pongo::ui::{Drawable,Ui}; use sdl2::pixels::Color; use sdl2::rect::Rect; pub struct Net { pub color: Color, pub x: f32, // x pixel coordinate of top left corner pub dot_width: f32, pub dot_height: f32, pub num_dots: i32 } impl Net { pub fn
(color: Color, x: f32, dot_width: f32, dot_height: f32, num_dots: i32) -> Net { return Net { color: color, x: x, dot_width: dot_width, dot_height: dot_height, num_dots: num_dots }; } } impl Drawable for Net { fn draw(&self, ui: &mut ...
new
identifier_name
net.rs
use pongo::ui::{Drawable,Ui}; use sdl2::pixels::Color; use sdl2::rect::Rect; pub struct Net { pub color: Color, pub x: f32, // x pixel coordinate of top left corner pub dot_width: f32, pub dot_height: f32, pub num_dots: i32 } impl Net { pub fn new(color: Color, x: f32, do...
} impl Drawable for Net { fn draw(&self, ui: &mut Ui) { let dot_x = self.x; let num_gaps = self.num_dots - 1; for i in 0..self.num_dots + num_gaps + 1 { if i % 2 == 0 { let dot_y = i as f32 * self.dot_height; ui.renderer.set_draw_color(self.co...
{ return Net { color: color, x: x, dot_width: dot_width, dot_height: dot_height, num_dots: num_dots }; }
identifier_body
borrowck-borrowed-uniq-rvalue.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let mut buggy_map: HashMap<uint, &uint> = HashMap::new(); buggy_map.insert(42, &*~1); //~ ERROR borrowed value does not live long enough // but it is ok if we use a temporary let tmp = ~2; buggy_map.insert(43, &*tmp); }
identifier_body
borrowck-borrowed-uniq-rvalue.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let mut buggy_map: HashMap<uint, &uint> = HashMap::new(); buggy_map.insert(42, &*~1); //~ ERROR borrowed value does not live long enough // but it is ok if we use a temporary let tmp = ~2; buggy_map.insert(43, &*tmp); }
main
identifier_name
borrowck-borrowed-uniq-rvalue.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// but it is ok if we use a temporary let tmp = ~2; buggy_map.insert(43, &*tmp); }
random_line_split
lib.rs
// Copyright 2013-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...
} /// This trait provides basic operations to modify the contents of a map. pub trait MutableMap<K, V>: Map<K, V> + Mutable { /// Insert a key-value pair into the map. An existing value for a /// key is replaced by the new value. Return true if the key did /// not already exist in the map. #[inline] ...
{ self.find(key).is_some() }
identifier_body
lib.rs
// Copyright 2013-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, key: &K) -> bool { self.find(key).is_some() } } /// This trait provides basic operations to modify the contents of a map. pub trait MutableMap<K, V>: Map<K, V> + Mutable { /// Insert a key-value pair into the map. An existing value for a /// key is replaced by the new value. Return true if ...
contains_key
identifier_name
lib.rs
// Copyright 2013-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...
/// Return true if the map contains a value for the specified key #[inline] fn contains_key(&self, key: &K) -> bool { self.find(key).is_some() } } /// This trait provides basic operations to modify the contents of a map. pub trait MutableMap<K, V>: Map<K, V> + Mutable { /// Insert a key-va...
/// trait provides basic operations to operate on these stores. pub trait Map<K, V>: Collection { /// Return a reference to the value corresponding to the key fn find<'a>(&'a self, key: &K) -> Option<&'a V>;
random_line_split
text-fields-attribute.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
changed(entry) => { let text = entry.text().to_string(); let len = text.len(); Change(text, len) }, placeholder_text: Some("Text to reverse"), }, #[name="la...
gtk::Window { gtk::Box { orientation: Vertical, #[name="entry"] gtk::Entry {
random_line_split
text-fields-attribute.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
{ content: String, } #[derive(Msg)] pub enum Msg { Change(String, usize), Quit, } #[widget] impl Widget for Win { fn model() -> Model { Model { content: String::new(), } } fn update(&mut self, event: Msg) { match event { Change(text, len) => { ...
Model
identifier_name
pointing.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_...
let ident = input.expect_ident()?; if ident.eq_ignore_ascii_case("auto") { Ok(computed_value::Keyword::Auto) } else { Cursor::from_css_keyword(&ident) .map(computed_value::Keyword::Cursor) .map_err(|()| SelectorPar...
-> Result<computed_value::Keyword, ParseError<'i>> { use std::ascii::AsciiExt; use style_traits::cursor::Cursor;
random_line_split
pointing.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_...
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.url.to_css(dest)?; if let Some((x, y)) = self.hotspot { dest.write_str(" ")?; x.to_css(dest)?; dest.write_str(" ")?; y.to_css(dest)?; ...
to_css
identifier_name
clone.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} impl<'a, Sized? T> Clone for &'a T { /// Return a shallow copy of the reference. #[inline] fn clone(&self) -> &'a T { *self } } macro_rules! clone_impl( ($t:ty) => { impl Clone for $t { /// Return a deep copy of the value. #[inline] fn clone(&self) -> $t ...
{ *self = source.clone() }
identifier_body
clone.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&self) -> &'a T { *self } } macro_rules! clone_impl( ($t:ty) => { impl Clone for $t { /// Return a deep copy of the value. #[inline] fn clone(&self) -> $t { *self } } } ) clone_impl!(int) clone_impl!(i8) clone_impl!(i16) clone_impl!(i32) clone_impl!(i64) c...
clone
identifier_name
clone.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
clone_impl!(uint) clone_impl!(u8) clone_impl!(u16) clone_impl!(u32) clone_impl!(u64) clone_impl!(f32) clone_impl!(f64) clone_impl!(()) clone_impl!(bool) clone_impl!(char) macro_rules! extern_fn_clone( ($($A:ident),*) => ( #[experimental = "this may not be sufficient for fns with region parameters"] ...
clone_impl!(i16) clone_impl!(i32) clone_impl!(i64)
random_line_split
preempt.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...
{ let (port, chan) = stream(); println!("main started"); spawn(move|| { starve_main(port); }); let mut i: isize = 0; println!("main waiting for alive signal"); chan.send(i); println!("main got alive signal"); while i < 50 { println!("main iterated"); i += 1; } println!("...
identifier_body
preempt.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...
// note: halfway done porting to modern rust use std::comm; fn starve_main(alive: Receiver<isize>) { println!("signalling main"); alive.recv(); println!("starving main"); let mut i: isize = 0; loop { i += 1; } } pub fn main() { let (port, chan) = stream(); println!("main started"); s...
random_line_split
preempt.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...
() { let (port, chan) = stream(); println!("main started"); spawn(move|| { starve_main(port); }); let mut i: isize = 0; println!("main waiting for alive signal"); chan.send(i); println!("main got alive signal"); while i < 50 { println!("main iterated"); i += 1; } println...
main
identifier_name
doepdmab.rs
#[doc = "Register `DOEPDMAB` reader"] pub struct R(crate::R<DOEPDMAB_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DOEPDMAB_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DOEPDMAB_SPEC>> for R { #[inline(always)] fn from(reader: ...
(crate::FieldReader<u32, u32>); impl DMABUFFERADDR_R { pub(crate) fn new(bits: u32) -> Self { DMABUFFERADDR_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DMABUFFERADDR_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { ...
DMABUFFERADDR_R
identifier_name
doepdmab.rs
#[doc = "Register `DOEPDMAB` reader"] pub struct R(crate::R<DOEPDMAB_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DOEPDMAB_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DOEPDMAB_SPEC>> for R { #[inline(always)] fn from(reader: ...
pub(crate) fn new(bits: u32) -> Self { DMABUFFERADDR_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DMABUFFERADDR_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:31 - DMA...
} #[doc = "Field `DMABufferAddr` reader - DMA Buffer Address"] pub struct DMABUFFERADDR_R(crate::FieldReader<u32, u32>); impl DMABUFFERADDR_R {
random_line_split
lib.rs
//! A library of Conflict-free Replicated Data Types. //! //! ###### Further Reading //! //! 1. [_A comprehensive study of Convergent and Commutative Replicated Data Types_](http://hal.inria.fr/docs/00/55/55/88/PDF/techreport.pdf) (Shapiro, et al.) //! 2. [_An Optimized Conflict-free Replicated Set_](http://arxiv.org/p...
} }
fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> TransactionId { TransactionId(quickcheck::Arbitrary::arbitrary(g)) } fn shrink(&self) -> Box<Iterator<Item=TransactionId> + 'static> { Box::new(self.id().shrink().map(|id| TransactionId(id)))
random_line_split
lib.rs
//! A library of Conflict-free Replicated Data Types. //! //! ###### Further Reading //! //! 1. [_A comprehensive study of Convergent and Commutative Replicated Data Types_](http://hal.inria.fr/docs/00/55/55/88/PDF/techreport.pdf) (Shapiro, et al.) //! 2. [_An Optimized Conflict-free Replicated Set_](http://arxiv.org/p...
(&self) -> Box<Iterator<Item=TransactionId> +'static> { Box::new(self.id().shrink().map(|id| TransactionId(id))) } }
shrink
identifier_name
lib.rs
//! A library of Conflict-free Replicated Data Types. //! //! ###### Further Reading //! //! 1. [_A comprehensive study of Convergent and Commutative Replicated Data Types_](http://hal.inria.fr/docs/00/55/55/88/PDF/techreport.pdf) (Shapiro, et al.) //! 2. [_An Optimized Conflict-free Replicated Set_](http://arxiv.org/p...
/// The Id for an individual operation on a CRDT. /// /// Some CRDTs require the user to provide a transaction ID when performing /// mutating operations. Transaction IDs provided to an individual replica /// **must** be monotonically increasing across operations. Transaction IDs /// across replicas **must** be uniqu...
{ use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; static mut REPLICA_COUNT: AtomicUsize = ATOMIC_USIZE_INIT; let id = unsafe { REPLICA_COUNT.fetch_add(1, Ordering::SeqCst) as u64 }; ReplicaId(id) }
identifier_body
mobilenetv3.rs
use std::error::Error; use std::path::PathBuf; use std::result::Result; use tensorflow::Code; use tensorflow::Graph; use tensorflow::SavedModelBundle; use tensorflow::SessionOptions; use tensorflow::SessionRunArgs; use tensorflow::Status; use tensorflow::Tensor; use tensorflow::DEFAULT_SERVING_SIGNATURE_DEF_KEY; use i...
// Create input variables for our addition let mut x = Tensor::new(&[1, 224, 224, 3]); let img = ImageReader::open("examples/mobilenetv3/sample.png")?.decode()?; for (i, (_, _, pixel)) in img.pixels().enumerate() { x[3 * i] = pixel.0[0] as f32; x[3 * i + 1] = pixel.0[1] as f32; ...
{ return Err(Box::new( Status::new_set( Code::NotFound, &format!( "Run 'python examples/mobilenetv3/create_model.py' to generate \ {} and try again.", model_file.display() ), ) ...
conditional_block
mobilenetv3.rs
use std::error::Error; use std::path::PathBuf; use std::result::Result; use tensorflow::Code; use tensorflow::Graph; use tensorflow::SavedModelBundle; use tensorflow::SessionOptions; use tensorflow::SessionRunArgs; use tensorflow::Status; use tensorflow::Tensor; use tensorflow::DEFAULT_SERVING_SIGNATURE_DEF_KEY; use i...
SavedModelBundle::load(&SessionOptions::new(), &["serve"], &mut graph, export_dir)?; let session = &bundle.session; // get in/out operations let signature = bundle .meta_graph_def() .get_signature(DEFAULT_SERVING_SIGNATURE_DEF_KEY)?; let x_info = signature.get_input("input_1")?; ...
} // Load the saved model exported by zenn_savedmodel.py. let mut graph = Graph::new(); let bundle =
random_line_split
mobilenetv3.rs
use std::error::Error; use std::path::PathBuf; use std::result::Result; use tensorflow::Code; use tensorflow::Graph; use tensorflow::SavedModelBundle; use tensorflow::SessionOptions; use tensorflow::SessionRunArgs; use tensorflow::Status; use tensorflow::Tensor; use tensorflow::DEFAULT_SERVING_SIGNATURE_DEF_KEY; use i...
() -> Result<(), Box<dyn Error>> { let export_dir = "examples/mobilenetv3"; let model_file: PathBuf = [export_dir, "saved_model.pb"].iter().collect(); if!model_file.exists() { return Err(Box::new( Status::new_set( Code::NotFound, &format!( ...
main
identifier_name
mobilenetv3.rs
use std::error::Error; use std::path::PathBuf; use std::result::Result; use tensorflow::Code; use tensorflow::Graph; use tensorflow::SavedModelBundle; use tensorflow::SessionOptions; use tensorflow::SessionRunArgs; use tensorflow::Status; use tensorflow::Tensor; use tensorflow::DEFAULT_SERVING_SIGNATURE_DEF_KEY; use i...
for (i, (_, _, pixel)) in img.pixels().enumerate() { x[3 * i] = pixel.0[0] as f32; x[3 * i + 1] = pixel.0[1] as f32; x[3 * i + 2] = pixel.0[2] as f32; } // Load the saved model exported by zenn_savedmodel.py. let mut graph = Graph::new(); let bundle = SavedModelBundl...
{ let export_dir = "examples/mobilenetv3"; let model_file: PathBuf = [export_dir, "saved_model.pb"].iter().collect(); if !model_file.exists() { return Err(Box::new( Status::new_set( Code::NotFound, &format!( "Run 'python examples/mobile...
identifier_body
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMe...
(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } ...
new
identifier_name
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMe...
/// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution...
{ self.is_root_element }
identifier_body
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMe...
if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } ...
{ dest.write_str("auto, ")?; }
conditional_block
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMe...
#[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOr...
random_line_split
mod.rs
#[cfg_attr(rustfmt, rustfmt_skip)] #[allow(unknown_lints)] #[allow(clippy::all)] mod grammar { // During the build step, `build.rs` will output the generated parser to `OUT_DIR` to avoid // adding it to the source directory, so we just directly include the generated parser here. // // Even with `.gitign...
(input: &str) -> ParseResult { grammar::DefinitionsParser::new().parse(::Lexer::new(input)) }
parse_string
identifier_name
mod.rs
#[cfg_attr(rustfmt, rustfmt_skip)] #[allow(unknown_lints)] #[allow(clippy::all)] mod grammar { // During the build step, `build.rs` will output the generated parser to `OUT_DIR` to avoid // adding it to the source directory, so we just directly include the generated parser here. // // Even with `.gitign...
{ grammar::DefinitionsParser::new().parse(::Lexer::new(input)) }
identifier_body
mod.rs
#[cfg_attr(rustfmt, rustfmt_skip)] #[allow(unknown_lints)] #[allow(clippy::all)] mod grammar { // During the build step, `build.rs` will output the generated parser to `OUT_DIR` to avoid // adding it to the source directory, so we just directly include the generated parser here. // // Even with `.gitign...
pub fn parse_string(input: &str) -> ParseResult { grammar::DefinitionsParser::new().parse(::Lexer::new(input)) }
/// name: "Node".to_string() /// }))])); /// ```
random_line_split
specialization-translate-projections-with-params.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) -> &u8 { self } } impl Trait<u8> for u8 {} fn main() { assert!(3u8.convert() == 3u8); }
as_item
identifier_name
specialization-translate-projections-with-params.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ assert!(3u8.convert() == 3u8); }
identifier_body
specialization-translate-projections-with-params.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl Trait<u8> for u8 {} fn main() { assert!(3u8.convert() == 3u8); }
type Item = u8; fn as_item(&self) -> &u8 { self }
random_line_split
header_bar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
lse { Some(unsafe { string::raw::from_buf(c_title as *const u8) }) } } pub fn set_subtitle(&mut self, subtitle: &str) { unsafe { subtitle.with_c_str(|c_str| { ffi::gtk_header_bar_set_subtitle(GTK_HEADER_BAR(self.pointer), c_str) }) } ...
None } e
conditional_block
header_bar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
ffi::gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(self.pointer), ffi::to_gboolean(setting)) } } } impl_drop!(HeaderBar) impl_TraitWidget!(HeaderBar) impl gtk::ContainerTrait for HeaderBar {} impl_widget_events!(HeaderBar)
pub fn set_show_close_button(&mut self, setting: bool) { unsafe {
random_line_split
header_bar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
pub fn is_show_close_button(&self) -> bool { unsafe { ffi::to_bool(ffi::gtk_header_bar_get_show_close_button(GTK_HEADER_BAR(self.pointer))) } } pub fn set_show_close_button(&mut self, setting: bool) { unsafe { ffi::gtk_header_bar_set_show_close_button(GTK_HEA...
unsafe { ffi::gtk_header_bar_pack_end(GTK_HEADER_BAR(self.pointer), child.get_widget()) } }
identifier_body
header_bar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
mut self, title: &str) { unsafe { title.with_c_str(|c_str| { ffi::gtk_header_bar_set_title(GTK_HEADER_BAR(self.pointer), c_str) }) } } pub fn get_title(&self) -> Option<String> { let c_title = unsafe { ffi::gtk_header_bar_get_title(GTK_HEADER_BAR(...
t_title(&
identifier_name
async.rs
#![cfg(feature = "std")] use std::{cell::Cell, io::Cursor, rc::Rc, str}; use {futures_03_dep as futures, tokio_dep as tokio}; use { bytes::{Buf, BytesMut}, combine::{ error::{ParseError, StreamError}, parser::{ byte::digit, combinator::{any_partial_state, AnyPartialSta...
// `Some` means that a message was successfully decoded // (and that we are ready to start decoding the next message) Some(output) => { let value = String::from_utf8(output)?; println!("Decoded `{}`", value); Ok(Some(value)) ...
{ println!("Requesting more input!"); Ok(None) }
conditional_block
async.rs
#![cfg(feature = "std")] use std::{cell::Cell, io::Cursor, rc::Rc, str}; use {futures_03_dep as futures, tokio_dep as tokio}; use { bytes::{Buf, BytesMut}, combine::{ error::{ParseError, StreamError}, parser::{ byte::digit, combinator::{any_partial_state, AnyPartialSta...
// Ideally this would be done automatically by the call to // `stream::decode` but it does unfortunately not work due // to lifetime issues (Non lexical lifetimes might fix it!) src.advance(removed_len); match opt { // `None` means we did not have enough input and we...
// Remove the input we just committed.
random_line_split
async.rs
#![cfg(feature = "std")] use std::{cell::Cell, io::Cursor, rc::Rc, str}; use {futures_03_dep as futures, tokio_dep as tokio}; use { bytes::{Buf, BytesMut}, combine::{ error::{ParseError, StreamError}, parser::{ byte::digit, combinator::{any_partial_state, AnyPartialSta...
} /// Parses blocks of data with length headers /// /// ``` /// Content-Length: 18 /// /// { "some": "data" } /// ``` // The `content_length_parses` parameter only exists to demonstrate that `content_length` only // gets parsed once per message fn decode_parser<'a, Input>( content_length_parses: Rc<Cell<i32>>, ) ...
{ LanguageServerDecoder { state: Default::default(), content_length_parses: Rc::new(Cell::new(0)), } }
identifier_body
async.rs
#![cfg(feature = "std")] use std::{cell::Cell, io::Cursor, rc::Rc, str}; use {futures_03_dep as futures, tokio_dep as tokio}; use { bytes::{Buf, BytesMut}, combine::{ error::{ParseError, StreamError}, parser::{ byte::digit, combinator::{any_partial_state, AnyPartialSta...
{ state: AnyPartialState, content_length_parses: Rc<Cell<i32>>, } impl Default for LanguageServerDecoder { fn default() -> Self { LanguageServerDecoder { state: Default::default(), content_length_parses: Rc::new(Cell::new(0)), } } } /// Parses blocks of data wi...
LanguageServerDecoder
identifier_name
vec-must-not-hide-type-from-dropck.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } #[derive(Debug)] struct C<'a> { id: Id, v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>, } impl<'a> HasId for Cell<Option<&'a C<'a>>> { fn count(&self) -> usize { match self.get() { None => 1, Some(c) => c.id.count(), } } } impl<'a> C<'a> { fn new() -> C<'...
#[unsafe_destructor] impl<T:HasId> Drop for CheckId<T> { fn drop(&mut self) { assert!(self.v.count() > 0);
random_line_split
vec-must-not-hide-type-from-dropck.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) -> usize { match self.get() { None => 1, Some(c) => c.id.count(), } } } impl<'a> C<'a> { fn new() -> C<'a> { C { id: Id::new(), v: Vec::new() } } } fn f() { let (mut c1, mut c2); c1 = C::new(); c2 = C::new(); c1.v.push(CheckId(Cell::...
count
identifier_name
types.rs
pub fn is_short_value(value: &[u8]) -> bool { value.len() <= SHORT_VALUE_MAX_LEN } /// Value type which is essentially raw bytes. pub type Value = Vec<u8>; /// Key-value pair type. /// /// The value is simply raw bytes; the key is a little bit tricky, which is /// encoded bytes. pub type KvPair = (Vec<u8>, Valu...
/// Delete `Key`. Delete { key: Key }, } impl RawMutation { pub fn key(&self) -> &Key { match self { RawMutation::Put { ref key, value: _, ttl: _, } => key, RawMutation::Delete { ref key } => key, } } } ...
/// Put `Value` into `Key` with TTL. The TTL will overwrite the existing TTL value. Put { key: Key, value: Value, ttl: u64 },
random_line_split
types.rs
pub fn is_short_value(value: &[u8]) -> bool { value.len() <= SHORT_VALUE_MAX_LEN } /// Value type which is essentially raw bytes. pub type Value = Vec<u8>; /// Key-value pair type. /// /// The value is simply raw bytes; the key is a little bit tricky, which is /// encoded bytes. pub type KvPair = (Vec<u8>, Value)...
} // Returned by MvccTxn when extra_op is set to kvrpcpb::ExtraOp::ReadOldValue. // key with current ts -> (short value of the prev txn, start ts of the prev txn). // The value of the map will be None when the mutation is `Insert`. // MutationType is the type of mutation of the current write. pub type OldValues = Has...
{ let value_size = match self { OldValue::Value { value } => value.len(), _ => 0, }; value_size + std::mem::size_of::<OldValue>() }
identifier_body
types.rs
pub fn is_short_value(value: &[u8]) -> bool { value.len() <= SHORT_VALUE_MAX_LEN } /// Value type which is essentially raw bytes. pub type Value = Vec<u8>; /// Key-value pair type. /// /// The value is simply raw bytes; the key is a little bit tricky, which is /// encoded bytes. pub type KvPair = (Vec<u8>, Value)...
} /// Extract the user key from a ts encoded key. #[inline] pub fn truncate_ts_for(key: &[u8]) -> Result<&[u8], codec::Error> { let len = key.len(); if len < number::U64_SIZE { return Err(codec::Error::KeyLength); } Ok(&key[..key.len() - number::U64_SIZE]) ...
{ let pos = key.len() - number::U64_SIZE; let k = &key[..pos]; let mut ts = &key[pos..]; Ok((k, number::decode_u64_desc(&mut ts)?.into())) }
conditional_block
types.rs
pub fn is_short_value(value: &[u8]) -> bool { value.len() <= SHORT_VALUE_MAX_LEN } /// Value type which is essentially raw bytes. pub type Value = Vec<u8>; /// Key-value pair type. /// /// The value is simply raw bytes; the key is a little bit tricky, which is /// encoded bytes. pub type KvPair = (Vec<u8>, Value)...
(mut self) -> Result<Key, codec::Error> { let len = self.0.len(); if len < number::U64_SIZE { // TODO: IMHO, this should be an assertion failure instead of // returning an error. If this happens, it indicates a bug in // the caller module, have to make code change to ...
truncate_ts
identifier_name
mutex.rs
// a simple spin lock based async mutex use super::cpu_relax; use futures::prelude::*; use futures::task; use std::cell::RefCell; use std::cell::UnsafeCell; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; #[derive(Clone)] pub ...
} } impl<T> Mutex<T> { pub fn new(val: T) -> Mutex<T> { Mutex { inner: Arc::new(MutexInner { raw: RawMutex::new(), data: UnsafeCell::new(val), }), } } pub fn lock_async(&self) -> AsyncMutexGuard<T> { AsyncMutexGuard { ...
{ task::current().notify(); Ok(Async::NotReady) }
conditional_block
mutex.rs
// a simple spin lock based async mutex use super::cpu_relax; use futures::prelude::*; use futures::task; use std::cell::RefCell; use std::cell::UnsafeCell; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; #[derive(Clone)] pub ...
#[test] fn smoke() { let m = Mutex::new(()); drop(m.lock()); drop(m.lock()); } #[test] fn test_mutex_arc_nested() { // Tests nested mutexes and access // to underlying data. let arc = Arc::new(Mutex::new(1)); let arc2 = Arc::new(Mutex::new(ar...
(0..1000).for_each(|i| { assert_eq!(*mutex.lock().get(&i).unwrap(), i + 1); assert_eq!(*mutex.lock().get(&(i + 1)).unwrap(), i + 2); }) }
random_line_split
mutex.rs
// a simple spin lock based async mutex use super::cpu_relax; use futures::prelude::*; use futures::task; use std::cell::RefCell; use std::cell::UnsafeCell; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; #[derive(Clone)] pub ...
} impl<T> MutexGuard<T> { #[inline] pub fn mutate(&self) -> &mut T { unsafe { &mut *self.mutex.data.get() } } } impl<T> Deref for MutexGuard<T> { type Target = T; #[inline] fn deref(&self) -> &T { unsafe { &*self.mutex.data.get() } } } impl<T> DerefMut for MutexGuard<T> {...
{ self.inner.raw.lock(); MutexGuard { mutex: self.inner.clone(), } }
identifier_body
mutex.rs
// a simple spin lock based async mutex use super::cpu_relax; use futures::prelude::*; use futures::task; use std::cell::RefCell; use std::cell::UnsafeCell; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; #[derive(Clone)] pub ...
(&self) { while self.state.compare_and_swap(false, true, Ordering::Relaxed) { while self.state.load(Ordering::Relaxed) { cpu_relax(); } } } fn unlock(&self) { assert!(self.state.compare_and_swap(true, false, Ordering::Relaxed)) } } impl<T: Si...
lock
identifier_name
aggregate_ordering.rs
use crate::expression::functions::sql_function; use crate::sql_types::{IntoNullable, SingleValue, SqlOrd, SqlType};
impl<T> SqlOrdAggregate for T where T: SqlOrd + IntoNullable + SingleValue, T::Nullable: SqlType + SingleValue, { type Ret = T::Nullable; } sql_function! { /// Represents a SQL `MAX` function. This function can only take types which are /// ordered. /// /// # Examples /// /// ```ru...
pub trait SqlOrdAggregate: SingleValue { type Ret: SqlType + SingleValue; }
random_line_split
tee.rs
#![crate_name = "tee"] #![feature(phase)] #![feature(macro_rules)] /* * This file is part of the uutils coreutils package. * * (c) Aleksander Bielawski <pabzdzdzwiagief@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ e...
{ inner: Box<Writer+'static>, path: Box<Path> } impl Writer for NamedWriter { fn write(&mut self, buf: &[u8]) -> IoResult<()> { with_path(&*self.path.clone(), || { let val = self.inner.write(buf); if val.is_err() { self.inner = box NullWriter as Box<Writer>;...
NamedWriter
identifier_name
tee.rs
#![crate_name = "tee"] #![feature(phase)] #![feature(macro_rules)] /* * This file is part of the uutils coreutils package. * * (c) Aleksander Bielawski <pabzdzdzwiagief@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ e...
; match File::open_mode(path, mode, Write) { Ok(file) => box file as Box<Writer>, Err(_) => box NullWriter as Box<Writer> } }; box NamedWriter { inner: inner, path: box path.clone() } as Box<Writer> } struct NamedWriter { inner: Box<Writer+'static>, path: Box<Pat...
{ Truncate }
conditional_block
tee.rs
#![crate_name = "tee"] #![feature(phase)] #![feature(macro_rules)] /* * This file is part of the uutils coreutils package. * * (c) Aleksander Bielawski <pabzdzdzwiagief@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ e...
program: String, append: bool, ignore_interrupts: bool, print_and_exit: Option<String>, files: Box<Vec<Path>> } fn options(args: &[String]) -> Result<Options, ()> { let opts = [ optflag("a", "append", "append to the given FILEs, do not overwrite"), optflag("i", "ignore-interrupt...
random_line_split
pact_builder.rs
use pact_matching::models::*; use super::interaction_builder::InteractionBuilder; use crate::prelude::*; /// Builder for `Pact` objects. /// /// ``` /// use pact_consumer::prelude::*; /// use pact_consumer::*; /// /// let pact = PactBuilder::new("Greeting Client", "Greeting Server") /// .interaction("asks for a gr...
pact: RequestResponsePact, } impl PactBuilder { /// Create a new `PactBuilder`, specifying the names of the service /// consuming the API and the service providing it. pub fn new<C, P>(consumer: C, provider: P) -> Self where C: Into<String>, P: Into<String>, { let mut pa...
pub struct PactBuilder {
random_line_split
pact_builder.rs
use pact_matching::models::*; use super::interaction_builder::InteractionBuilder; use crate::prelude::*; /// Builder for `Pact` objects. /// /// ``` /// use pact_consumer::prelude::*; /// use pact_consumer::*; /// /// let pact = PactBuilder::new("Greeting Client", "Greeting Server") /// .interaction("asks for a gr...
(&mut self, interaction: RequestResponseInteraction) -> &mut Self { self.pact.interactions.push(interaction); self } /// Return the `Pact` we've built. pub fn build(&self) -> RequestResponsePact { self.pact.clone() } } impl StartMockServer for PactBuilder { fn start_mock_server...
push_interaction
identifier_name
main.rs
use std::thread; use std::time::Duration; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn
(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, } } fn eat(&self, table: &Table) { let _left = table.forks[self.left].lock().unwrap(); thread::sleep(Duration::from_milli...
new
identifier_name
main.rs
use std::thread; use std::time::Duration; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, ...
let handles: Vec<_> = philosophers .into_iter() .map(|p| { let table = table.clone(); thread::spawn(move || { p.eat(&table); }) }) .collect(); // collect() can return any type, so Vec<_> is needed for let in the above for h in handles { ...
Philosopher::new("Gilles Deleuze", 1, 2), Philosopher::new("Karl Marx", 2, 3), Philosopher::new("Emma Goldman", 3, 4), Philosopher::new("Michel Foucault", 0, 4)];
random_line_split
fixed_bug_long_thin_box_one_shot_manifold3.rs
/*! * # Expected behaviour: * The box stands vertically until it falls asleep. * The box should not fall (horizontally) on the ground. * The box should not traverse the ground. * * # Symptoms: * The long, thin, box fails to collide with the plane: it just ignores it. * * # Cause: * The one shot contact manifo...
let geom = ShapeHandle::new(Cuboid::new(Vector3::new(rad, rad * 10.0, rad))); let collider_desc = ColliderDesc::new(geom).density(r!(1.0)); RigidBodyDesc::new() .collider(&collider_desc) .translation(Vector3::new(x, y, z)) .build(&mut world); /* * Set up the testbed. */...
{ /* * World */ let mut world = World::new(); world.set_gravity(Vector3::new(r!(0.0), r!(-9.81), r!(0.0))); /* * Plane */ let ground_shape = ShapeHandle::new(Plane::new(Vector3::y_axis())); ColliderDesc::new(ground_shape).build(&mut world); /* * Create the box ...
identifier_body