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
oneshot.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 ...
ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst) }; // Now that we've got ownership of our state, figure out what to do // about it. match state { EMPTY => unreachable!(), // our task used for select was stolen DATA => Ok(t...
// of it (may fail)
random_line_split
oneshot.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 ...
pub fn drop_port(&mut self) { match self.state.swap(DISCONNECTED, Ordering::SeqCst) { // An empty channel has nothing to do, and a remotely disconnected // channel also has nothing to do b/c we're about to run the drop // glue DISCONNECTED | EMPTY => {} ...
{ match self.state.swap(DISCONNECTED, Ordering::SeqCst) { DATA | DISCONNECTED | EMPTY => {} // If someone's waiting, we gotta wake them up ptr => unsafe { SignalToken::cast_from_uint(ptr).signal(); } } }
identifier_body
oneshot.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 ...
(&mut self, token: SignalToken) -> SelectionResult<T> { let ptr = unsafe { token.cast_to_uint() }; match self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) { EMPTY => SelSuccess, DATA => { drop(unsafe { SignalToken::cast_from_uint(ptr) }); S...
start_selection
identifier_name
oneshot.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 ...
// Not possible, these are one-use channels DATA => unreachable!(), // There is a thread waiting on the other end. We leave the 'DATA' // state inside so it'll pick it up on the other end. ptr => unsafe { SignalToken::cast_from_uint(ptr).sig...
{ Err(self.data.take().unwrap()) }
conditional_block
lib.rs
// Copyright 2016 Matthew Fornaciari <mattforni@gmail.com> //! A dead simple wrapper around file and directory manipulation. //! //! # Usage //! //! This crate is [on crates.io](https://crates.io/crates/touch) and can be //! used by adding `args` to the dependencies in your project's `Cargo.toml`. //! //! ```toml //! [...
(path: &str) -> bool { Path::new(path).exists() }
exists
identifier_name
lib.rs
// Copyright 2016 Matthew Fornaciari <mattforni@gmail.com> //! A dead simple wrapper around file and directory manipulation. //! //! # Usage //! //! This crate is [on crates.io](https://crates.io/crates/touch) and can be //! used by adding `args` to the dependencies in your project's `Cargo.toml`. //! //! ```toml //! [...
{ Path::new(path).exists() }
identifier_body
lib.rs
// Copyright 2016 Matthew Fornaciari <mattforni@gmail.com> //! A dead simple wrapper around file and directory manipulation. //! //! # Usage //! //! This crate is [on crates.io](https://crates.io/crates/touch) and can be //! used by adding `args` to the dependencies in your project's `Cargo.toml`.
//! //! ```toml //! [dependencies] //! touch = "0" //! ``` //! //! and this to your crate root: //! //! ```rust //! extern crate touch; //! ``` //! //! # Example //! //! ```rust //! extern crate touch; //! //! use touch::exists; //! use touch::dir; //! use touch::file; //! //! const DIR: &'static str = "/tmp/touch"; //...
random_line_split
numeric.rs
use std::ops::{Add, Mul, Div, Rem}; use num::{Integer, PrimInt, FromPrimitive, Unsigned}; /// Computes the binomial coefficient (n choose m) /// Returns `None` if an input is invalid pub fn binomial<T: Integer + Clone>(n: &T, m: &T) -> Option<T> { if n.clone() <= T::zero() || m.clone() < T::zero()
else { // Recall (n choose m) = (n choose n-m), so choose the one // which will result in fewer computations if n.clone() - m.clone() >= m.clone() { Some(binom_no_check(n, m)) } else { Some(binom_no_check(n, &(n.clone() - m.clone()))) } } } /// Compu...
{ None }
conditional_block
numeric.rs
use std::ops::{Add, Mul, Div, Rem}; use num::{Integer, PrimInt, FromPrimitive, Unsigned}; /// Computes the binomial coefficient (n choose m) /// Returns `None` if an input is invalid pub fn
<T: Integer + Clone>(n: &T, m: &T) -> Option<T> { if n.clone() <= T::zero() || m.clone() < T::zero() { None } else { // Recall (n choose m) = (n choose n-m), so choose the one // which will result in fewer computations if n.clone() - m.clone() >= m.clone() { Some(bino...
binomial
identifier_name
numeric.rs
use std::ops::{Add, Mul, Div, Rem}; use num::{Integer, PrimInt, FromPrimitive, Unsigned}; /// Computes the binomial coefficient (n choose m) /// Returns `None` if an input is invalid pub fn binomial<T: Integer + Clone>(n: &T, m: &T) -> Option<T> { if n.clone() <= T::zero() || m.clone() < T::zero() { None ...
} sum } /// Same as `binomial` but doesn't check for valid inputs fn binom_no_check<T: Integer + Clone>(n: &T, m: &T) -> T { if m.clone() == T::zero() { T::one() } else { binom_no_check(&(n.clone() - T::one()), &(m.clone() - T::one())) * n.clone() / m.clone() } }
sum = &sum + &(&n % &ten); n = &n / &ten;
random_line_split
numeric.rs
use std::ops::{Add, Mul, Div, Rem}; use num::{Integer, PrimInt, FromPrimitive, Unsigned}; /// Computes the binomial coefficient (n choose m) /// Returns `None` if an input is invalid pub fn binomial<T: Integer + Clone>(n: &T, m: &T) -> Option<T>
/// Computes the least common multiple of the two given integers pub fn lcm<T: Integer + Clone>(n: &T, m: &T) -> T { n.clone() * m.clone() / n.clone().gcd(m) } /// Computes integer powers n^m where m is a primitive integral type pub fn pow_primint<T, U>(n: &T, m: U) -> T where T: Integer + Clone, f...
{ if n.clone() <= T::zero() || m.clone() < T::zero() { None } else { // Recall (n choose m) = (n choose n-m), so choose the one // which will result in fewer computations if n.clone() - m.clone() >= m.clone() { Some(binom_no_check(n, m)) } else { S...
identifier_body
client.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 futures::Future; use std::io::Result; use std::net::Shutdown; use std::path::Path; use tokio_core::reactor::Handle; use tokio_uds::UnixStream; use auth::{Authenticator, AuthError, ServerGuid}; pub struct Bus { inner: UnixStream, } impl Bus { pub fn connect<P...
random_line_split
client.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 futures::Future; use std::io::Result; use std::net::Shutdown; use std::path::Path; use tokio_core::reactor::Handl...
<P, F, T> (path: P, handle: &Handle, auth_strategy: F) -> impl Future<Item = (ServerGuid, Self), Error = (AuthError, Option<Authenticator>)> where P: AsRef<Path>, F: FnOnce(Authenticator) -> T, T: Future<Item = (ServerGuid, Authenticator), ...
connect
identifier_name
client.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 futures::Future; use std::io::Result; use std::net::Shutdown; use std::path::Path; use tokio_core::reactor::Handl...
pub fn disconnect(self) -> Result<()> { self.into_inner().shutdown(Shutdown::Both) } }
{ self.inner }
identifier_body
mod.rs
use std::str::FromStr; use std::collections::HashMap; use std::ops::{BitAnd, BitOr, Shl, Shr, Not}; const DATA: &'static str = include_str!("input.txt"); pub fn main() -> Vec<String> { let s1 = run_circuit(DATA, "a").unwrap(); let s2 = part2(DATA, "a", "b", 956).unwrap(); vec![s1.to_string(), s2.to_string...
fn binary_from_str(a: &str, b: &str, o: &str, f: fn(u16, u16) -> u16) -> Result<Gate, &'static str> { a.parse::<Source>().and_then(|a| { b.parse::<Source>().and_then(|b| { ...
{ a.parse::<Source>().and_then(|a| { o.parse::<Source>().map(|o| { Gate::UnaryOp { src: a, out: o, f: f, } }) }) }
identifier_body
mod.rs
use std::str::FromStr; use std::collections::HashMap; use std::ops::{BitAnd, BitOr, Shl, Shr, Not}; const DATA: &'static str = include_str!("input.txt"); pub fn main() -> Vec<String> { let s1 = run_circuit(DATA, "a").unwrap(); let s2 = part2(DATA, "a", "b", 956).unwrap(); vec![s1.to_string(), s2.to_string...
(s: &str) -> Result<Source, Self::Err> { match s { s if s.is_empty() => Err("empty identifier"), s if (|s: &str| s.chars().all(|c| c.is_digit(10)))(s) => { s.parse::<u16>().map_err(|_| "parse error").map(Source::Pattern) } s if (|s: &str| s.chars()...
from_str
identifier_name
mod.rs
use std::str::FromStr; use std::collections::HashMap; use std::ops::{BitAnd, BitOr, Shl, Shr, Not}; const DATA: &'static str = include_str!("input.txt"); pub fn main() -> Vec<String> { let s1 = run_circuit(DATA, "a").unwrap(); let s2 = part2(DATA, "a", "b", 956).unwrap(); vec![s1.to_string(), s2.to_string...
fn from_str(s: &str) -> Result<Gate, Self::Err> { fn id<T>(x: T) -> T { x }; fn unary_from_str(a: &str, o: &str, f: fn(u16) -> u16) -> Result<Gate, &'static str> { a.parse::<Source>().and_then(|a| { o.parse::<Source>().map(|o| { G...
random_line_split
tempfile.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(tmpdir: &Path, suffix: &str) -> Option<TempDir> { if!tmpdir.is_absolute() { return TempDir::new_in(&os::make_absolute(tmpdir), suffix); } static mut CNT: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT; for _ in range(0u, 1000) { let filename = fo...
new_in
identifier_name
tempfile.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
match self.path { Some(ref p) => { fs::rmdir_recursive(p) } None => Ok(()) } } } impl Drop for TempDir { fn drop(&mut self) { if!self.disarmed { let _ = self.cleanup_dir(); } } } // the tests for this module ne...
fn cleanup_dir(&mut self) -> IoResult<()> { assert!(!self.disarmed); self.disarmed = true;
random_line_split
tempfile.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } // the tests for this module need to change the path using change_dir, // and this doesn't play nicely with other tests so these unit tests are located // in src/test/run-pass/tempfile.rs
{ let _ = self.cleanup_dir(); }
conditional_block
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/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![feature(zero_one)] #![plugin(heapsize_p...
(&self) -> EachIndex<T, I> { each_index(self.begin(), self.end()) } }
each_index
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/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![feature(zero_one)] #![plugin(heapsize_p...
/// Move the end of the range to the target index. /// /// ~~~ignore /// target /// | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ...
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![feature(zero_one)] #![plugin(heapsize_p...
/// Adjust the beginning offset and the length by the supplied deltas. #[inline] pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) { self.begin = self.begin + begin_delta; self.length = self.length + length_delta; } /// Set the begin and length values. #[inline] ...
{ self.length = target - self.begin; }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![feature(zero_one)] #![plugin(heapsize_p...
} } /// Methods for `Range`s with indices based on integer values impl<T: Int, I: RangeIndex<Index=T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { each_index(self.begin(), self.end()) } }
{ Range::new(begin, end - begin) }
conditional_block
semigroup.rs
//! Module for holding the Semigroup typeclass definition and typeclass instances //! //! You can, for example, combine tuples. #![cfg_attr( feature = "std", doc = r#" # Examples ``` #[macro_use] extern crate frunk; # fn main() { use frunk::Semigroup; let t1 = (1, 2.5f32, String::from("hi"), Some(3)); let t2...
#[test] #[cfg(feature = "std")] fn test_hashmap() { let mut v1: HashMap<i32, Option<String>> = HashMap::new(); v1.insert(1, Some("Hello".to_owned())); v1.insert(2, Some("Goodbye".to_owned())); v1.insert(4, None); let mut v2: HashMap<i32, Option<String>> = HashMap::n...
{ assert_eq!(Any(3).combine(&Any(5)), Any(7)); assert_eq!(Any(true).combine(&Any(false)), Any(true)); }
identifier_body
semigroup.rs
//! Module for holding the Semigroup typeclass definition and typeclass instances //! //! You can, for example, combine tuples. #![cfg_attr( feature = "std", doc = r#" # Examples ``` #[macro_use] extern crate frunk; # fn main() { use frunk::Semigroup; let t1 = (1, 2.5f32, String::from("hi"), Some(3)); let t2...
} )* } } simple_all_impls! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 } macro_rules! simple_any_impls { ($($tr:ty)*) => { $( impl Semigroup for Any<$tr> { fn combine(&self, other: &Self) -> Self { let x = self.0; ...
fn combine(&self, other: &Self) -> Self { let x = self.0; let y = other.0; All(x.bitand(y)) }
random_line_split
semigroup.rs
//! Module for holding the Semigroup typeclass definition and typeclass instances //! //! You can, for example, combine tuples. #![cfg_attr( feature = "std", doc = r#" # Examples ``` #[macro_use] extern crate frunk; # fn main() { use frunk::Semigroup; let t1 = (1, 2.5f32, String::from("hi"), Some(3)); let t2...
<T>(pub T); /// Wrapper type for boolean that acts as a bitwise || combination #[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)] pub struct Any<T>(pub T); /// A Semigroup is a class of thing that has a definable combine operation pub trait Semigroup { /// Associative operation taking which combi...
All
identifier_name
count.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::Peekable; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if s...
} } // fn peekable(self) -> Peekable<Self> where Self: Sized { // Peekable{iter: self, peeked: None} // } // fn count(self) -> usize where Self: Sized { // // Might overflow. // self.fold(0, |cnt, _| cnt + 1) // } } } } type T = i32; Iterator_impl!(T); // impl...
} else { None::<Self::Item>
random_line_split
count.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::Peekable; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if s...
}
{ let a: A<T> = A { begin: 0, end: 10 }; let mut peekable: Peekable<A<T>> = a.peekable(); peekable.next(); assert_eq!(peekable.count(), 9); }
identifier_body
count.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::Peekable; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if s...
() { let a: A<T> = A { begin: 0, end: 10 }; let mut peekable: Peekable<A<T>> = a.peekable(); peekable.next(); assert_eq!(peekable.count(), 9); } }
count_test2
identifier_name
at_exit_imp.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use collections::vec::Vec; use core::atomic; use core::mem; use exclusive::Exclusive; type Queue = Exclusive<Vec<proc():Send>>; static mut QUEUE: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT; static mut RUNNING: atomic::AtomicBool = atomic::INIT_ATOMIC_BOOL; pub fn init() { let state: Box<Queue> = box Exclusiv...
use alloc::boxed::Box; use collections::MutableSeq;
random_line_split
at_exit_imp.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn run() { let cur = unsafe { rtassert!(!RUNNING.load(atomic::SeqCst)); let queue = QUEUE.swap(0, atomic::SeqCst); rtassert!(queue!= 0); let queue: Box<Queue> = mem::transmute(queue); let v = mem::replace(&mut *queue.lock(), Vec::new()); v }; for to_ru...
{ unsafe { // Note that the check against 0 for the queue pointer is not atomic at // all with respect to `run`, meaning that this could theoretically be a // use-after-free. There's not much we can do to protect against that, // however. Let's just assume a well-behaved runtime and ...
identifier_body
at_exit_imp.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let cur = unsafe { rtassert!(!RUNNING.load(atomic::SeqCst)); let queue = QUEUE.swap(0, atomic::SeqCst); rtassert!(queue!= 0); let queue: Box<Queue> = mem::transmute(queue); let v = mem::replace(&mut *queue.lock(), Vec::new()); v }; for to_run in cur.int...
run
identifier_name
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::Bindings::DOMExceptionBinding::...
, } }; error!("Error at {}:{}:{} {}", error_info.filename, error_info.lineno, error_info.column, error_info.message); if dispatch_event { GlobalScope::from_context(cx) .report_an_error(error_info, value.handle()); } } /// Throw an...
{ panic!("Uncaught exception: failed to stringify primitive"); }
conditional_block
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::Bindings::DOMExceptionBinding::...
NotFound, /// HierarchyRequestError DOMException HierarchyRequest, /// WrongDocumentError DOMException WrongDocument, /// InvalidCharacterError DOMException InvalidCharacter, /// NotSupportedError DOMException NotSupported, /// InUseAttributeError DOMException InUseAttribute,...
/// NotFoundError DOMException
random_line_split
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::Bindings::DOMExceptionBinding::...
Error::QuotaExceeded => DOMErrorName::QuotaExceededError, Error::TypeMismatch => DOMErrorName::TypeMismatchError, Error::InvalidModification => DOMErrorName::InvalidModificationError, Error::Type(message) => { assert!(!JS_IsExceptionPending(cx)); throw_type_error(...
{ let code = match result { Error::IndexSize => DOMErrorName::IndexSizeError, Error::NotFound => DOMErrorName::NotFoundError, Error::HierarchyRequest => DOMErrorName::HierarchyRequestError, Error::WrongDocument => DOMErrorName::WrongDocumentError, Error::InvalidCharacter => D...
identifier_body
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::Bindings::DOMExceptionBinding::...
{ /// The error message. pub message: String, /// The file name. pub filename: String, /// The line number. pub lineno: c_uint, /// The column number. pub column: c_uint, } impl ErrorInfo { unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) ...
ErrorInfo
identifier_name
error.rs
use std::fmt; use std::error::Error; use super::Rule; #[derive(Debug, PartialEq, Clone)]
pub col: usize, pub expected: Vec<Rule>, } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.expected.is_empty() { write!(f, "no token expected at line {} col {}", self.line, self.col) } else { write!(f, "expected token...
pub struct ParseError { pub line: usize,
random_line_split
error.rs
use std::fmt; use std::error::Error; use super::Rule; #[derive(Debug, PartialEq, Clone)] pub struct ParseError { pub line: usize, pub col: usize, pub expected: Vec<Rule>, } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.expected.is_empty() { ...
} }
{ "expected tokens which were not found" }
conditional_block
error.rs
use std::fmt; use std::error::Error; use super::Rule; #[derive(Debug, PartialEq, Clone)] pub struct ParseError { pub line: usize, pub col: usize, pub expected: Vec<Rule>, } impl fmt::Display for ParseError { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.expected.is_empty() { write!(f, "no token expected at line {} col {}", self.line, self.col) } else { write!(f, "expected token(s): {} at line {} col {}", self.expected.iter().map(|r| format!("{}", r)).collec...
fmt
identifier_name
while_early_ret.rs
#![allow(unused_assignments)] // expect-exit-status-1 fn main() -> Result<(),u8> { let mut countdown = 10;
if countdown < 5 { return if countdown > 8 { Ok(()) } else { Err(1) ...
while countdown > 0 {
random_line_split
while_early_ret.rs
#![allow(unused_assignments)] // expect-exit-status-1 fn
() -> Result<(),u8> { let mut countdown = 10; while countdown > 0 { if countdown < 5 { return if countdown > 8 { ...
main
identifier_name
while_early_ret.rs
#![allow(unused_assignments)] // expect-exit-status-1 fn main() -> Result<(),u8> { let mut countdown = 10; while countdown > 0 { if countdown < 5
countdown -= 1 ; } Ok(()) } // ISSUE(77553): Originally, this test had `Err(1)` on line 22 (instead of `Ok(())`) and // `std::process::exit(2)` on line 26 (instead of `Err(1)`); and this worked as expected on Linux // and MacOS. But on Windows (MSVC, at least), the call to ...
{ return if countdown > 8 { Ok(()) } else { Err(1) } ; }
conditional_block
while_early_ret.rs
#![allow(unused_assignments)] // expect-exit-status-1 fn main() -> Result<(),u8>
else { Err(1) } ; } countdown -= 1 ; } Ok(()) } // ISSUE(77553): Originally, this test had `Err(1)` on line 22 (instead of `Ok(())`) and // `std::process::exit(2)` on line 26 (instea...
{ let mut countdown = 10; while countdown > 0 { if countdown < 5 { return if countdown > 8 { Ok(...
identifier_body
day_7.rs
use alloc::raw_vec::RawVec; use std::ops::{Deref, DerefMut}; use std::{slice, ptr}; use std::intrinsics::assume; pub struct Stack<T> { size: usize, buf: RawVec<T> } impl <T> Deref for Stack<T> { type Target = [T]; fn deref(&self) -> &[T] { unsafe { slice::from_raw_parts(self.as_p...
(&mut self, v: T) -> bool { if self.size == self.buf.cap() { false } else { unsafe { let end = self.as_mut_ptr().offset(self.size as isize); ptr::write(end, v); } self.size += 1; true } } ...
push
identifier_name
day_7.rs
use alloc::raw_vec::RawVec; use std::ops::{Deref, DerefMut}; use std::{slice, ptr}; use std::intrinsics::assume; pub struct Stack<T> { size: usize, buf: RawVec<T> } impl <T> Deref for Stack<T> { type Target = [T]; fn deref(&self) -> &[T] { unsafe { slice::from_raw_parts(self.as_p...
} impl <T> Stack<T> { pub fn new(max_size: usize) -> Stack<T> { Stack { size: 0, buf: RawVec::with_capacity(max_size) } } pub fn size(&self) -> usize { self.size } pub fn is_empty(&self) -> bool { self.size == 0 } pub fn push(&mut self, v: T) -> bool { i...
{ unsafe { let p = self.buf.ptr(); assume(!p.is_null()); slice::from_raw_parts_mut(self.as_ptr(), self.size) } }
identifier_body
day_7.rs
use alloc::raw_vec::RawVec; use std::ops::{Deref, DerefMut}; use std::{slice, ptr}; use std::intrinsics::assume; pub struct Stack<T> { size: usize, buf: RawVec<T> } impl <T> Deref for Stack<T> { type Target = [T]; fn deref(&self) -> &[T] { unsafe { slice::from_raw_parts(self.as_p...
pub fn new(max_size: usize) -> Stack<T> { Stack { size: 0, buf: RawVec::with_capacity(max_size) } } pub fn size(&self) -> usize { self.size } pub fn is_empty(&self) -> bool { self.size == 0 } pub fn push(&mut self, v: T) -> bool { if self.size == self.buf.c...
} } impl <T> Stack<T> {
random_line_split
day_7.rs
use alloc::raw_vec::RawVec; use std::ops::{Deref, DerefMut}; use std::{slice, ptr}; use std::intrinsics::assume; pub struct Stack<T> { size: usize, buf: RawVec<T> } impl <T> Deref for Stack<T> { type Target = [T]; fn deref(&self) -> &[T] { unsafe { slice::from_raw_parts(self.as_p...
} unsafe fn as_ptr(&self) -> *mut T { let p = self.buf.ptr(); assume(!p.is_null()); p } }
{ self.size -= 1; unsafe { Some(ptr::read(self.get_unchecked(self.size))) } }
conditional_block
lib.rs
// Copyright 2016 The Gfx-rs Developers. // // 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 ag...
<C: RenderFormat>(wb: winit::WindowBuilder) -> Result<(MetalWindow, Device, Factory, RenderTargetView<Resources, C>), InitError> { init_raw(wb, C::get_format()) .map(|(window, device, factory, color)| (window, device, factory, Typed::new(color))) } /// Initialize with a given size. Raw format versio...
init
identifier_name
lib.rs
// Copyright 2016 The Gfx-rs Developers. // // 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 ag...
layer: layer, drawable: daddr, backbuffer: addr, pool: Cell::new(NSAutoreleasePool::alloc().init()) }; (*daddr).0 = drawable.0; (*addr).0 = drawable.texture().0; Ok((window, device, factory, color)) } }
let drawable = layer.next_drawable().unwrap(); let window = MetalWindow { window: winit_window,
random_line_split
ascii.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...
delegating_ascii_methods!(); } #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] impl AsciiExt for [u8] { type Owned = Vec<u8>; delegating_ascii_methods!(); } #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] impl AsciiExt for str { type Owned = String; delegati...
random_line_split
mut.rs
#[allow(dead_code)] #[derive(Clone, Copy)] struct Book { // `&'static str` is a reference to a string allocated in read only memory author: &'static str, title: &'static str, year: u32, } // This function takes a reference to a book fn borrow_book(book: &Book) { println!("I borrowed {} {} edition",...
fn main() { // An immutable Book let geb = Book { // string literals have type `&'static str` author: "Douglas Hofstadter", title: "Gödel, Escher, Bach", year: 1979, }; // Immutably borrow `geb` borrow_book(&geb); // Error! Can't borrow an immutable object as ...
{ // the fields of the book can be modified book.year = 2014; }
identifier_body
mut.rs
#[allow(dead_code)] #[derive(Clone, Copy)] struct Book { // `&'static str` is a reference to a string allocated in read only memory author: &'static str, title: &'static str, year: u32, } // This function takes a reference to a book fn borrow_book(book: &Book) { println!("I borrowed {} {} edition",...
(book: &mut Book) { // the fields of the book can be modified book.year = 2014; } fn main() { // An immutable Book let geb = Book { // string literals have type `&'static str` author: "Douglas Hofstadter", title: "Gödel, Escher, Bach", year: 1979, }; // Immutabl...
new_edition
identifier_name
mut.rs
#[allow(dead_code)] #[derive(Clone, Copy)] struct Book {
author: &'static str, title: &'static str, year: u32, } // This function takes a reference to a book fn borrow_book(book: &Book) { println!("I borrowed {} {} edition", book.title, book.year); } // This function takes a reference to a mutable book fn new_edition(book: &mut Book) { // the fields of ...
// `&'static str` is a reference to a string allocated in read only memory
random_line_split
mod.rs
pub mod button; pub mod frame; pub mod region; pub struct Widget; impl Widget { fn
() -> Widget { Widget } } pub trait UIObject { fn get_name(&self) -> String; //fn get_object_type() -> String; //fn is_object_type(type_: &str) -> String; fn draw(&self); } pub trait ParentObject: UIObject { /// Returns the object's parent object. fn get_parent(); } pub trait Visi...
new_inherited
identifier_name
mod.rs
pub mod button; pub mod frame; pub mod region; pub struct Widget; impl Widget { fn new_inherited() -> Widget
} pub trait UIObject { fn get_name(&self) -> String; //fn get_object_type() -> String; //fn is_object_type(type_: &str) -> String; fn draw(&self); } pub trait ParentObject: UIObject { /// Returns the object's parent object. fn get_parent(); } pub trait VisibleRegion: ParentObject { /// R...
{ Widget }
identifier_body
lib.rs
//! # SabiWM - 錆WM (Rust WM) //! //! SabiWM is a window manager written entirely in safe Rust. //! It aims to be a reliable, highly customizable tiling window manager //! in the spirit of XMonad, I3, bspwm and the like. //! //! ## SabiWM Lib //! //! The core part of SabiWM is its library. It serves as a //! learning ba...
} } /// Initialize the logger pub fn initialize_logger() -> Result<()> { let xdg = BaseDirectories::with_prefix("sabiwm") .chain_err(|| "unable to get xdg base directory")?; let path = xdg.place_cache_file("sabiwm.log") .chain_err(|| "unable to get path for log file")?; fern::Dispatch::n...
initialize_logger() .chain_err(|| "unable to initialize logger")?; let xcb = backend::Xcb::new()?; let mut workspace: core::Workspace<u32> = core::Workspace::new(0, "Main", None); loop { match xcb.event() { Event::WindowCreated(window) => { if !xcb.is_window...
identifier_body
lib.rs
//! # SabiWM - 錆WM (Rust WM) //! //! SabiWM is a window manager written entirely in safe Rust. //! It aims to be a reliable, highly customizable tiling window manager //! in the spirit of XMonad, I3, bspwm and the like. //! //! ## SabiWM Lib //! //! The core part of SabiWM is its library. It serves as a //! learning ba...
_ => (), } } } /// Initialize the logger pub fn initialize_logger() -> Result<()> { let xdg = BaseDirectories::with_prefix("sabiwm") .chain_err(|| "unable to get xdg base directory")?; let path = xdg.place_cache_file("sabiwm.log") .chain_err(|| "unable to get path for log f...
workspace = workspace.remove(window); }
conditional_block
lib.rs
//! # SabiWM - 錆WM (Rust WM) //! //! SabiWM is a window manager written entirely in safe Rust. //! It aims to be a reliable, highly customizable tiling window manager //! in the spirit of XMonad, I3, bspwm and the like. //! //! ## SabiWM Lib //! //! The core part of SabiWM is its library. It serves as a //! learning ba...
-> Result<()> { let xdg = BaseDirectories::with_prefix("sabiwm") .chain_err(|| "unable to get xdg base directory")?; let path = xdg.place_cache_file("sabiwm.log") .chain_err(|| "unable to get path for log file")?; fern::Dispatch::new() .format(|out, message, record| { ...
itialize_logger()
identifier_name
lib.rs
//! # SabiWM - 錆WM (Rust WM) //! //! SabiWM is a window manager written entirely in safe Rust. //! It aims to be a reliable, highly customizable tiling window manager //! in the spirit of XMonad, I3, bspwm and the like. //! //! ## SabiWM Lib //! //! The core part of SabiWM is its library. It serves as a //! learning ba...
Event::WindowCreated(window) => { if!xcb.is_window(window) { continue; } xcb.resize_window(window, 50, 50); workspace = workspace.add(window); } Event::WindowClosed(window) => { worksp...
loop { match xcb.event() {
random_line_split
testworklet.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/. */ // check-tidy: no specs after this line use crate::dom::bindings::codegen::Bindings::TestWorkletBinding::TestWork...
}
{ let id = self.worklet.worklet_id(); let pool = ScriptThread::worklet_thread_pool(); pool.test_worklet_lookup(id, String::from(key)) .map(DOMString::from) }
identifier_body
testworklet.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/. */ // check-tidy: no specs after this line use crate::dom::bindings::codegen::Bindings::TestWorkletBinding::TestWork...
use crate::dom::bindings::str::USVString; use crate::dom::promise::Promise; use crate::dom::window::Window; use crate::dom::worklet::Worklet; use crate::dom::workletglobalscope::WorkletGlobalScopeType; use crate::realms::InRealm; use crate::script_thread::ScriptThread; use dom_struct::dom_struct; use std::rc::Rc; #[do...
use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::reflector::Reflector; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString;
random_line_split
testworklet.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/. */ // check-tidy: no specs after this line use crate::dom::bindings::codegen::Bindings::TestWorkletBinding::TestWork...
(&self, key: DOMString) -> Option<DOMString> { let id = self.worklet.worklet_id(); let pool = ScriptThread::worklet_thread_pool(); pool.test_worklet_lookup(id, String::from(key)) .map(DOMString::from) } }
Lookup
identifier_name
mod.rs
use chrono::{offset::Utc, DateTime}; use diesel::{self, pg::PgConnection}; mod password; use self::password::Password; pub use self::password::{ CreationError as PasswordCreationError, PlaintextPassword, ValidationError, VerificationError, }; use schema::local_auth; use user::{AuthenticatedUser, UnauthenticatedUs...
if self.user_id!= user.id { return Err(VerificationError::Process); } self.password.verify(password).map(|_| AuthenticatedUser { id: user.id, primary_email: user.primary_email, created_at: user.created_at, updated_at: user.updated_at, ...
random_line_split
mod.rs
use chrono::{offset::Utc, DateTime}; use diesel::{self, pg::PgConnection}; mod password; use self::password::Password; pub use self::password::{ CreationError as PasswordCreationError, PlaintextPassword, ValidationError, VerificationError, }; use schema::local_auth; use user::{AuthenticatedUser, UnauthenticatedUs...
( user: &UnverifiedUser, password: PlaintextPassword, password2: PlaintextPassword, ) -> Result<Self, PasswordCreationError> { use self::password::Validate; let password = password .validate() .and_then(|password| password.compare(password2))?; ...
new_from_two
identifier_name
mod.rs
use chrono::{offset::Utc, DateTime}; use diesel::{self, pg::PgConnection}; mod password; use self::password::Password; pub use self::password::{ CreationError as PasswordCreationError, PlaintextPassword, ValidationError, VerificationError, }; use schema::local_auth; use user::{AuthenticatedUser, UnauthenticatedUs...
self.password.verify(password).map(|_| AuthenticatedUser { id: user.id, primary_email: user.primary_email, created_at: user.created_at, updated_at: user.updated_at, }) } } /// This type exists to create new `LocalAuth` record in the database. #[deri...
{ return Err(VerificationError::Process); }
conditional_block
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/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead o...
pub enum TimerSource { /// The event was requested from a window (ScriptTask). FromWindow(PipelineId), /// The event was requested from a worker (DedicatedGlobalWorkerScope). FromWorker } /// The id to be used for a TimerEvent is defined by the corresponding TimerEventRequest. #[derive(PartialEq, Eq, C...
/// Describes the task that requested the TimerEvent. #[derive(Copy, Clone, HeapSizeOf, Deserialize, Serialize)]
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead o...
{} /// Amount of milliseconds. pub type MsDuration = Length<Milliseconds, u64>; /// Amount of nanoseconds. pub type NsDuration = Length<Nanoseconds, u64>; /// Returns the duration since an unspecified epoch measured in ms. pub fn precise_time_ms() -> MsDuration { Length::new(time::precise_time_ns() / (1000 * 100...
Nanoseconds
identifier_name
semistatement-in-lambda.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 ...
|| if true { 1 } else { 2 } * 3; // The following is invalid and parses as `if true { 1 } else { 2 }; *3` // if true { 1 } else { 2 } * 3 }
random_line_split
semistatement-in-lambda.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 ...
* 3; // The following is invalid and parses as `if true { 1 } else { 2 }; *3` // if true { 1 } else { 2 } * 3 }
{ 2 }
conditional_block
semistatement-in-lambda.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 ...
() { // Test that lambdas behave as unary expressions with block-like expressions -if true { 1 } else { 2 } * 3; || if true { 1 } else { 2 } * 3; // The following is invalid and parses as `if true { 1 } else { 2 }; *3` // if true { 1 } else { 2 } * 3 }
main
identifier_name
semistatement-in-lambda.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 ...
{ // Test that lambdas behave as unary expressions with block-like expressions -if true { 1 } else { 2 } * 3; || if true { 1 } else { 2 } * 3; // The following is invalid and parses as `if true { 1 } else { 2 }; *3` // if true { 1 } else { 2 } * 3 }
identifier_body
dom.rs
/// Returns the address of this node, for debugging purposes. #[inline] pub fn id(&self) -> usize { self.0 } } /// Simple trait to provide basic information about the type of an element. /// /// We avoid exposing the full type id, since computing it in the general case /// would be difficult for ...
/// looking at the element and its ancestors. (This argument is used /// to implement matching of `:lang()` against snapshots.) fn match_element_lang(&self,
random_line_split
dom.rs
be /// performed on this node is to compare it to another opaque handle or to another /// OpaqueNode. /// /// Layout and Graphics use this to safely represent nodes for comparison purposes. /// Because the script task's GC does not trace layout, node data cannot be safely stored in layout /// data structures. Also, la...
/// Mutably borrows the ElementData. fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> { self.get_data().map(|x| x.borrow_mut()) } /// Whether we should skip any root- or item-based display property /// blockification on this element. (This function exists so that Gecko /// ...
{ self.get_data().map(|x| x.borrow()) }
identifier_body
dom.rs
be /// performed on this node is to compare it to another opaque handle or to another /// OpaqueNode. /// /// Layout and Graphics use this to safely represent nodes for comparison purposes. /// Because the script task's GC does not trace layout, node data cannot be safely stored in layout /// data structures. Also, la...
(&self) -> bool { self.is_element() || self.is_text_node() } } /// A node iterator that only returns node that don't need layout. pub struct LayoutIterator<T>(pub T); impl<T, I> Iterator for LayoutIterator<T> where T: Iterator<Item=I>, I: NodeInfo, { type Item = I; fn next(&mut self) -> Option<I...
needs_layout
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod ast; mod errors; use std::{iter::Peekable, str::Chars}; pub use ast::{DocblockAST, DocblockField, DocblockSection}; use com...
/// Read until the end of the line. fn parse_free_text_line(&mut self) -> ParseResult<SpanString> { let start = self.offset; let free_text = self.take_while(|c| c!= &'\n'); let end = self.offset; Ok(SpanString::new(Span::new(start, end), free_text)) } fn complete_previ...
{ let start = self.offset; let name = self.take_while(is_field_name_char); if name.is_empty() { self.errors.push(Diagnostic::error( SyntaxError::ExpectedFieldName, self.current_position(), )); return Err(()); } l...
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod ast; mod errors; use std::{iter::Peekable, str::Chars}; pub use ast::{DocblockAST, DocblockField, DocblockSection}; use com...
(&self) -> &TextSource { &self.0 } pub fn to_text_source(self) -> TextSource { self.0 } } type ParseResult<T> = Result<T, ()>; /// Parses a docblock's contents. /// /// Expectes to be passed a string containing the _contents_ of a docblock (with /// the leading `/*` and trailing `*/` alrea...
text_source
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod ast; mod errors; use std::{iter::Peekable, str::Chars}; pub use ast::{DocblockAST, DocblockField, DocblockSection}; use com...
} } self.complete_previous_section(); Ok(()) } /// Consume the ` * ` left margin, returning true/false indicating if we /// read the full margin without reaching the end of the input. fn parse_margin(&mut self) -> ParseResult<bool> { self.consume_whitespace...
{ self.in_progress_text = Some(free_text); }
conditional_block
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod ast; mod errors; use std::{iter::Peekable, str::Chars}; pub use ast::{DocblockAST, DocblockField, DocblockSection}; use com...
SyntaxError::ExpectedFieldName, self.current_position(), )); return Err(()); } let end = self.offset; Ok(SpanString::new(Span::new(start, end), name)) } /// Read until the end of the line. fn parse_free_text_line(&mut self) -> ...
random_line_split
common.rs
/* * Copyright 2015 Ben Ashford * * 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 ...
(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { if!self.is_empty() { try!(formatter.write_str("?")); try!(formatter.write_str(&self.0.iter().map(|&(ref k, ref v)| { format!("{}={}", k, v.0) }).join("&"))); } Ok(()) } } ...
fmt
identifier_name
common.rs
/* * Copyright 2015 Ben Ashford * * 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 ...
} impl<'a> fmt::Display for Options<'a> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { if!self.is_empty() { try!(formatter.write_str("?")); try!(formatter.write_str(&self.0.iter().map(|&(ref k, ref v)| { format!("{}={}", k, v.0) ...
{ self.0.push((key, val.into())); }
identifier_body
common.rs
/* * Copyright 2015 Ben Ashford * * 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 ...
} } /// Values for `default_operator` query parameters pub enum DefaultOperator { And, Or } impl From<DefaultOperator> for OptionVal { fn from(from: DefaultOperator) -> OptionVal { OptionVal(match from { DefaultOperator::And => "and", DefaultOperator::Or => "or" ...
random_line_split
E0617.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { unsafe { printf(::std::ptr::null(), 0f32); //~^ ERROR can't pass `f32` to variadic function //~| HELP cast the value to `c_double` printf(::std::ptr::null(), 0i8); //~^ ERROR can't pass `i8` to variadic function //~| HELP cast the value to `c_int` printf(...
main
identifier_name
E0617.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} }
{ unsafe { printf(::std::ptr::null(), 0f32); //~^ ERROR can't pass `f32` to variadic function //~| HELP cast the value to `c_double` printf(::std::ptr::null(), 0i8); //~^ ERROR can't pass `i8` to variadic function //~| HELP cast the value to `c_int` printf(::s...
identifier_body
E0617.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
// <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-tidy-linelength extern { fn printf(c: *const i8,...); } fn main() { unsafe { printf(::std::ptr::null(), 0f32); //~^ ER...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
lib.rs
//#![allow(dead_code, unused_must_use, unused_imports, unstable)] // Temporary warning removal until old_io is updated et al. #![feature(io, collections, core)] #[macro_use] extern crate log; use factory::{Record, RecordResult}; use std::string::ToString; pub mod controller; pub mod factory; mod utils; struct
{ factory: factory::Factory, } impl Txtdb { pub fn new(factory: factory::Factory) -> Txtdb { Txtdb { factory: factory, } } #[allow(dead_code, unused_must_use, unused_variables)] fn add<T: ToString>(&mut self, record: T) -> RecordResult<u64, String> { //! Add a...
Txtdb
identifier_name
lib.rs
//#![allow(dead_code, unused_must_use, unused_imports, unstable)] // Temporary warning removal until old_io is updated et al. #![feature(io, collections, core)] #[macro_use] extern crate log; use factory::{Record, RecordResult}; use std::string::ToString; pub mod controller; pub mod factory; mod utils; struct Txt...
}
{ //! Searches for the first instance of a record that matches the one provided. //! Returns the id of the record in the database. // TODO, how do you create a `Record` if you don't know the id? // Since we aren't using it, should we document not having the id in there? // ...
identifier_body
lib.rs
//#![allow(dead_code, unused_must_use, unused_imports, unstable)] // Temporary warning removal until old_io is updated et al. #![feature(io, collections, core)] #[macro_use] extern crate log; use factory::{Record, RecordResult}; use std::string::ToString; pub mod controller; pub mod factory; mod utils; struct Txt...
} #[allow(dead_code, unused_must_use, unused_variables)] fn find_id(id: u64) -> RecordResult<Record, String> { //! Searches for a record with the id provided. //! Returns a copy of the record. // 1. Read each line? // 2. Check if the ID matches // 3. Return ...
#[allow(dead_code, unused_must_use, unused_variables)] fn remove(&mut self, record: Record) -> RecordResult<u64, String> { //! Finds and removes the first instance of a record that matches the one provided. //! Returns the id of the record it removes. Err("Not implemented yet".to_string(...
random_line_split
mod.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distribute...
self.bsrr.reset(port); } /// Sets the port speed for the GPIO pin. /// /// # Panics /// /// Port must be a value between [0..15] or the kernel will panic. fn set_speed(&mut self, speed: Speed, port: u8) { self.ospeedr.set_speed(speed, port); } /// Get the current po...
/// Port must be a value between [0..15] or the kernel will panic. fn reset_bit(&mut self, port: u8) {
random_line_split
mod.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distribute...
} impl Deref for GPIO { type Target = RawGPIO; fn deref(&self) -> &Self::Target { &*(self.0) } } impl DerefMut for GPIO { fn deref_mut(&mut self) -> &mut Self::Target { &mut *(self.0) } } impl RawGPIO { /// Enable a GPIO group. This must be done before setting any pins withi...
{ RawGPIO::enable(group); }
identifier_body
mod.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distribute...
(&self, port: u8) -> AlternateFunction { match port { 0...7 => self.afrl.get_function(port), 8...15 => self.afrh.get_function(port), _ => panic!("AFRL/AFRH::set_function - specified port must be between [0..15]!"), } } }
get_function
identifier_name
boxed.rs
use std::any::{self, Any}; use std::ops::Deref; use neon_runtime::raw; use neon_runtime::external; use crate::context::{Context, FinalizeContext}; use crate::context::internal::Env; use crate::handle::{Managed, Handle}; use crate::types::internal::ValueInternal; use crate::types::Value; type BoxAny = Box<dyn Any + S...
fn downcast<Other: Value>(env: Env, other: Other) -> Option<Self> { let local = other.to_raw(); let data = unsafe { maybe_external_deref(env, local) }; // Attempt to downcast the `Option<&BoxAny>` to `Option<*const T>` data.and_then(|v| v.downcast_ref()) .map(|raw_data|...
{ let data = unsafe { maybe_external_deref(env, other.to_raw()) }; data.map(|v| v.is::<T>()).unwrap_or(false) }
identifier_body
boxed.rs
use std::any::{self, Any}; use std::ops::Deref; use neon_runtime::raw; use neon_runtime::external; use crate::context::{Context, FinalizeContext}; use crate::context::internal::Env; use crate::handle::{Managed, Handle}; use crate::types::internal::ValueInternal; use crate::types::Value; type BoxAny = Box<dyn Any + S...
/// } /// /// fn print_path(mut cx: FunctionContext) -> JsResult<JsUndefined> { /// let path = cx.argument::<JsBox<PathBuf>>(0)?; /// /// println!("{}", path.display()); /// /// Ok(cx.undefined()) /// } /// ``` /// /// Passing a user defined struct wrapped in a `RefCell` for mutability. This /// pattern is ...
random_line_split
boxed.rs
use std::any::{self, Any}; use std::ops::Deref; use neon_runtime::raw; use neon_runtime::external; use crate::context::{Context, FinalizeContext}; use crate::context::internal::Env; use crate::handle::{Managed, Handle}; use crate::types::internal::ValueInternal; use crate::types::Value; type BoxAny = Box<dyn Any + S...
} } impl<T: Finalize> Finalize for std::sync::Mutex<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { if let Ok(v) = self.into_inner() { v.finalize(cx); } } } impl<T: Finalize> Finalize for std::sync::RwLock<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { ...
{ v.finalize(cx); }
conditional_block
boxed.rs
use std::any::{self, Any}; use std::ops::Deref; use neon_runtime::raw; use neon_runtime::external; use crate::context::{Context, FinalizeContext}; use crate::context::internal::Env; use crate::handle::{Managed, Handle}; use crate::types::internal::ValueInternal; use crate::types::Value; type BoxAny = Box<dyn Any + S...
<'a, C: Context<'a>>(self, cx: &mut C) { (*self).finalize(cx); } } impl<T: Finalize> Finalize for std::rc::Rc<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { if let Ok(v) = std::rc::Rc::try_unwrap(self) { v.finalize(cx); } } } impl<T: Finalize> Finalize for std...
finalize
identifier_name
assignability-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let x = ~[0,1,2,3]; // Call a method do x.iterate() |y| { assert!(x[*y] == *y); true }; // Call a parameterized function assert_eq!(length(x.clone()), x.len()); // Call a parameterized function, with type arguments that require // a borrow assert_eq!(length::<int, &[int...
{ let mut len = 0; do x.iterate() |_y| { len += 1; true }; return len; }
identifier_body
assignability-trait.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 ...
assert_eq!(length::<int, &[int]>(z), z.len()); }
random_line_split
assignability-trait.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, f: &fn(x: &A) -> bool) -> bool { self.iter().advance(f) } } fn length<A, T: iterable<A>>(x: T) -> uint { let mut len = 0; do x.iterate() |_y| { len += 1; true }; return len; } pub fn main() { let x = ~[0,1,2,3]; // Call a method do x.iterate() |y| { assert!(x[*y] == *y); tr...
iterate
identifier_name
console.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::ConsoleBinding; use dom::bindings::codegen::Bindings::ConsoleBinding::Consol...
(self, messages: Vec<DOMString>) { for message in messages { println!("{}", message); } } fn Warn(self, messages: Vec<DOMString>) { for message in messages { println!("{}", message); } } fn Error(self, messages: Vec<DOMString>) { for mess...
Info
identifier_name
console.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::ConsoleBinding; use dom::bindings::codegen::Bindings::ConsoleBinding::Consol...
fn Warn(self, messages: Vec<DOMString>) { for message in messages { println!("{}", message); } } fn Error(self, messages: Vec<DOMString>) { for message in messages { println!("{}", message); } } fn Assert(self, condition: bool, message: Optio...
}
random_line_split