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
main.rs
pub fn sort_disjoint(values: &mut [i32], indices: &[usize]) { let mut sublist_indices = indices.to_owned(); sublist_indices.sort_unstable(); let mut sublist: Vec<i32> = sublist_indices.iter().map(|&i| values[i]).collect(); sublist.sort_unstable(); for i in 0..sublist.len() { values[sublist_i...
}
{ let mut values = [7, 6, 5, 4, 3, 2, 1, 0]; let indices = [6, 1, 7, 2, 0, 4, 3, 5]; sort_disjoint(&mut values, &indices); assert_eq!(values, [0, 1, 2, 3, 4, 5, 6, 7]); }
identifier_body
main.rs
pub fn sort_disjoint(values: &mut [i32], indices: &[usize]) { let mut sublist_indices = indices.to_owned(); sublist_indices.sort_unstable(); let mut sublist: Vec<i32> = sublist_indices.iter().map(|&i| values[i]).collect(); sublist.sort_unstable(); for i in 0..sublist.len() { values[sublist_i...
() { let mut values = [7, 6, 5, 4, 3, 2, 1, 0]; let indices = [6, 1, 7]; sort_disjoint(&mut values, &indices); println!("{:?}", values); } #[cfg(test)] mod tests { use super::sort_disjoint; #[test] fn test_example() { let mut values = [7, 6, 5, 4, 3, 2, 1, 0]; let indices = ...
main
identifier_name
globs.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } n!(f); //~ ERROR cannot find function `f` in this scope n_with_super!(f); mod test2 { super::n! { f //~ ERROR cannot find function `f` in this scope } super::n_with_super! { f } } ...
{ let _: u32 = $i(); let _: () = f(); super::$j(); }
identifier_body
globs.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() -> u32 { 0 } pub fn f() {} mod test { use super::*; fn g() { let _: u32 = $i(); let _: () = f(); } } macro n($j:ident) { mod test { use super::*; fn g() { ...
$i
identifier_name
globs.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
f //~ ERROR cannot find function `f` in this scope } super::n_with_super! { f } } } }
random_line_split
slice.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 ...
<'a>(&'a mut self, _from: &Foo) -> &'a mut Foo { unsafe { COUNT += 1; } self } fn slice_to_mut_<'a>(&'a mut self, _to: &Foo) -> &'a mut Foo { unsafe { COUNT += 1; } self } fn slice_mut_<'a>(&'a mut self, _from: &Foo, _to: &Foo) -> &'a mut Foo { unsafe { COUNT += 1...
slice_from_mut_
identifier_name
slice.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 as_slice_<'a>(&'a self) -> &'a Foo { unsafe { COUNT += 1; } self } fn slice_from_<'a>(&'a self, _from: &Foo) -> &'a Foo { unsafe { COUNT += 1; } self } fn slice_to_<'a>(&'a self, _to: &Foo) -> &'a Foo { unsafe { COUNT += 1; } self } fn slice...
struct Foo; impl Slice<Foo, Foo> for Foo {
random_line_split
slice.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 slice_from_<'a>(&'a self, _from: &Foo) -> &'a Foo { unsafe { COUNT += 1; } self } fn slice_to_<'a>(&'a self, _to: &Foo) -> &'a Foo { unsafe { COUNT += 1; } self } fn slice_<'a>(&'a self, _from: &Foo, _to: &Foo) -> &'a Foo { unsafe { COUNT += 1; } s...
{ unsafe { COUNT += 1; } self }
identifier_body
variant_ref_mut.rs
use vtable::VTable; use variant_ref::VariantRef; use std::any::{Any, TypeId}; use std::fmt::{Debug, Display, Error as FmtError, Formatter}; pub struct VariantRefMut<'a> { data: &'a mut (), vtable: &'a VTable, } impl<'a> VariantRefMut<'a> { pub fn new<T: Any>(value: &'a mut T, vtable: &'a VTable) -> Self { ...
<T: Any>(&self) -> &T { debug_assert!(self.is::<T>()); &*(self.data as *const _ as *const T) } #[inline] pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T { debug_assert!(self.is::<T>()); &mut *(self.data as *mut _ as *mut T) } } impl<'a> AsRef<VariantRef<'a>> for...
downcast_ref_unchecked
identifier_name
variant_ref_mut.rs
use vtable::VTable; use variant_ref::VariantRef; use std::any::{Any, TypeId}; use std::fmt::{Debug, Display, Error as FmtError, Formatter}; pub struct VariantRefMut<'a> { data: &'a mut (), vtable: &'a VTable, } impl<'a> VariantRefMut<'a> { pub fn new<T: Any>(value: &'a mut T, vtable: &'a VTable) -> Self { ...
} } #[inline] pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> { if self.is::<T>() { unsafe { Some(&mut *(self.data as *mut _ as *mut T)) } } else { None } } #[inline] pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T { debug_assert!(se...
random_line_split
variant_ref_mut.rs
use vtable::VTable; use variant_ref::VariantRef; use std::any::{Any, TypeId}; use std::fmt::{Debug, Display, Error as FmtError, Formatter}; pub struct VariantRefMut<'a> { data: &'a mut (), vtable: &'a VTable, } impl<'a> VariantRefMut<'a> { pub fn new<T: Any>(value: &'a mut T, vtable: &'a VTable) -> Self { ...
} #[inline] pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T { debug_assert!(self.is::<T>()); &*(self.data as *const _ as *const T) } #[inline] pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T { debug_assert!(self.is::<T>()); &mut *(self.data as *...
{ None }
conditional_block
graphics.rs
use super::*; use redox::*; impl Editor { /// Redraw the window pub fn redraw(&mut self) { // TODO: Only draw when relevant for the window let x = self.x(); let y = self.y(); // Redraw window self.window.set([0, 0, 0, 255]); self.window.rect(8 * (x - self.scroll...
file: String::new(), cmd: String::new(), msg: String::new(), } } }
impl StatusBar { pub fn new() -> Self { StatusBar { mode: String::new(),
random_line_split
graphics.rs
use super::*; use redox::*; impl Editor { /// Redraw the window pub fn redraw(&mut self) { // TODO: Only draw when relevant for the window let x = self.x(); let y = self.y(); // Redraw window self.window.set([0, 0, 0, 255]); self.window.rect(8 * (x - self.scroll...
else { self.status_bar.mode.chars().collect() }).into_iter().enumerate() { self.window.char(n as isize * 8, h as isize - 16 - 1, c, [255, 255, 255, 255]); } self.window.sync(); } } pub struct StatusBar { pub mode: String, pub file: String, pub cmd: Stri...
{ self.status_bar.mode.chars().take(w / (8 * 4) - 5).chain(vec!['.', '.', '.']).collect::<Vec<_>>() }
conditional_block
graphics.rs
use super::*; use redox::*; impl Editor { /// Redraw the window pub fn redraw(&mut self) { // TODO: Only draw when relevant for the window let x = self.x(); let y = self.y(); // Redraw window self.window.set([0, 0, 0, 255]); self.window.rect(8 * (x - self.scroll...
{ pub mode: String, pub file: String, pub cmd: String, pub msg: String, } impl StatusBar { pub fn new() -> Self { StatusBar { mode: String::new(), file: String::new(), cmd: String::new(), msg: String::new(), } } }
StatusBar
identifier_name
graphics.rs
use super::*; use redox::*; impl Editor { /// Redraw the window pub fn redraw(&mut self)
} else { self.window.char(8 * (x - self.scroll_y) as isize, 16 * (y - self.scroll_x) as isize, *c, [255, 255, 255, 255]); } } } l...
{ // TODO: Only draw when relevant for the window let x = self.x(); let y = self.y(); // Redraw window self.window.set([0, 0, 0, 255]); self.window.rect(8 * (x - self.scroll_y) as isize, 16 * (y - self.scroll_x) as isize, ...
identifier_body
populate_healer.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::{sync::Arc, time::Instant}; use anyhow::{bail, format_err, Error}; use clap_old::Arg; use cloned::cloned; use fbinit::FacebookIni...
(fb: FacebookInit) -> Result<Config, Error> { let app = args::MononokeAppBuilder::new("populate healer queue") .build() .about("Populate blobstore queue from existing key source") .arg( Arg::with_name("storage-id") .long("storage-id") .short("S") ...
parse_args
identifier_name
populate_healer.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::{sync::Arc, time::Instant}; use anyhow::{bail, format_err, Error}; use clap_old::Arg; use cloned::cloned; use fbinit::FacebookIni...
} fn parse_args(fb: FacebookInit) -> Result<Config, Error> { let app = args::MononokeAppBuilder::new("populate healer queue") .build() .about("Populate blobstore queue from existing key source") .arg( Arg::with_name("storage-id") .long("storage-id") ....
{ Self { init_range: (*state.init_range).clone(), current_range: (*state.current_range).clone(), } }
identifier_body
populate_healer.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::{sync::Arc, time::Instant}; use anyhow::{bail, format_err, Error}; use clap_old::Arg; use cloned::cloned; use fbinit::FacebookIni...
started_at: Instant, readonly_storage: bool, } /// State used to resume iteration in case of restart #[derive(Debug, Clone)] struct State { count: usize, init_range: Arc<BlobstoreKeyParam>, current_range: Arc<BlobstoreKeyParam>, } impl State { fn from_init(init_range: Arc<BlobstoreKeyParam>) -...
ctx: CoreContext, state_key: Option<String>, dry_run: bool,
random_line_split
stats.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 ...
(self) -> f64 { if self.len() == 0 { 0.0 } else { let mean = self.mean(); let mut v = 0.0; for self.each |s| { let x = *s - mean; v += x*x; } v/(self.len() as f64) } } fn std_dev(self...
var
identifier_name
stats.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn median_abs_dev(self) -> f64 { let med = self.median(); let abs_devs = self.map(|v| num::abs(med - *v)); abs_devs.median() } fn median_abs_dev_pct(self) -> f64 { (self.median_abs_dev() / self.median()) * 100.0 } }
{ (self.std_dev() / self.mean()) * 100.0 }
identifier_body
stats.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 ...
else { let mean = self.mean(); let mut v = 0.0; for self.each |s| { let x = *s - mean; v += x*x; } v/(self.len() as f64) } } fn std_dev(self) -> f64 { f64::sqrt(self.var()) } fn std_dev_pct(sel...
{ 0.0 }
conditional_block
stats.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
fn median_abs_dev_pct(self) -> f64 { (self.median_abs_dev() / self.median()) * 100.0 }
random_line_split
token.rs
#[derive(Clone, Debug, PartialEq)] pub enum Token { UseKeyword, LetKeyword, ForKeyword, InKeyword, BindKeyword, AsKeyword, WhereKeyword, ToKeyword, QueryKeyword, SetKeyword, DeleteKeyword, UniqueKeyword, AndKeyword, ComponentKeyword, RouteKeyword, Store...
OpenParen, CloseParen, Dot, Comma, Equals, Colon, Semi, Bang, Plus, Minus, Mul, Div, Identifier(String), LiteralNumber(i32), LiteralString(String), LiteralBool(bool), VariableReference(String), }
Pipe, OpenBrace, CloseBrace, OpenBracket, CloseBracket,
random_line_split
token.rs
#[derive(Clone, Debug, PartialEq)] pub enum
{ UseKeyword, LetKeyword, ForKeyword, InKeyword, BindKeyword, AsKeyword, WhereKeyword, ToKeyword, QueryKeyword, SetKeyword, DeleteKeyword, UniqueKeyword, AndKeyword, ComponentKeyword, RouteKeyword, StoreKeyword, ActionKeyword, ExternKeyword, ...
Token
identifier_name
bilock.rs
#![feature(test)] #[cfg(feature = "bilock")] mod bench { use futures::executor::LocalPool; use futures::task::{Context, Waker}; use futures_util::lock::BiLock; use futures_util::lock::BiLockAcquire; use futures_util::lock::BiLockAcquired; use futures_util::task::ArcWake; use std::sync::Arc...
y.release_lock(y_guard); } (x, y) }) } }
let y_guard = match y.poll_next(&mut waker) { Ok(Poll::Ready(Some(guard))) => guard, _ => panic!(), };
random_line_split
bilock.rs
#![feature(test)] #[cfg(feature = "bilock")] mod bench { use futures::executor::LocalPool; use futures::task::{Context, Waker}; use futures_util::lock::BiLock; use futures_util::lock::BiLockAcquire; use futures_util::lock::BiLockAcquired; use futures_util::task::ArcWake; use std::sync::Arc...
(b: &mut Bencher) { let pool = LocalPool::new(); let mut exec = pool.executor(); let waker = notify_noop(); let mut map = task::LocalMap::new(); let mut waker = task::Context::new(&mut map, &waker, &mut exec); b.iter(|| { let (x, y) = BiLock::new(1); ...
lock_unlock
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #![deny(unsafe_code)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern ...
mod storage_thread; pub mod subresource_integrity; mod websocket_loader; /// An implementation of the [Fetch specification](https://fetch.spec.whatwg.org/) pub mod fetch { pub mod cors_cache; pub mod methods; } /// A module for re-exports of items used in unit tests. pub mod test { pub use crate::hosts::{p...
pub mod http_cache; pub mod http_loader; pub mod image_cache; pub mod mime_classifier; pub mod resource_thread;
random_line_split
debug.rs
// Copyright 2016 Mozilla // // 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 writing, software...
<S: Borrow<Schema>>(conn: &rusqlite::Connection, schema: &S) -> Result<Datoms> { datoms_after(conn, schema, bootstrap::TX0 - 1) } /// Return the set of datoms in the store with transaction ID strictly greater than the given `tx`, /// ordered by (e, a, v, tx). /// /// The datom set returned does not include any dat...
datoms
identifier_name
debug.rs
// Copyright 2016 Mozilla // // 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 writing, software...
} } /// Convert a numeric entid to an ident `Entid` if possible, otherwise a numeric `Entid`. pub fn to_entid(schema: &Schema, entid: i64) -> EntidOrIdent { schema.get_ident(entid).map_or(EntidOrIdent::Entid(entid), |ident| EntidOrIdent::Ident(ident.clone())) } // /// Convert a symbolic ident to an ident `En...
{ self }
conditional_block
debug.rs
// Copyright 2016 Mozilla // // 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 writing, software...
pub a: EntidOrIdent, pub v: edn::Value, pub tx: i64, pub added: Option<bool>, } /// Represents a set of datoms (assertions) in the store. /// /// To make comparision easier, we deterministically order. The ordering is the ascending tuple /// ordering determined by `(e, a, (value_type_tag, v), tx)`, wh...
pub struct Datom { // TODO: generalize this. pub e: EntidOrIdent,
random_line_split
traits.rs
// Copyright (c) 2017 Jason White
// 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, copy, modify, merge, publish, distribute, sublicense, and/or sell //...
//
random_line_split
traits.rs
// Copyright (c) 2017 Jason White // // 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, copy, modify, merge, publish, d...
/// Outputs the task knows about *a priori*. It must calculate these by /// *only* looking at the task parameters. It cannot do anything fancy like /// running an external process to determine these. fn known_outputs(&self, _resources: &mut res::Set) {} }
{}
identifier_body
traits.rs
// Copyright (c) 2017 Jason White // // 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, copy, modify, merge, publish, d...
(&self, _resources: &mut res::Set) {} /// Outputs the task knows about *a priori*. It must calculate these by /// *only* looking at the task parameters. It cannot do anything fancy like /// running an external process to determine these. fn known_outputs(&self, _resources: &mut res::Set) {} }
known_inputs
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![comment = "The Servo Parallel Browser Project"] #![license = "MPL"] #![feature(globs, macro_rules)] #![deny(u...
pub use properties::{CSSFloat, DeclaredValue, PropertyDeclarationParseResult}; pub use properties::{longhands, Angle, AngleOrCorner, AngleAoc, CornerAoc}; pub use properties::{Left, Right, Bottom, Top}; pub use node::{TElement, TElementAttributes, TNode}; pub use selectors::{PseudoElement, Before, After, SelectorList, ...
pub use selector_matching::{matches, matches_simple_selector, common_style_affecting_attributes}; pub use selector_matching::{RECOMMENDED_SELECTOR_BLOOM_FILTER_SIZE,SELECTOR_WHITESPACE}; pub use properties::{cascade, cascade_anonymous, computed}; pub use properties::{PropertyDeclaration, ComputedValues, computed_values...
random_line_split
memory.rs
extern crate byteorder; use std::io::Cursor; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; #[derive(Debug)] pub enum MemoryError { PPUAccessViolation(String), APUAccessViolation(String), } pub struct Memory { pub mem: Vec<u8>, } impl Memory { pub fn new() -> Memory { let mut m = M...
if addr <= 0x3FFF { return Ok( (addr & 0x7FF & 0x08) as usize); } if addr <= 0x401F { return Err(MemoryError::APUAccessViolation("Memory access is currently not implemented".to_string())); } Ok(addr as usize) } }
if addr <= 0x1FFF { return Ok( (addr & 0x7FF) as usize); } if addr <= 0x2007 { return Err(MemoryError::PPUAccessViolation("PPU Memory access is currently not implemented".to_string())); }
random_line_split
memory.rs
extern crate byteorder; use std::io::Cursor; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; #[derive(Debug)] pub enum MemoryError { PPUAccessViolation(String), APUAccessViolation(String), } pub struct
{ pub mem: Vec<u8>, } impl Memory { pub fn new() -> Memory { let mut m = Memory { mem: Vec::with_capacity(::std::u16::MAX as usize +1) }; unsafe { &m.mem.set_len(::std::u16::MAX as usize +1); } return m; } // meant for a 'raw' write interface, not meant t...
Memory
identifier_name
memory.rs
extern crate byteorder; use std::io::Cursor; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; #[derive(Debug)] pub enum MemoryError { PPUAccessViolation(String), APUAccessViolation(String), } pub struct Memory { pub mem: Vec<u8>, } impl Memory { pub fn new() -> Memory { let mut m = M...
&self.mem[idx..(idx+inp.len())].clone_from_slice(inp); } pub fn read8(self:&Memory,addr: u16) -> Result<u8,MemoryError> { match self.resolve_address(addr) { Ok(raddr) => Ok(self.mem[raddr]), Err(err) => Err(err) } } pub fn read16(self:&Memory,addr: u16) ...
{ panic!("memory vec length is {}, input array goes from {} to {}",self.mem.len(),index,inp.len()+idx) }
conditional_block
memory.rs
extern crate byteorder; use std::io::Cursor; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; #[derive(Debug)] pub enum MemoryError { PPUAccessViolation(String), APUAccessViolation(String), } pub struct Memory { pub mem: Vec<u8>, } impl Memory { pub fn new() -> Memory
// meant for a 'raw' write interface, not meant to be used by the 6502 processor itself, more // tests and other tools to be able to read blocks of memory quickly and easily // pub fn write(self:&mut Memory, index:u16, inp: &[u8]) { let idx = index as usize; if inp.len() + idx > self.m...
{ let mut m = Memory { mem: Vec::with_capacity(::std::u16::MAX as usize +1) }; unsafe { &m.mem.set_len(::std::u16::MAX as usize +1); } return m; }
identifier_body
margin.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" /> <% from data import ALL_SIDES, maybe_moz_logical_alias %> <%...
allowed_in_page_rule=True, servo_restyle_damage="reflow" )} % endfor
logical=side[1], spec=spec, flags="APPLIES_TO_FIRST_LETTER GETCS_NEEDS_LAYOUT_FLUSH",
random_line_split
types.rs
//! Representation of an email address use idna::domain_to_ascii; use once_cell::sync::Lazy; use regex::Regex; use std::{ convert::{TryFrom, TryInto}, error::Error, ffi::OsStr, fmt::{Display, Formatter, Result as FmtResult}, net::IpAddr, str::FromStr, }; /// Represents an email address with a ...
(user: &str) -> Result<(), AddressError> { if USER_RE.is_match(user) { Ok(()) } else { Err(AddressError::InvalidUser) } } pub(super) fn check_domain(domain: &str) -> Result<(), AddressError> { Address::check_domain_ascii(domain).or_else(|_| { ...
check_user
identifier_name
types.rs
//! Representation of an email address use idna::domain_to_ascii; use once_cell::sync::Lazy; use regex::Regex; use std::{ convert::{TryFrom, TryInto}, error::Error, ffi::OsStr, fmt::{Display, Formatter, Result as FmtResult}, net::IpAddr, str::FromStr, }; /// Represents an email address with a ...
if let Some(caps) = LITERAL_RE.captures(domain) { if let Some(cap) = caps.get(1) { if cap.as_str().parse::<IpAddr>().is_ok() { return Ok(()); } } } Err(AddressError::InvalidDomain) } #[cfg(feature = "smtp-tra...
{ return Ok(()); }
conditional_block
types.rs
//! Representation of an email address use idna::domain_to_ascii; use once_cell::sync::Lazy; use regex::Regex; use std::{ convert::{TryFrom, TryInto}, error::Error, ffi::OsStr, fmt::{Display, Formatter, Result as FmtResult}, net::IpAddr, str::FromStr, }; /// Represents an email address with a ...
Address::check_domain(domain)?; Ok(user.len()) } #[derive(Debug, PartialEq, Clone, Copy)] /// Errors in email addresses parsing pub enum AddressError { /// Missing domain or user MissingParts, /// Unbalanced angle bracket Unbalanced, /// Invalid email user InvalidUser, /// Invalid e...
Address::check_user(user)?;
random_line_split
types.rs
//! Representation of an email address use idna::domain_to_ascii; use once_cell::sync::Lazy; use regex::Regex; use std::{ convert::{TryFrom, TryInto}, error::Error, ffi::OsStr, fmt::{Display, Formatter, Result as FmtResult}, net::IpAddr, str::FromStr, }; /// Represents an email address with a ...
} impl<U, D> TryFrom<(U, D)> for Address where U: AsRef<str>, D: AsRef<str>, { type Error = AddressError; fn try_from((user, domain): (U, D)) -> Result<Self, Self::Error> { let user = user.as_ref(); Address::check_user(user)?; let domain = domain.as_ref(); Address::ch...
{ let at_start = check_address(val)?; Ok(Address { serialized: val.into(), at_start, }) }
identifier_body
image_cache_thread.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 image::base::ImageMetadata; use ipc_channel::ipc::{self, IpcSender}; use msg::constellation_msg::Image; use st...
{ No, Yes, } /// The client side of the image cache thread. This can be safely cloned /// and passed to different threads. #[derive(Clone, Deserialize, Serialize)] pub struct ImageCacheThread { chan: IpcSender<ImageCacheCommand>, } /// The public API for the image cache thread. impl ImageCacheThread { ...
UsePlaceholder
identifier_name
image_cache_thread.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 image::base::ImageMetadata; use ipc_channel::ipc::{self, IpcSender}; use msg::constellation_msg::Image; use st...
/// TODO(gw): Profile this on some real world sites and see /// if it's worth caching the results of this locally in each /// layout / paint thread. GetImageIfAvailable(Url, UsePlaceholder, IpcSender<Result<Arc<Image>, ImageState>>), /// Synchronously check the state of an image in the cache. If th...
/// loaded. Supply a channel to receive the results, and optionally an image responder /// that is passed to the result channel. RequestImageAndMetadata(Url, ImageCacheChan, Option<ImageResponder>), /// Synchronously check the state of an image in the cache.
random_line_split
process.rs
::Stop, 't' => ProcessStatus::Tracing, 'X' | 'x' => ProcessStatus::Dead, 'K' => ProcessStatus::Wakekill, 'W' => ProcessStatus::Waking, 'P' => ProcessStatus::Parked, x => ProcessStatus::Unknown(x as u32), } } } impl fmt::Display for Pro...
else { PathBuf::new() }; } } tmp.pop(); tmp.push("environ"); p.environ = copy_from_file(&tmp); tmp.pop(); tmp.push("cwd"); p.cwd = realpath(&tmp); tmp.pop(); tmp.push("root"); p.root = realpa...
{ PathBuf::from(cmd) }
conditional_block
process.rs
Status::Stop, 't' => ProcessStatus::Tracing, 'X' | 'x' => ProcessStatus::Dead, 'K' => ProcessStatus::Wakekill, 'W' => ProcessStatus::Waking, 'P' => ProcessStatus::Parked, x => ProcessStatus::Unknown(x as u32), } } } impl fmt::Display f...
} fn start_time(&self) -> u64 { self.start_time } fn run_time(&self) -> u64 { self.run_time } fn cpu_usage(&self) -> f32 { self.cpu_usage } fn disk_usage(&self) -> DiskUsage { DiskUsage { written_bytes: self.written_bytes.saturating_sub(sel...
} fn status(&self) -> ProcessStatus { self.status
random_line_split
process.rs
} #[doc(hidden)] impl From<char> for ProcessStatus { fn from(status: char) -> ProcessStatus { match status { 'R' => ProcessStatus::Run, 'S' => ProcessStatus::Sleep, 'D' => ProcessStatus::Idle, 'Z' => ProcessStatus::Zombie, 'T' => ProcessStatus::S...
{ match status { 1 => ProcessStatus::Idle, 2 => ProcessStatus::Run, 3 => ProcessStatus::Sleep, 4 => ProcessStatus::Stop, 5 => ProcessStatus::Zombie, x => ProcessStatus::Unknown(x), } }
identifier_body
process.rs
::Stop, 't' => ProcessStatus::Tracing, 'X' | 'x' => ProcessStatus::Dead, 'K' => ProcessStatus::Wakekill, 'W' => ProcessStatus::Waking, 'P' => ProcessStatus::Parked, x => ProcessStatus::Unknown(x as u32), } } } impl fmt::Display for Pro...
(&self) -> ProcessStatus { self.status } fn start_time(&self) -> u64 { self.start_time } fn run_time(&self) -> u64 { self.run_time } fn cpu_usage(&self) -> f32 { self.cpu_usage } fn disk_usage(&self) -> DiskUsage { DiskUsage { writt...
status
identifier_name
infohash.rs
/* * Copyright (C) 2014-2020 Savoir-faire Linux Inc. * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * 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 ...
pub fn get(data: &str) -> InfoHash { let mut h = InfoHash::new(); unsafe { let c_str = CString::new(data).unwrap(); dht_infohash_get(&mut h, c_str.as_ptr() as *mut u8, data.len()); } h } pub fn from_bytes(data: &Vec<u8>) -> InfoHash { let mut...
let mut h = InfoHash::new(); unsafe { dht_infohash_random(&mut h); } h }
identifier_body
infohash.rs
/* * Copyright (C) 2014-2020 Savoir-faire Linux Inc. * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * 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 ...
data: &Vec<u8>) -> InfoHash { let mut h = InfoHash::new(); unsafe { dht_infohash_get(&mut h, data.as_ptr() as *mut u8, data.len()); } h } pub fn from_hex(data: &str) -> InfoHash { let mut h = InfoHash::new(); unsafe { let c_str = CString::...
rom_bytes(
identifier_name
infohash.rs
/* * Copyright (C) 2014-2020 Savoir-faire Linux Inc. * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * 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 ...
pub fn random() -> InfoHash { let mut h = InfoHash::new(); unsafe { dht_infohash_random(&mut h); } h } pub fn get(data: &str) -> InfoHash { let mut h = InfoHash::new(); unsafe { let c_str = CString::new(data).unwrap(); dht...
pub fn new() -> InfoHash { InfoHash { d: [0; 20] } }
random_line_split
remutex.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 ...
} #[unsafe_destructor] impl<'a, T> Drop for ReentrantMutexGuard<'a, T> { #[inline] fn drop(&mut self) { unsafe { self.__lock.poison.done(&self.__poison); self.__lock.inner.unlock(); } } } #[cfg(test)] mod test { use prelude::v1::*; use sys_common::remutex:...
{ &self.__lock.data }
identifier_body
remutex.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 ...
/// /// The data protected by the mutex can be accessed through this guard via its /// Deref and DerefMut implementations #[must_use] pub struct ReentrantMutexGuard<'a, T: 'a> { // funny underscores due to how Deref/DerefMut currently work (they // disregard field privacy). __lock: &'a ReentrantMutex<T>, ...
/// dropped (falls out of scope), the lock will be unlocked.
random_line_split
remutex.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 ...
(&mut self) { *self.0.borrow_mut() = 42; } } #[test] fn poison_works() { let m = Arc::new(ReentrantMutex::new(RefCell::new(0))); let mc = m.clone(); let result = thread::spawn(move ||{ let lock = mc.lock().unwrap(); *lock.borrow_mut() = 1;...
drop
identifier_name
_5_1_framebuffers.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::Context; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, processInput, loadTexture}; use shader::Shader; use camera::Camera; ...
() { let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // timing let mut deltaTime: f32; // time between current frame a...
main_4_5_1
identifier_name
_5_1_framebuffers.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::Context; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, processInput, loadTexture}; use shader::Shader; use camera::Camera; ...
glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); // query framebuffer size a...
{ let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // timing let mut deltaTime: f32; // time between current frame and...
identifier_body
_5_1_framebuffers.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::Context; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, processInput, loadTexture}; use shader::Shader; use camera::Camera; ...
gl::BindFramebuffer(gl::FRAMEBUFFER, 0); // draw as wireframe // gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE); (shader, screenShader, cubeVBO, cubeVAO, planeVBO, planeVAO, quadVBO, quadVAO, cubeTexture, floorTexture, framebuffer, textureColorbuffer) }; // render loop // ...
{ println!("ERROR::FRAMEBUFFER:: Framebuffer is not complete!"); }
conditional_block
_5_1_framebuffers.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::Context; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, processInput, loadTexture}; use shader::Shader; use camera::Camera; ...
shader.useProgram(); let mut model: Matrix4<f32>; let view = camera.GetViewMatrix(); let projection: Matrix4<f32> = perspective(Deg(camera.Zoom), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); shader.setMat4(c_str!("view"), &view); shader.setMa...
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
random_line_split
static-function-pointer-xc.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast // aux-build:static-function-pointer-aux.rs extern crate aux = "static-fu...
// 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
static-function-pointer-xc.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...
() { assert_eq!(aux::F(42), -42); unsafe { assert_eq!(aux::MutF(42), -42); aux::MutF = f; assert_eq!(aux::MutF(42), 42); aux::MutF = aux::f; assert_eq!(aux::MutF(42), -42); } }
main
identifier_name
static-function-pointer-xc.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...
pub fn main() { assert_eq!(aux::F(42), -42); unsafe { assert_eq!(aux::MutF(42), -42); aux::MutF = f; assert_eq!(aux::MutF(42), 42); aux::MutF = aux::f; assert_eq!(aux::MutF(42), -42); } }
{ x }
identifier_body
shootout-meteor.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...
(&mut self, other: Data) { self.nb += other.nb; let Data { min: min, max: max,..} = other; if min < self.min { self.min = min; } if max > self.max { self.max = max; } } } // Records a new found solution. Returns false if the search must be // stopped. fn handle_sol(raw_sol: &List<u...
reduce_from
identifier_name
shootout-meteor.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...
for (cur_id, pos_masks) in masks_at.iter().enumerate() { if board & 1 << (50 + cur_id)!= 0 { continue; } for &cur_m in pos_masks.iter() { if cur_m & board!= 0 { continue; } coverable |= cur_m; // if every coordinates can be covered and eve...
{ continue; }
conditional_block
shootout-meteor.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...
// Records a new found solution. Returns false if the search must be // stopped. fn handle_sol(raw_sol: &List<u64>, data: &mut Data) { // because we break the symetry, 2 solutions correspond to a call // to this method: the normal solution, and the same solution in // reverse order, i.e. the board rotated...
if min < self.min { self.min = min; } if max > self.max { self.max = max; } } }
random_line_split
main.rs
use std::io; use std::cmp; fn main() { let mut input = String::new(); let mut wrap = 0; let mut ribbon = 0; while let Ok(n) = io::stdin().read_line(&mut input) { if n == 0
let (l, w, h) = { let parts: Vec<_> = input.split('x').collect(); let dims: Vec<_> = parts.iter().filter_map(|&x| x.trim().parse::<i32>().ok()).collect(); if dims.len()!= 3 { continue; } (dims[0], dims[1], dims[2]) }; ...
{ break; }
conditional_block
main.rs
use std::io; use std::cmp; fn main() { let mut input = String::new(); let mut wrap = 0; let mut ribbon = 0; while let Ok(n) = io::stdin().read_line(&mut input) { if n == 0 { break;
let (l, w, h) = { let parts: Vec<_> = input.split('x').collect(); let dims: Vec<_> = parts.iter().filter_map(|&x| x.trim().parse::<i32>().ok()).collect(); if dims.len()!= 3 { continue; } (dims[0], dims[1], dims[2]) }; ...
}
random_line_split
main.rs
use std::io; use std::cmp; fn
() { let mut input = String::new(); let mut wrap = 0; let mut ribbon = 0; while let Ok(n) = io::stdin().read_line(&mut input) { if n == 0 { break; } let (l, w, h) = { let parts: Vec<_> = input.split('x').collect(); let dims: Vec<_> = parts.it...
main
identifier_name
main.rs
use std::io; use std::cmp; fn main()
wrap += 2*l*w + 2*w*h + 2*h*l; wrap += cmp::min(l*w, cmp::min(w*h, h*l)); ribbon += 2*l + 2*w + 2*h - 2*(cmp::max(l, cmp::max(w, h))); ribbon += l*w*h; input.clear(); } println!("Wrap: {0}", wrap); println!("Ribbon: {0}", ribbon); }
{ let mut input = String::new(); let mut wrap = 0; let mut ribbon = 0; while let Ok(n) = io::stdin().read_line(&mut input) { if n == 0 { break; } let (l, w, h) = { let parts: Vec<_> = input.split('x').collect(); let dims: Vec<_> = parts.iter(...
identifier_body
nvptx.rs
use super::{InlineAsmArch, InlineAsmType}; use rustc_macros::HashStable_Generic; def_reg_class! { Nvptx NvptxInlineAsmRegClass { reg16, reg32, reg64, } } impl NvptxInlineAsmRegClass { pub fn valid_modifiers(self, _arch: InlineAsmArch) -> &'static [char] { &[] } pub...
pub fn suggest_modifier( self, _arch: InlineAsmArch, _ty: InlineAsmType, ) -> Option<(char, &'static str)> { None } pub fn default_modifier(self, _arch: InlineAsmArch) -> Option<(char, &'static str)> { None } pub fn supported_types( self, ...
{ None }
identifier_body
nvptx.rs
use super::{InlineAsmArch, InlineAsmType}; use rustc_macros::HashStable_Generic; def_reg_class! { Nvptx NvptxInlineAsmRegClass { reg16, reg32, reg64, } } impl NvptxInlineAsmRegClass { pub fn valid_modifiers(self, _arch: InlineAsmArch) -> &'static [char] { &[] } pub...
def_regs! { // Registers in PTX are declared in the assembly. // There are no predefined registers that one can use. Nvptx NvptxInlineAsmReg NvptxInlineAsmRegClass {} }
} } }
random_line_split
nvptx.rs
use super::{InlineAsmArch, InlineAsmType}; use rustc_macros::HashStable_Generic; def_reg_class! { Nvptx NvptxInlineAsmRegClass { reg16, reg32, reg64, } } impl NvptxInlineAsmRegClass { pub fn
(self, _arch: InlineAsmArch) -> &'static [char] { &[] } pub fn suggest_class(self, _arch: InlineAsmArch, _ty: InlineAsmType) -> Option<Self> { None } pub fn suggest_modifier( self, _arch: InlineAsmArch, _ty: InlineAsmType, ) -> Option<(char, &'static str)> {...
valid_modifiers
identifier_name
no_0113_path_sum_ii.rs
use crate::common::TreeNode; use std::cell::RefCell; use std::rc::Rc; struct Solution; impl Solution { pub fn
(root: Option<Rc<RefCell<TreeNode>>>, sum: i32) -> Vec<Vec<i32>> { let mut ans = Vec::new(); Self::helper(&root, sum, &mut vec![], &mut ans); ans } fn helper( root: &Option<Rc<RefCell<TreeNode>>>, mut sum: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>,...
path_sum
identifier_name
no_0113_path_sum_ii.rs
use crate::common::TreeNode;
use std::rc::Rc; struct Solution; impl Solution { pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, sum: i32) -> Vec<Vec<i32>> { let mut ans = Vec::new(); Self::helper(&root, sum, &mut vec![], &mut ans); ans } fn helper( root: &Option<Rc<RefCell<TreeNode>>>, mut s...
use std::cell::RefCell;
random_line_split
no_0113_path_sum_ii.rs
use crate::common::TreeNode; use std::cell::RefCell; use std::rc::Rc; struct Solution; impl Solution { pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, sum: i32) -> Vec<Vec<i32>> { let mut ans = Vec::new(); Self::helper(&root, sum, &mut vec![], &mut ans); ans } fn helper( ...
} } #[cfg(test)] mod tests { use super::*; use crate::common::tree_node; #[test] fn test_path_sum() { let root = tree_node(TreeNode { val: 5, left: tree_node(TreeNode { val: 4, left: tree_node(TreeNode { val: 11, ...
{ let r = r.borrow(); sum -= r.val; tmp.push(r.val); if sum == 0 && r.left.is_none() && r.right.is_none() { ans.push(tmp.clone()); } if r.left.is_some() { Self::helper(&r.left, sum, tmp, ans); } ...
conditional_block
mod.rs
//! A type is a classification which determines how data is used. #[deny(missing_docs)] mod array_type; mod enums; #[deny(missing_docs)] mod float_type; #[deny(missing_docs)] mod fn_type; #[deny(missing_docs)] mod int_type; #[deny(missing_docs)] mod metadata_type; #[deny(missing_docs)] mod ptr_type; #[deny(missing_doc...
(ty: LLVMTypeRef) -> Self { assert!(!ty.is_null()); Type { ty, _marker: PhantomData, } } // REVIEW: LLVM 5.0+ seems to have removed this function in release mode // and so will fail to link when used. I've decided to remove it from 5.0+ // for now. We sh...
new
identifier_name
mod.rs
//! A type is a classification which determines how data is used. #[deny(missing_docs)] mod array_type; mod enums; #[deny(missing_docs)] mod float_type; #[deny(missing_docs)] mod fn_type; #[deny(missing_docs)] mod int_type; #[deny(missing_docs)] mod metadata_type; #[deny(missing_docs)] mod ptr_type; #[deny(missing_doc...
fn size_of(self) -> Option<IntValue<'ctx>> { if!self.is_sized() { return None; } unsafe { Some(IntValue::new(LLVMSizeOf(self.ty))) } } fn print_to_string(self) -> LLVMString { unsafe { LLVMString::new(LLVMPrintTypeToString(self....
{ unsafe { LLVMTypeIsSized(self.ty) == 1 } }
identifier_body
mod.rs
//! A type is a classification which determines how data is used. #[deny(missing_docs)] mod array_type; mod enums; #[deny(missing_docs)] mod float_type; #[deny(missing_docs)] mod fn_type; #[deny(missing_docs)] mod int_type; #[deny(missing_docs)] mod metadata_type; #[deny(missing_docs)] mod ptr_type; #[deny(missing_doc...
unsafe { Some(IntValue::new(LLVMSizeOf(self.ty))) } } fn print_to_string(self) -> LLVMString { unsafe { LLVMString::new(LLVMPrintTypeToString(self.ty)) } } pub fn get_element_type(self) -> AnyTypeEnum<'ctx> { unsafe { AnyTyp...
{ return None; }
conditional_block
mod.rs
//! A type is a classification which determines how data is used. #[deny(missing_docs)] mod array_type; mod enums; #[deny(missing_docs)] mod float_type; #[deny(missing_docs)] mod fn_type; #[deny(missing_docs)] mod int_type; #[deny(missing_docs)] mod metadata_type; #[deny(missing_docs)] mod ptr_type; #[deny(missing_doc...
_ => LLVMConstNull(self.ty) } } } fn ptr_type(self, address_space: AddressSpace) -> PointerType<'ctx> { unsafe { PointerType::new(LLVMPointerType(self.ty, address_space as u32)) } } fn vec_type(self, size: u32) -> VectorType<'ctx> { ...
unsafe { match LLVMGetTypeKind(self.ty) { LLVMTypeKind::LLVMMetadataTypeKind => LLVMConstPointerNull(self.ty),
random_line_split
ethcore.rs
// Copyright 2015, 2016 Ethcore (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 later version....
(&self, _: Params) -> Result<Value, Error> { to_value(&take_weak!(self.miner).minimal_gas_price()) } fn extra_data(&self, _: Params) -> Result<Value, Error> { to_value(&Bytes::new(take_weak!(self.miner).extra_data())) } fn gas_floor_target(&self, _: Params) -> Result<Value, Error> { to_value(&take_weak!(sel...
min_gas_price
identifier_name
ethcore.rs
// Copyright 2015, 2016 Ethcore (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 later version....
fn min_gas_price(&self, _: Params) -> Result<Value, Error> { to_value(&take_weak!(self.miner).minimal_gas_price()) } fn extra_data(&self, _: Params) -> Result<Value, Error> { to_value(&Bytes::new(take_weak!(self.miner).extra_data())) } fn gas_floor_target(&self, _: Params) -> Result<Value, Error> { to_va...
{ from_params::<(Address,)>(params).and_then(|(author,)| { take_weak!(self.miner).set_author(author); to_value(&true) }) }
identifier_body
ethcore.rs
// Copyright 2015, 2016 Ethcore (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 later version....
pub struct EthcoreClient<M> where M: MinerService, { miner: Weak<M>, } impl<M> EthcoreClient<M> where M: MinerService, { /// Creates new `EthcoreClient`. pub fn new(miner: &Arc<M>) -> Self { EthcoreClient { miner: Arc::downgrade(miner) } } } impl<M> Ethcore for EthcoreClient<M> where M: MinerService +'...
use v1::traits::Ethcore; use v1::types::Bytes; /// Ethcore implementation.
random_line_split
cli.rs
// bitcoin-donation - Generate a Bitcoin address for donations. // Copyright (C) 2017 Cooper Paul EdenDay // // 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, o...
Err(format!("RPC URL '{}' could not be parsed.", v)) } pub fn build_cli<'a>() -> App<'a, 'a> { App::new(NAME) .version(VERSION) .author(AUTHORS) .about(DESCRIPTION) .arg( Arg::with_name("uname") .short("u") .long("username") ...
{ return Ok(()); }
conditional_block
cli.rs
// bitcoin-donation - Generate a Bitcoin address for donations. // Copyright (C) 2017 Cooper Paul EdenDay // // 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, o...
pub fn build_cli<'a>() -> App<'a, 'a> { App::new(NAME) .version(VERSION) .author(AUTHORS) .about(DESCRIPTION) .arg( Arg::with_name("uname") .short("u") .long("username") .help("Bitcoin Core RPC username.") .multipl...
{ if Uri::from_str(&v).is_ok() { return Ok(()); } Err(format!("RPC URL '{}' could not be parsed.", v)) }
identifier_body
cli.rs
// bitcoin-donation - Generate a Bitcoin address for donations. // Copyright (C) 2017 Cooper Paul EdenDay // // 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, o...
(v: String) -> Result<(), String> { if Uri::from_str(&v).is_ok() { return Ok(()); } Err(format!("RPC URL '{}' could not be parsed.", v)) } pub fn build_cli<'a>() -> App<'a, 'a> { App::new(NAME) .version(VERSION) .author(AUTHORS) .about(DESCRIPTION) .arg( ...
validate_uri
identifier_name
cli.rs
// bitcoin-donation - Generate a Bitcoin address for donations. // Copyright (C) 2017 Cooper Paul EdenDay // // 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, o...
.validator(validate_uri), ) .arg( Arg::with_name("no_conf") .short("n") .long("no-config") .help("Ignore the RPC password from the Bitcoin Core config file") .takes_value(false), ) }
.multiple(false) .empty_values(false) .value_name("URL") .default_value("http://localhost:18332/")
random_line_split
lib.rs
use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; use std; use std::fmt; use std::collections::HashMap; use std::convert::TryInto; extern crate num; use std::ops::{AddAssign, SubAssign}; use num::{Zero,One}; type Position =...
return true; } self.memory.write(self.input.read().into()); self.input.fwd(); }, '.' => { self.output.write(self.memory.read().try_into().unwrap()); self.output.fwd(); }, _ => (), ...
',' => { if self.input.ptr == self.input.len() {
random_line_split
lib.rs
use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; use std; use std::fmt; use std::collections::HashMap; use std::convert::TryInto; extern crate num; use std::ops::{AddAssign, SubAssign}; use num::{Zero,One}; type Position =...
(program: &[u8]) -> JumpMap { let mut stack: Vec<usize> = Vec::new(); let mut jumps = JumpMap::new(); let plen = program.len(); let mut pos: Position = 0; while pos < plen { let opcode = program[pos] as char; match opcode { '[' => stack.pu...
_find_jumps
identifier_name
lib.rs
use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; use std; use std::fmt; use std::collections::HashMap; use std::convert::TryInto; extern crate num; use std::ops::{AddAssign, SubAssign}; use num::{Zero,One}; type Position =...
pub fn dec(&mut self) { self.buf[self.ptr] -= T::one(); } pub fn read(&self) -> T { self.buf[self.ptr] } pub fn write(&mut self, val: T) { self.buf[self.ptr] = val; } } #[wasm_bindgen] pub struct Interpreter { program: Buffer<u8>, jumps: JumpMap, memory: ...
{ self.buf[self.ptr] += T::one(); }
identifier_body
backend.rs
use redis::{self, Connection, Commands}; use chrono::Duration; use cache::{CacheError, CacheResult}; use cache::context::CacheContext; // Redis abstraction pub struct CacheBackend { conn: Connection, one_day: i64 } impl CacheBackend { pub fn new(conn: Connection) -> Self { CacheBackend { ...
(&mut self, context: &CacheContext) -> CacheResult<bool> { self.conn.exists(context.get_key()).map_err(CacheError::Redis) } pub fn load_entries(&mut self, context: &CacheContext) -> CacheResult<Vec<String>> { self.conn.lrange(context.get_key(), 0, -1).map_err(CacheError::Redis) } }
is_stored
identifier_name
backend.rs
use redis::{self, Connection, Commands}; use chrono::Duration; use cache::{CacheError, CacheResult}; use cache::context::CacheContext; // Redis abstraction pub struct CacheBackend {
impl CacheBackend { pub fn new(conn: Connection) -> Self { CacheBackend { conn: conn, one_day: Duration::days(1).num_seconds() } } pub fn add_entries(&mut self, context: &CacheContext, items: Vec<String>) -> CacheResult<()> { let mut pipe = redis::pipe(); ...
conn: Connection, one_day: i64 }
random_line_split
backend.rs
use redis::{self, Connection, Commands}; use chrono::Duration; use cache::{CacheError, CacheResult}; use cache::context::CacheContext; // Redis abstraction pub struct CacheBackend { conn: Connection, one_day: i64 } impl CacheBackend { pub fn new(conn: Connection) -> Self { CacheBackend { ...
}
{ self.conn.lrange(context.get_key(), 0, -1).map_err(CacheError::Redis) }
identifier_body
mod.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // 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 ...
// along with this program. If not, see <http://www.gnu.org/licenses/>. //! This module returns a `MemoryRegion` of the data segment, so that it can be //! search as well. use std::env; use std::fs; use std::io::{self, Read}; use communication::{Address, MemoryRegion}; /// Represents the data segment of the cur...
// GNU General Public License for more details. // // You should have received a copy of the GNU General Public License
random_line_split
mod.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // 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 ...
{ pub address: Address, pub memory_region: MemoryRegion, } /// loads the current binary into memory so that its header can be parsed. /// We probably could parse the header from memory, because the program is /// already running, but that would require different code for Linux and /// Windows. fn load_current...
DataSegment
identifier_name
mod.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // 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 ...
#[cfg(target_os = "windows")] mod windows; #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "linux")] pub use self::linux::get_data_segment; #[cfg(target_os = "windows")] pub use self::windows::get_data_segment;
{ let current_program = env::current_exe()?; let mut file = fs::File::open(current_program)?; let mut program = vec![]; file.read_to_end(&mut program)?; Ok(program) }
identifier_body
with_std.rs
use super::{Clock, Reference}; use crate::lib::*; use parking_lot::Mutex; use std::time::SystemTime; /// The default clock that reports [`Instant`]s. pub type DefaultClock = MonotonicClock; /// A mock implementation of a clock tracking [`Instant`]s. All it /// does is keep track of what "now" is by allowing the progr...
} impl Clock for FakeAbsoluteClock { type Instant = Instant; fn now(&self) -> Self::Instant { *self.now.lock() } } /// The monotonic clock implemented by [`Instant`]. #[derive(Clone, Debug, Default)] pub struct MonotonicClock(); impl Reference for Instant { fn duration_since(&self, earlier:...
{ *(self.now.lock()) += by }
identifier_body
with_std.rs
use super::{Clock, Reference}; use crate::lib::*; use parking_lot::Mutex; use std::time::SystemTime; /// The default clock that reports [`Instant`]s. pub type DefaultClock = MonotonicClock; /// A mock implementation of a clock tracking [`Instant`]s. All it /// does is keep track of what "now" is by allowing the progr...
else { Duration::new(0, 0) } } fn saturating_sub(&self, duration: Duration) -> Self { self.checked_sub(duration).unwrap_or(*self) } } impl Clock for MonotonicClock { type Instant = Instant; fn now(&self) -> Self::Instant { Instant::now() } } /// The non-m...
{ *self - earlier }
conditional_block
with_std.rs
use super::{Clock, Reference}; use crate::lib::*; use parking_lot::Mutex; use std::time::SystemTime; /// The default clock that reports [`Instant`]s. pub type DefaultClock = MonotonicClock; /// A mock implementation of a clock tracking [`Instant`]s. All it /// does is keep track of what "now" is by allowing the progr...
type Instant = Instant; fn now(&self) -> Self::Instant { Instant::now() } } /// The non-monotonic clock implemented by [`SystemTime`]. #[derive(Clone, Debug, Default)] pub struct SystemClock(); impl Reference for SystemTime { /// Returns the difference in times between the two /// SystemT...
} } impl Clock for MonotonicClock {
random_line_split
with_std.rs
use super::{Clock, Reference}; use crate::lib::*; use parking_lot::Mutex; use std::time::SystemTime; /// The default clock that reports [`Instant`]s. pub type DefaultClock = MonotonicClock; /// A mock implementation of a clock tracking [`Instant`]s. All it /// does is keep track of what "now" is by allowing the progr...
(&self, duration: Duration) -> Self { self.checked_sub(duration).unwrap_or(*self) } } impl Clock for MonotonicClock { type Instant = Instant; fn now(&self) -> Self::Instant { Instant::now() } } /// The non-monotonic clock implemented by [`SystemTime`]. #[derive(Clone, Debug, Default)]...
saturating_sub
identifier_name
day_3.rs
pub use tdd_kata::map_kata::day_3::HashMap; #[test] fn it_should_create_a_new_empty_map() { let map = HashMap::new(10); assert!(map.is_empty()); assert_eq!(map.size(), 0); } #[test] fn
() { let mut map = HashMap::new(10); let old_size = map.size(); map.put(1,1); assert_eq!(map.size(), old_size+1); } #[test] #[ignore] fn it_should_contain_put_value() { let mut map = HashMap::new(10); map.put(1,1); assert!(map.contains(1)); } #[test] #[ignore] fn it_should_not_increase_...
it_should_increase_map_size_when_put
identifier_name