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
raw.rs
extern crate libsqlite3_sys as ffi; extern crate libc; use std::ffi::{CString, CStr}; use std::io::{stderr, Write}; use std::{ptr, str}; use result::*; use result::Error::DatabaseError; #[allow(missing_debug_implementations, missing_copy_implementations)] pub struct RawConnection { pub internal_connection: *mut ...
Ok(()) } } pub fn rows_affected_by_last_query(&self) -> usize { unsafe { ffi::sqlite3_changes(self.internal_connection) as usize } } pub fn last_error_message(&self) -> String { let c_str = unsafe { CStr::from_ptr(ffi::sqlite3_errmsg(self.internal_connection)) }; ...
{ let mut err_msg = ptr::null_mut(); let query = try!(CString::new(query)); let callback_fn = None; let callback_arg = ptr::null_mut(); unsafe { ffi::sqlite3_exec( self.internal_connection, query.as_ptr(), callback_fn, ...
identifier_body
raw.rs
extern crate libsqlite3_sys as ffi; extern crate libc; use std::ffi::{CString, CStr}; use std::io::{stderr, Write}; use std::{ptr, str}; use result::*; use result::Error::DatabaseError; #[allow(missing_debug_implementations, missing_copy_implementations)] pub struct RawConnection { pub internal_connection: *mut ...
}; match connection_status { ffi::SQLITE_OK => Ok(RawConnection { internal_connection: conn_pointer, }), err_code => { let message = super::error_message(err_code); Err(ConnectionError::BadConnection(message.into())) ...
let database_url = try!(CString::new(database_url)); let connection_status = unsafe { ffi::sqlite3_open(database_url.as_ptr(), &mut conn_pointer)
random_line_split
lib.rs
use std::path::{Path, PathBuf}; use std::fs::{self, ReadDir, DirEntry}; use std::io::Error; pub struct DeepWalk { root: PathBuf, } impl DeepWalk { pub fn new<P: AsRef<Path>>(root: P) -> Self { DeepWalk { root: root.as_ref().to_path_buf() } } }
type IntoIter = Iter; fn into_iter(self) -> Iter { Iter { root: Some(self.root), dirs: Vec::new() } } } pub struct Iter { root: Option<PathBuf>, dirs: Vec<ReadDir>, } // TODO: Remove and implement Iterator for DeepWalk. impl Iterator for Iter { type Item = Result<DirEntry, Error>; ...
impl IntoIterator for DeepWalk { type Item = Result<DirEntry, Error>;
random_line_split
lib.rs
use std::path::{Path, PathBuf}; use std::fs::{self, ReadDir, DirEntry}; use std::io::Error; pub struct DeepWalk { root: PathBuf, } impl DeepWalk { pub fn new<P: AsRef<Path>>(root: P) -> Self { DeepWalk { root: root.as_ref().to_path_buf() } } } impl IntoIterator for DeepWalk { type Item = Resu...
() { for val in get_test_roots() { assert_eq!(DeepWalk::new(val).root, Path::new(val)); } } #[test] fn deep_walk_into_iterator() { for val in get_test_roots() { assert_eq!(DeepWalk::new(val).into_iter().root, Some(PathBuf::from(val))); } } }
deep_walk_new
identifier_name
lib.rs
use std::path::{Path, PathBuf}; use std::fs::{self, ReadDir, DirEntry}; use std::io::Error; pub struct DeepWalk { root: PathBuf, } impl DeepWalk { pub fn new<P: AsRef<Path>>(root: P) -> Self { DeepWalk { root: root.as_ref().to_path_buf() } } } impl IntoIterator for DeepWalk { type Item = Resu...
#[test] fn deep_walk_into_iterator() { for val in get_test_roots() { assert_eq!(DeepWalk::new(val).into_iter().root, Some(PathBuf::from(val))); } } }
{ for val in get_test_roots() { assert_eq!(DeepWalk::new(val).root, Path::new(val)); } }
identifier_body
udptransport.rs
#[feature(struct_variant)]; #[feature(macro_rules)]; use osc::{OscType, OscMessage, OscWriter, OscReader}; use rpc::{ServerId, LogEntry, AppendEntriesRpc, AppendEntriesResponseRpc, RequestVoteRpc, RequestVoteResponseRpc, RaftRpc, AppendEntries, AppendEntriesResponse, RequestVote, RequestVoteRes...
(&self, sender: ServerId, argsVec: ~[OscType]) -> RequestVoteRpc { let mut args = argsVec.move_iter(); let term: int = args.next().unwrap().unwrap_int() as int; let candidateId: ServerId = from_str::<ServerId>(args.next().unwrap().unwrap_string()).unwrap(); let lastLogIndex: int = args.next().unwrap().u...
parseRequestVote
identifier_name
udptransport.rs
#[feature(struct_variant)]; #[feature(macro_rules)]; use osc::{OscType, OscMessage, OscWriter, OscReader}; use rpc::{ServerId, LogEntry, AppendEntriesRpc, AppendEntriesResponseRpc, RequestVoteRpc, RequestVoteResponseRpc, RaftRpc, AppendEntries, AppendEntriesResponse, RequestVote, RequestVoteRes...
// AppendEntries {term: int, leaderId: ServerId, prevLogIndex: int, // entries: ~[LogEntry], leaderCommitIndex: int}, fn parseAppendEntries(&self, sender: ServerId, argsVec: ~[OscType]) -> AppendEntriesRpc { let mut args = argsVec.move_iter(); let term = args.next().unwrap().unwrap_int() as int; le...
{ return match msg.address { ~"/appendEntries" => AppendEntries(self.parseAppendEntries(sender, msg.arguments)), ~"/requestVote" => RequestVote(self.parseRequestVote(sender, msg.arguments)), _ => fail!("woops no implementation for {}", msg.address) }; }
identifier_body
udptransport.rs
#[feature(struct_variant)]; #[feature(macro_rules)]; use osc::{OscType, OscMessage, OscWriter, OscReader}; use rpc::{ServerId, LogEntry, AppendEntriesRpc, AppendEntriesResponseRpc, RequestVoteRpc, RequestVoteResponseRpc, RaftRpc, AppendEntries, AppendEntriesResponse, RequestVote, RequestVoteRes...
prevLogIndex: prevLogIndex, prevLogTerm: prevLogTerm, entries: entries, leaderCommitIndex: leaderCommitIndex}; } // RequestVote {term: int, candidateId: ServerId, lastLogIndex: int, // lastLogTerm: int} fn parseRequestVote(&self, sender: ServerId, argsVec: ~[...
random_line_split
configure.rs
// Copyright 2020 The Exonum Team // // 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 i...
(&mut self, instance_id: InstanceId, params: Vec<u8>) -> Self::Output { const METHOD_DESCRIPTOR: MethodDescriptor<'static> = MethodDescriptor::new(CONFIGURE_INTERFACE_NAME, 0); self.generic_call_mut(instance_id, METHOD_DESCRIPTOR, params) } fn apply_config(&mut self, instance_id: In...
verify_config
identifier_name
configure.rs
// Copyright 2020 The Exonum Team // // 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 i...
}
{ const METHOD_DESCRIPTOR: MethodDescriptor<'static> = MethodDescriptor::new(CONFIGURE_INTERFACE_NAME, 1); self.generic_call_mut(instance_id, METHOD_DESCRIPTOR, params) }
identifier_body
configure.rs
// Copyright 2020 The Exonum Team // // 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 i...
/// So the service instance should save them by itself if it is important for /// the service business logic. /// /// This method can be triggered at any time and does not follow the general transaction /// execution workflow, so the errors returned might be ignored. /// /// # Execution poli...
random_line_split
abstract-const-as-cast-4.rs
// check-pass #![feature(generic_const_exprs)] #![allow(incomplete_features)] trait Trait {} pub struct EvaluatableU128<const N: u128>; struct HasCastInTraitImpl<const N: usize, const M: u128>; impl<const O: usize> Trait for HasCastInTraitImpl<O, { O as u128 }> {} pub fn use_trait_impl<const N: usize>() where Evalua...
<T: Trait>() {} assert_impl::<HasCastInTraitImpl<N, { N as u128 }>>(); assert_impl::<HasCastInTraitImpl<N, { N as _ }>>(); assert_impl::<HasCastInTraitImpl<12, { 12 as u128 }>>(); assert_impl::<HasCastInTraitImpl<13, 13>>(); } pub fn use_trait_impl_2<const N: usize>() where EvaluatableU128<{N as _}>:, ...
assert_impl
identifier_name
abstract-const-as-cast-4.rs
// check-pass #![feature(generic_const_exprs)] #![allow(incomplete_features)] trait Trait {} pub struct EvaluatableU128<const N: u128>; struct HasCastInTraitImpl<const N: usize, const M: u128>; impl<const O: usize> Trait for HasCastInTraitImpl<O, { O as u128 }> {} pub fn use_trait_impl<const N: usize>() where Evalua...
fn main() {}
assert_impl::<HasCastInTraitImpl<N, { N as _ }>>(); assert_impl::<HasCastInTraitImpl<12, { 12 as u128 }>>(); assert_impl::<HasCastInTraitImpl<13, 13>>(); }
random_line_split
abstract-const-as-cast-4.rs
// check-pass #![feature(generic_const_exprs)] #![allow(incomplete_features)] trait Trait {} pub struct EvaluatableU128<const N: u128>; struct HasCastInTraitImpl<const N: usize, const M: u128>; impl<const O: usize> Trait for HasCastInTraitImpl<O, { O as u128 }> {} pub fn use_trait_impl<const N: usize>() where Evalua...
fn main() {}
{ fn assert_impl<T: Trait>() {} assert_impl::<HasCastInTraitImpl<N, { N as u128 }>>(); assert_impl::<HasCastInTraitImpl<N, { N as _ }>>(); assert_impl::<HasCastInTraitImpl<12, { 12 as u128 }>>(); assert_impl::<HasCastInTraitImpl<13, 13>>(); }
identifier_body
static-reference-to-fn-2.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 finished(_: &mut StateMachineIter) -> Option<(&'static str)> { return None; } fn state_iter() -> StateMachineIter<'static> { StateMachineIter { statefn: &state1 //~ ERROR borrowed value does not live long enough } } fn main() { let mut it = state_iter(); println!("{}",it.next()); ...
{ self_.statefn = &finished; //~^ ERROR borrowed value does not live long enough return Some("state3"); }
identifier_body
static-reference-to-fn-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct StateMachine...
// http://rust-lang.org/COPYRIGHT. //
random_line_split
static-reference-to-fn-2.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 ...
(self_: &mut StateMachineIter) -> Option<&'static str> { self_.statefn = &state2; //~^ ERROR borrowed value does not live long enough return Some("state1"); } fn state2(self_: &mut StateMachineIter) -> Option<(&'static str)> { self_.statefn = &state3; //~^ ERROR borrowed value does not live long en...
state1
identifier_name
scene.rs
// This is a part of Sonorous. // Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! Scene management. use std::io::timer::sleep; use std::time::Duration; use sdl::get_ticks; use ui::common::Ticker; /// Options used by the scene to customize the scene ...
{ /// If specified, limits the number of `Scene::tick` calls per second to this value. /// `run_scene` ensures this limitation by sleeping after each tick as needed. pub tpslimit: Option<uint>, /// If specified, limits the number of `Scene::render` calls per second to this value. /// Due to the imp...
SceneOptions
identifier_name
scene.rs
// This is a part of Sonorous. // Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! Scene management. use std::io::timer::sleep; use std::time::Duration; use sdl::get_ticks; use ui::common::Ticker; /// Options used by the scene to customize the scene ...
} /// A command returned by `Scene`'s `tick` method. pub enum SceneCommand { /// Continues displaying this scene. Continue, /// Pushes a new `Scene` to the scene stack, making it the active scene. The current scene is /// stopped (after calling `deactivate`) until the new scene returns `PopScene` comm...
{ SceneOptions { fpslimit: Some(fps), ..self } }
identifier_body
scene.rs
// This is a part of Sonorous. // Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! Scene management. use std::io::timer::sleep; use std::time::Duration; use sdl::get_ticks; use ui::common::Ticker; /// Options used by the scene to customize the scene ...
impl SceneOptions { /// Creates default options for the scene. pub fn new() -> SceneOptions { SceneOptions { tpslimit: None, fpslimit: None } } /// Replaces `tpslimit` field with given value. pub fn tpslimit(self, tps: uint) -> SceneOptions { SceneOptions { tpslimit: Some(tps),..sel...
}
random_line_split
scene.rs
// This is a part of Sonorous. // Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! Scene management. use std::io::timer::sleep; use std::time::Duration; use sdl::get_ticks; use ui::common::Ticker; /// Options used by the scene to customize the scene ...
_ => {} } match result { SceneCommand::Continue => { panic!("impossible"); } SceneCommand::Push(newscene) => { stack.push(current); current = newscene; } SceneCommand::Replace => { ...
{ let opts = current.scene_options(); let mintickdelay = opts.tpslimit.map_or(0, |tps| 1000 / tps); let interval = opts.fpslimit.map_or(0, |fps| 1000 / fps); let mut ticker = Ticker::with_interval(interval); loop { let t...
conditional_block
associated-types-eq-3.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 ...
baz(&a); //~^ ERROR type mismatch resolving //~| expected usize //~| found struct `Bar` }
random_line_split
associated-types-eq-3.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let a = 42; foo1(a); //~^ ERROR type mismatch resolving //~| expected usize //~| found struct `Bar` baz(&a); //~^ ERROR type mismatch resolving //~| expected usize //~| found struct `Bar` }
main
identifier_name
trait-inheritance-auto.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 ...
<T:Quux>(a: &T) { assert_eq!(a.f(), 10); assert_eq!(a.g(), 20); assert_eq!(a.h(), 30); } pub fn main() { let a = &A { x: 3 }; f(a); }
f
identifier_name
trait-inheritance-auto.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 ...
trait Quux: Foo + Bar + Baz { } struct A { x: isize } impl Foo for A { fn f(&self) -> isize { 10 } } impl Bar for A { fn g(&self) -> isize { 20 } } impl Baz for A { fn h(&self) -> isize { 30 } } fn f<T:Quux>(a: &T) { assert_eq!(a.f(), 10); assert_eq!(a.g(), 20); assert_eq!(a.h(), 30); } pub fn main() {...
trait Baz { fn h(&self) -> isize; }
random_line_split
trait-inheritance-auto.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 f<T:Quux>(a: &T) { assert_eq!(a.f(), 10); assert_eq!(a.g(), 20); assert_eq!(a.h(), 30); } pub fn main() { let a = &A { x: 3 }; f(a); }
{ 30 }
identifier_body
stylesheet.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 {Namespace, Prefix}; use context::QuirksMode; use cssparser::{Parser, ParserInput, RuleListParser}; use error_...
{ /// The lock used for user-agent stylesheets. pub shared_lock: SharedRwLock, /// The user or user agent stylesheets. pub user_or_user_agent_stylesheets: Vec<DocumentStyleSheet>, /// The quirks mode stylesheet. pub quirks_mode_stylesheet: DocumentStyleSheet, } /// A set of namespaces applying...
UserAgentStylesheets
identifier_name
stylesheet.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 {Namespace, Prefix}; use context::QuirksMode; use cssparser::{Parser, ParserInput, RuleListParser}; use error_...
Arc::ptr_eq(&self.0, &other.0) } } impl ToMediaListKey for DocumentStyleSheet { fn to_media_list_key(&self) -> MediaListKey { self.0.to_media_list_key() } } impl StylesheetInDocument for DocumentStyleSheet { fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin { self.0.ori...
impl PartialEq for DocumentStyleSheet { fn eq(&self, other: &Self) -> bool {
random_line_split
stylesheet.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 {Namespace, Prefix}; use context::QuirksMode; use cssparser::{Parser, ParserInput, RuleListParser}; use error_...
/// Records that the stylesheet has been explicitly disabled through the /// CSSOM. /// /// Returns whether the the call resulted in a change in disabled state. /// /// Disabled stylesheets remain in the document, but their rules are not /// added to the Stylist. pub fn set_disabled(&s...
{ self.disabled.load(Ordering::SeqCst) }
identifier_body
test.rs
use quickcheck::{TestResult, quickcheck}; use rand::Rng; use super::{integer_value, regex_value}; use expectest::prelude::*; use pact_matching::s; #[test] fn validates_integer_value() { fn prop(s: String) -> TestResult { let mut rng = ::rand::thread_rng(); if rng.gen() && s.chars().any(|ch|!ch.is_n...
quickcheck(prop as fn(_) -> _); expect!(integer_value(s!("1234"))).to(be_ok()); expect!(integer_value(s!("1234x"))).to(be_err()); } #[test] fn validates_regex_value() { expect!(regex_value(s!("1234"))).to(be_ok()); expect!(regex_value(s!("["))).to(be_err()); }
random_line_split
test.rs
use quickcheck::{TestResult, quickcheck}; use rand::Rng; use super::{integer_value, regex_value}; use expectest::prelude::*; use pact_matching::s; #[test] fn validates_integer_value() { fn prop(s: String) -> TestResult { let mut rng = ::rand::thread_rng(); if rng.gen() && s.chars().any(|ch|!ch.is_n...
() { expect!(regex_value(s!("1234"))).to(be_ok()); expect!(regex_value(s!("["))).to(be_err()); }
validates_regex_value
identifier_name
test.rs
use quickcheck::{TestResult, quickcheck}; use rand::Rng; use super::{integer_value, regex_value}; use expectest::prelude::*; use pact_matching::s; #[test] fn validates_integer_value() { fn prop(s: String) -> TestResult { let mut rng = ::rand::thread_rng(); if rng.gen() && s.chars().any(|ch|!ch.is_n...
{ expect!(regex_value(s!("1234"))).to(be_ok()); expect!(regex_value(s!("["))).to(be_err()); }
identifier_body
tables.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Analyze tracing data for edenscm //! //! This is edenscm application specific. It's not a general purposed library. use serde_json::Valu...
"args" => { if let Ok(args) = serde_json::from_str::<Vec<String>>(value) { // Normalize the first argument to "hg". let mut full = "hg".to_string(); fo...
{ if let Ok(names) = serde_json::from_str::<Vec<String>>(value) { let name = names.get(0).cloned().unwrap_or_default(); row.insert("parent".into(), name.into()); } ...
conditional_block
tables.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Analyze tracing data for edenscm //! //! This is edenscm application specific. It's not a general purposed library. use serde_json::Valu...
(span: &TreeSpan<&str>, row: &mut Row) { for (&name, &value) in span.meta.iter() { match name { // Those keys are likely generated. Skip them. "module_path" | "cat" | "line" | "name" => {} // Attempt to convert it to an integer (since tracing data is // strin...
extract_span
identifier_name
tables.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Analyze tracing data for edenscm //! //! This is edenscm application specific. It's not a general purposed library. use serde_json::Valu...
{ for (&name, &value) in span.meta.iter() { match name { // Those keys are likely generated. Skip them. "module_path" | "cat" | "line" | "name" => {} // Attempt to convert it to an integer (since tracing data is // string only). _ => match value.p...
identifier_body
tables.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Analyze tracing data for edenscm //! //! This is edenscm application specific. It's not a general purposed library. use serde_json::Valu...
} _ => {} } } } // The "log:command-row" event is used by code that wants to // log to columns of the main command row easily. "log:command-row" if span.is...
}
random_line_split
lib.rs
#![crate_name = "graphics"] #![deny(missing_docs)] #![deny(missing_copy_implementations)] //! A library for 2D graphics that works with multiple back-ends. //! //! Piston-Graphics was started in 2014 by Sven Nilsen to test //! back-end agnostic design for 2D in Rust. //! This means generic code can be reused across pr...
<G>( image: &<G as Graphics>::Texture, transform: math::Matrix2d, g: &mut G ) where G: Graphics { Image::new().draw(image, &Default::default(), transform, g); } /// Draws ellipse. pub fn ellipse<R: Into<types::Rectangle>, G>( color: types::Color, rect: R, transform: math::Matrix2d, ...
image
identifier_name
lib.rs
#![crate_name = "graphics"] #![deny(missing_docs)] #![deny(missing_copy_implementations)] //! A library for 2D graphics that works with multiple back-ends. //! //! Piston-Graphics was started in 2014 by Sven Nilsen to test //! back-end agnostic design for 2D in Rust. //! This means generic code can be reused across pr...
{ Text::new_color(color, font_size) .draw(text, cache, &Default::default(), transform, g) }
identifier_body
lib.rs
#![crate_name = "graphics"] #![deny(missing_docs)] #![deny(missing_copy_implementations)] //! A library for 2D graphics that works with multiple back-ends. //! //! Piston-Graphics was started in 2014 by Sven Nilsen to test //! back-end agnostic design for 2D in Rust. //! This means generic code can be reused across pr...
pub mod text; pub mod triangulation; pub mod math; pub mod deform; pub mod grid; pub mod radians { //! Reexport radians helper trait from vecmath pub use vecmath::traits::Radians; } /// Clears the screen. pub fn clear<G>( color: types::Color, g: &mut G ) where G: Graphics { g.clear_color(color); ...
pub mod image; pub mod types; pub mod modular_index;
random_line_split
cluster.rs
//! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2) //! functionality of connection pools. To get more details about creating r2d2 pools //! please refer to original documentation. use std::iter::Iterator; use query::QueryBuilder; use client::{CDRS, Session}; use error::{Error as CEr...
(&self, connection: &mut Self::Connection) -> Result<(), Self::Error> { let query = QueryBuilder::new("SELECT * FROM system.peers;").finalize(); connection.query(query, false, false).map(|_| ()) } fn has_broken(&self, _connection: &mut Self::Connection) -> bool { false } } #[cfg(t...
is_valid
identifier_name
cluster.rs
//! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2) //! functionality of connection pools. To get more details about creating r2d2 pools //! please refer to original documentation. use std::iter::Iterator; use query::QueryBuilder; use client::{CDRS, Session}; use error::{Error as CEr...
} impl<T: Authenticator + Send + Sync +'static, X: CDRSTransport + Send + Sync +'static> r2d2::ManageConnection for ClusterConnectionManager<T, X> { type Connection = Session<T, X>; type Error = CError; fn connect(&self) -> Result<Self::Connection, Self::Error> { let transport_res: CResu...
{ ClusterConnectionManager { load_balancer: load_balancer, authenticator: authenticator, compression: compression, } }
identifier_body
cluster.rs
//! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2) //! functionality of connection pools. To get more details about creating r2d2 pools //! please refer to original documentation. use std::iter::Iterator; use query::QueryBuilder; use client::{CDRS, Session}; use error::{Error as CEr...
X: CDRSTransport + Send + Sync +'static> r2d2::ManageConnection for ClusterConnectionManager<T, X> { type Connection = Session<T, X>; type Error = CError; fn connect(&self) -> Result<Self::Connection, Self::Error> { let transport_res: CResult<X> = self.load_balancer .next() ...
} impl<T: Authenticator + Send + Sync + 'static,
random_line_split
str.rs
s: &str) -> Result<ByteString, ()> { Ok(ByteString::new(s.to_owned().into_bytes())) } } impl ops::Deref for ByteString { type Target = [u8]; fn deref(&self) -> &[u8] { &self.0 } } /// A string that is constructed from a UCS-2 buffer by replacing invalid code /// points with the replace...
ing, PhantomData<*const ()>); impl DOMString { /// Creates a new `DOMString`. pub fn new() -> DOMString { DOMString(String::new(), PhantomData) } /// Creates a new `DOMString` from a `String`. pub fn from_string(s: String) -> DOMString { DOMString(s, PhantomData) } /// App...
tring(Str
identifier_name
str.rs
str(s: &str) -> Result<ByteString, ()> { Ok(ByteString::new(s.to_owned().into_bytes())) } } impl ops::Deref for ByteString { type Target = [u8]; fn deref(&self) -> &[u8] { &self.0 } } /// A string that is constructed from a UCS-2 buffer by replacing invalid code /// points with the rep...
/// Appends a given string slice onto the end of this String. pub fn push_str(&mut self, string: &str) { self.0.push_str(string) } /// Clears this `DOMString`, removing all contents. pub fn clear(&mut self) { self.0.clear() } /// Shortens this String to the specified lengt...
pub fn from_string(s: String) -> DOMString { DOMString(s, PhantomData) }
random_line_split
macro_parser.rs
Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $...
erTtFrame>, top_elts: TokenTreeOrTokenTreeVec, sep: Option<Token>, idx: usize, up: Option<Box<MatcherPos>>, matches: Vec<Vec<Rc<NamedMatch>>>, match_lo: usize, match_cur: usize, match_hi: usize, sp_lo: BytePos, } pub fn count_names(ms: &[TokenTree]) -> usize { ms.iter().fold(0, ...
Vec<Match
identifier_name
macro_parser.rs
Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $...
r_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos) -> Box<MatcherPos> { let match_idx_hi = count_names(&ms[..]); let matches: Vec<_> = (0..match_idx_hi).map(|_| Vec::new()).collect(); Box::new(MatcherPos { stack: vec![], top_elts: TtSeq(ms), sep...
|count, elt| { count + match elt { &TtSequence(_, ref seq) => { seq.num_captures } &TtDelimited(_, ref delim) => { count_names(&delim.tts) } &TtToken(_, MatchNt(..)) => { 1 } &TtT...
identifier_body
macro_parser.rs
//! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] ...
if seq.op == ast::ZeroOrMore { let mut new_ei = ei.clone(); new_ei.match_cur += seq.num_captures; new_ei.idx += 1; //we specifically matched zero repeats. f...
match ei.top_elts.get_tt(idx) { /* need to descend into sequence */ TtSequence(sp, seq) => {
random_line_split
variable.rs
//! A basic `Variable` implementation. //! //! `FunctionBuilderContext`, `FunctionBuilder`, and related types have a `Variable` //! type parameter, to allow frontends that identify variables with //! their own index types to use them directly. Frontends which don't //! can use the `Variable` defined here. use cretonne...
} impl EntityRef for Variable { fn new(index: usize) -> Self { debug_assert!(index < (u32::MAX as usize)); Variable(index as u32) } fn index(self) -> usize { self.0 as usize } }
{ debug_assert!(index < u32::MAX); Variable(index) }
identifier_body
variable.rs
//! A basic `Variable` implementation. //! //! `FunctionBuilderContext`, `FunctionBuilder`, and related types have a `Variable` //! type parameter, to allow frontends that identify variables with //! their own index types to use them directly. Frontends which don't //! can use the `Variable` defined here. use cretonne...
fn index(self) -> usize { self.0 as usize } }
random_line_split
variable.rs
//! A basic `Variable` implementation. //! //! `FunctionBuilderContext`, `FunctionBuilder`, and related types have a `Variable` //! type parameter, to allow frontends that identify variables with //! their own index types to use them directly. Frontends which don't //! can use the `Variable` defined here. use cretonne...
(self) -> usize { self.0 as usize } }
index
identifier_name
enclosure_getters.rs
// This file is part of feed. // // Copyright © 2015-2017 Chris Palmer <pennstate5013@gmail.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 3 of the License, or ...
}
self.mime_type.clone() }
identifier_body
enclosure_getters.rs
// This file is part of feed. // // Copyright © 2015-2017 Chris Palmer <pennstate5013@gmail.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 3 of the License, or ...
/// /// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned() /// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg"; /// /// let enclosure = EnclosureBuilder::new() /// .url(url.as_ref()) /// .mime_type("audio/ogg") /// .finalize() /// .unwrap(); /// ...
/// /// ``` /// use feed::{EnclosureBuilder, EnclosureGetters};
random_line_split
enclosure_getters.rs
// This file is part of feed. // // Copyright © 2015-2017 Chris Palmer <pennstate5013@gmail.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 3 of the License, or ...
&self) -> String { self.length.clone() } /// Get the enclosure type that exists under `Enclosure`. /// /// # Examples /// /// ``` /// use feed::{EnclosureBuilder, EnclosureGetters}; /// /// let enclosure_type = "audio/ogg"; /// /// let url = "http://www.podtrac....
ength(
identifier_name
deref_mut.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cell::RefCell; use core::cell::RefMut; use core::ops::DerefMut; use core::ops::Deref; // pub struct RefCell<T:?Sized> { // borrow: Cell<BorrowFlag>, // value: UnsafeCell<T>, // } // impl<T> RefCell<T>...
}
{ let value: T = 68; let refcell: RefCell<T> = RefCell::<T>::new(value); let mut value_refmut: RefMut<T> = refcell.borrow_mut(); { let deref_mut: &mut T = value_refmut.deref_mut(); *deref_mut = 500; } let value_ref: &T = value_refmut.deref(); assert_eq!(*value_ref, 500); }
identifier_body
deref_mut.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cell::RefCell; use core::cell::RefMut; use core::ops::DerefMut; use core::ops::Deref; // pub struct RefCell<T:?Sized> { // borrow: Cell<BorrowFlag>, // value: UnsafeCell<T>, // } // impl<T> RefCell<T>...
() { let value: T = 68; let refcell: RefCell<T> = RefCell::<T>::new(value); let mut value_refmut: RefMut<T> = refcell.borrow_mut(); { let deref_mut: &mut T = value_refmut.deref_mut(); *deref_mut = 500; } let value_ref: &T = value_refmut.deref(); assert_eq!(*value_ref, 500); } }
deref_test1
identifier_name
deref_mut.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cell::RefCell; use core::cell::RefMut; use core::ops::DerefMut; use core::ops::Deref; // pub struct RefCell<T:?Sized> { // borrow: Cell<BorrowFlag>, // value: UnsafeCell<T>, // } // impl<T> RefCell<T>...
// /// ``` // /// use std::cell::RefCell; // /// // /// let c = RefCell::new(5); // /// // /// let five = c.into_inner(); // /// ``` // #[stable(feature = "rust1", since = "1.0.0")] // #[inline] // pub fn into_inner(self) -> T { // ...
// /// // /// # Examples // ///
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 https://mozilla.org/MPL/2.0/. */ /// A random number generator which shares one instance of an `OsRng`. /// /// A problem with `OsRng`, which is i...
{ rng: Rc<RefCell<ServoRng>>, } // A thread-local RNG, designed as a drop-in replacement for rand::thread_rng. pub fn thread_rng() -> ServoThreadRng { SERVO_THREAD_RNG.with(|t| t.clone()) } thread_local! { static SERVO_THREAD_RNG: ServoThreadRng = ServoThreadRng { rng: Rc::new(RefCell::new(ServoRng::new(...
ServoThreadRng
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/. */ /// A random number generator which shares one instance of an `OsRng`. /// /// A problem with `OsRng`, which is i...
{ let mut bytes = [0; 16]; thread_rng().fill_bytes(&mut bytes); Uuid::from_random_bytes(bytes) }
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 https://mozilla.org/MPL/2.0/. */ /// A random number generator which shares one instance of an `OsRng`. /// /// A problem with `OsRng`, which is i...
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[cfg(target_pointer_width = "64")] use rand::isaac::Isaac64Rng as IsaacWordRng; #[cfg(target_pointer_width = "32")] use rand::isaac::IsaacRng as IsaacWordRng; use rand::os::OsRng; use rand::reseeding::{Reseeder, ReseedingRng}; pub use rand::{Rand, ...
random_line_split
channel.rs
use futures::channel::mpsc; use futures::executor::block_on; use futures::future::poll_fn; use futures::sink::SinkExt; use futures::stream::StreamExt; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread; #[test] fn sequence() { let (tx, rx) = mpsc::channel(1); let amt = 20; let t = thread::spa...
#[test] fn drop_rx() { let (mut tx, rx) = mpsc::channel::<u32>(1); block_on(tx.send(1)).unwrap(); drop(rx); assert!(block_on(tx.send(1)).is_err()); } #[test] fn drop_order() { static DROPS: AtomicUsize = AtomicUsize::new(0); let (mut tx, rx) = mpsc::channel(1); struct A; impl Drop f...
{ let (tx, mut rx) = mpsc::channel::<u32>(1); drop(tx); let f = poll_fn(|cx| rx.poll_next_unpin(cx)); assert_eq!(block_on(f), None) }
identifier_body
channel.rs
use futures::channel::mpsc; use futures::executor::block_on; use futures::future::poll_fn; use futures::sink::SinkExt; use futures::stream::StreamExt; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread; #[test] fn
() { let (tx, rx) = mpsc::channel(1); let amt = 20; let t = thread::spawn(move || block_on(send_sequence(amt, tx))); let list: Vec<_> = block_on(rx.collect()); let mut list = list.into_iter(); for i in (1..=amt).rev() { assert_eq!(list.next(), Some(i)); } assert_eq!(list.next(),...
sequence
identifier_name
channel.rs
use futures::channel::mpsc; use futures::executor::block_on; use futures::future::poll_fn; use futures::sink::SinkExt; use futures::stream::StreamExt; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread; #[test] fn sequence() { let (tx, rx) = mpsc::channel(1); let amt = 20; let t = thread::spa...
static DROPS: AtomicUsize = AtomicUsize::new(0); let (mut tx, rx) = mpsc::channel(1); struct A; impl Drop for A { fn drop(&mut self) { DROPS.fetch_add(1, Ordering::SeqCst); } } block_on(tx.send(A)).unwrap(); assert_eq!(DROPS.load(Ordering::SeqCst), 0); drop...
} #[test] fn drop_order() {
random_line_split
env.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 ...
() -> uint { unsafe { MIN_STACK } } pub fn debug_borrow() -> bool { unsafe { DEBUG_BORROW } } pub fn poison_on_free() -> bool { unsafe { POISON_ON_FREE } }
min_stack
identifier_name
env.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 ...
}
unsafe { POISON_ON_FREE }
random_line_split
env.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 ...
{ unsafe { POISON_ON_FREE } }
identifier_body
tail.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 anyhow::{Context, Error}; use bookmarks::{BookmarkUpdateLog, BookmarkUpdateLogEntry, Freshness}; use cloned::cloned; use context::CoreC...
None => { debug!( ctx.logger(), "tail_entries: no more entries during iteration {}. Sleeping.", iteration ); log_noop_iteration_to_scuba(scuba_sample, repo_id); tokio::time::s...
{ debug!( ctx.logger(), "tail_entries generating, iteration {}", iteration ); let entries_with_queue_size: std::iter::Map<_, _> = add_queue_sizes(entries, queue_size as usize).map(Ok); ...
conditional_block
tail.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 anyhow::{Context, Error}; use bookmarks::{BookmarkUpdateLog, BookmarkUpdateLogEntry, Freshness}; use cloned::cloned; use context::CoreC...
match entries.last().map(|last_item_ref| last_item_ref.id) { Some(last_entry_id) => { debug!( ctx.logger(), "tail_entries generating, iteration {}", iteration ); let entries_with_queue...
{ unfold_forever((0, start_id), move |(iteration, current_id)| { cloned!(ctx, bookmark_update_log, scuba_sample); async move { let entries: Vec<Result<_, Error>> = bookmark_update_log .read_next_bookmark_log_entries( ctx.clone(), cu...
identifier_body
tail.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 anyhow::{Context, Error}; use bookmarks::{BookmarkUpdateLog, BookmarkUpdateLogEntry, Freshness}; use cloned::cloned; use context::CoreC...
<T, F, Fut, Item>( init: T, mut f: F, ) -> impl stream::Stream<Item = Result<Item, Error>> where T: Copy, F: FnMut(T) -> Fut, Fut: future::Future<Output = Result<(Item, T), Error>>, { stream::unfold(init, move |iteration_value| { f(iteration_value).then(move |result| { match ...
unfold_forever
identifier_name
tail.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 anyhow::{Context, Error}; use bookmarks::{BookmarkUpdateLog, BookmarkUpdateLogEntry, Freshness}; use cloned::cloned; use context::CoreC...
pub(crate) fn tail_entries( ctx: CoreContext, start_id: u64, repo_id: RepositoryId, bookmark_update_log: Arc<dyn BookmarkUpdateLog>, scuba_sample: MononokeScubaSampleBuilder, ) -> impl stream::Stream<Item = Result<(BookmarkUpdateLogEntry, QueueSize), Error>> { unfold_forever((0, start_id), move...
}
random_line_split
keycodes.rs
// https://stackoverflow. // com/questions/3202629/where-can-i-find-a-list-of-mac-virtual-key-codes /* keycodes for keys that are independent of keyboard layout */ #![allow(non_upper_case_globals)] #![allow(dead_code)] pub const kVK_Return: u16 = 0x24; pub const kVK_Tab: u16 = 0x30; pub const kVK_Space: u16 = 0x31; ...
pub const kVK_F5: u16 = 0x60; pub const kVK_F6: u16 = 0x61; pub const kVK_F7: u16 = 0x62; pub const kVK_F3: u16 = 0x63; pub const kVK_F8: u16 = 0x64; pub const kVK_F9: u16 = 0x65; pub const kVK_F11: u16 = 0x67; pub const kVK_F13: u16 = 0x69; pub const kVK_F16: u16 = 0x6A; pub const kVK_F14: u16 = 0x6B; pub const kVK_F1...
pub const kVK_Mute: u16 = 0x4A; pub const kVK_F18: u16 = 0x4F; pub const kVK_F19: u16 = 0x50; pub const kVK_F20: u16 = 0x5A;
random_line_split
self_authentication.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or d...
// FIXME - pass secret key of the wallet as an argument let client_id = ClientFullId::new_bls(&mut thread_rng()); // Account Creation println!("\nTrying to create an account..."); match Authenticator::create_acc(secret_0.as_str(), secret_1.as_str(), client_id, || ()) { ...
println!("\n------------ Enter password ---------------"); let _ = std::io::stdin().read_line(&mut secret_1); secret_1 = secret_1.trim().to_string();
random_line_split
self_authentication.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or d...
println!("\n------------ Enter password ---------------"); let _ = std::io::stdin().read_line(&mut secret_1); secret_1 = secret_1.trim().to_string(); // FIXME - pass secret key of the wallet as an argument let client_id = ClientFullId::new_bls(&mut thread_rng()); // Acc...
{ unwrap!(safe_core::utils::logging::init(true)); let mut secret_0 = String::new(); let mut secret_1 = String::new(); println!("\nDo you already have an account created (enter Y for yes)?"); let mut user_option = String::new(); let _ = std::io::stdin().read_line(&mut user_option); user_op...
identifier_body
self_authentication.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or d...
() { unwrap!(safe_core::utils::logging::init(true)); let mut secret_0 = String::new(); let mut secret_1 = String::new(); println!("\nDo you already have an account created (enter Y for yes)?"); let mut user_option = String::new(); let _ = std::io::stdin().read_line(&mut user_option); user...
main
identifier_name
database.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::err::Result; use rusqlite::{params, Connection, OptionalExtension, Row, Statement, NO_PARAMS}; use std::collections::HashMap; use std::path::Path; fn trace(s: &str) { println...
(&mut self, entry: &MediaEntry) -> Result<()> { let stmt = cached_sql!( self.update_entry_stmt, self.db, " insert or replace into media (fname, csum, mtime, dirty) values (?,?,?,?)" ); let sha1_str = entry.sha1.map(hex::encode); stmt.execute(params![ ...
set_entry
identifier_name
database.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::err::Result; use rusqlite::{params, Connection, OptionalExtension, Row, Statement, NO_PARAMS}; use std::collections::HashMap; use std::path::Path; fn trace(s: &str) { println...
} if res.is_err() { self.rollback()?; } res } fn begin(&mut self) -> Result<()> { self.db.execute_batch("begin immediate").map_err(Into::into) } fn commit(&mut self) -> Result<()> { self.db.execute_batch("commit").map_err(Into::into) }...
{ res = Err(e); }
conditional_block
database.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::err::Result; use rusqlite::{params, Connection, OptionalExtension, Row, Statement, NO_PARAMS}; use std::collections::HashMap; use std::path::Path; fn trace(s: &str) { println...
db.pragma_update(None, "page_size", &4096)?; db.pragma_update(None, "legacy_file_format", &false)?; db.pragma_update_and_check(None, "journal_mode", &"wal", |_| Ok(()))?; initial_db_setup(&mut db)?; Ok(db) } fn initial_db_setup(db: &mut Connection) -> Result<()> { // tables already exist? ...
if std::env::var("TRACESQL").is_ok() { db.trace(Some(trace)); }
random_line_split
database.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::err::Result; use rusqlite::{params, Connection, OptionalExtension, Row, Statement, NO_PARAMS}; use std::collections::HashMap; use std::path::Path; fn trace(s: &str) { println...
} fn row_to_entry(row: &Row) -> rusqlite::Result<MediaEntry> { // map the string checksum into bytes let sha1_str: Option<String> = row.get(1)?; let sha1_array = if let Some(s) = sha1_str { let mut arr = [0; 20]; match hex::decode_to_slice(s, arr.as_mut()) { Ok(_) => Some(arr),...
{ self.db .execute_batch("delete from media; update meta set lastUsn = 0, dirMod = 0") .map_err(Into::into) }
identifier_body
lib.rs
// Copyright 2018 Developers of the Rand project. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed /...
html_root_url = "https://rust-random.github.io/rand/" )] #![deny(missing_docs)] #![deny(missing_debug_implementations)] #![no_std] #[cfg(not(target_os = "emscripten"))] mod pcg128; mod pcg64; #[cfg(not(target_os = "emscripten"))] pub use self::pcg128::{Lcg128Xsl64, Mcg128Xsl64, Pcg64, Pcg64Mcg}; pub use self::pcg...
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
random_line_split
core_sphere.rs
extern crate rustcmb; use rustcmb::core::sphere; const SIZE: usize = 4; fn main() { let default_field = sphere::Field::default(); let field = sphere::Field::new(SIZE); let mut mut_field = sphere::Field::new(SIZE); println!("default_field: {:?}", default_field); println!("field: {:?}", field); ...
let mut foo_coef = sphere::Coef::new(SIZE); for l in foo_coef.a_l_begin()..foo_coef.a_l_end() { for m in foo_coef.a_m_begin()..foo_coef.a_m_end(l) { *foo_coef.a_at_mut(l, m) = (l + m + 5) as f64; } } for i in foo_coef.b_l_begin()..foo_coef.b_l_end() { for j in foo_...
random_line_split
core_sphere.rs
extern crate rustcmb; use rustcmb::core::sphere; const SIZE: usize = 4; fn
() { let default_field = sphere::Field::default(); let field = sphere::Field::new(SIZE); let mut mut_field = sphere::Field::new(SIZE); println!("default_field: {:?}", default_field); println!("field: {:?}", field); println!("mut_field: {:?}", mut_field); println!("field size: {:?}", field....
main
identifier_name
core_sphere.rs
extern crate rustcmb; use rustcmb::core::sphere; const SIZE: usize = 4; fn main()
} println!("mut_field after simple indexing: {:?}", mut_field); let mut foo_coef = sphere::Coef::new(SIZE); for l in foo_coef.a_l_begin()..foo_coef.a_l_end() { for m in foo_coef.a_m_begin()..foo_coef.a_m_end(l) { *foo_coef.a_at_mut(l, m) = (l + m + 5) as f64; } } ...
{ let default_field = sphere::Field::default(); let field = sphere::Field::new(SIZE); let mut mut_field = sphere::Field::new(SIZE); println!("default_field: {:?}", default_field); println!("field: {:?}", field); println!("mut_field: {:?}", mut_field); println!("field size: {:?}", field.siz...
identifier_body
compiled.rs
if portable. pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin", "no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type", "hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above", "memory_below", "mo...
// According to the spec, these fields must be >= -1 where -1 means that the feature is not // supported. Using 0 instead of -1 works because we skip sections with length 0. macro_rules! read_nonneg { () => {{ match try!(read_le_u16(file)) as i16 { n if n >= 0 => n as us...
{ macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ); let (bnames, snames, nnames) = if longnames { (boolfnames, stringfnames, numfnames) } else { (boolnames, stringnames, numnames) }; // ...
identifier_body
compiled.rs
if portable. pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin", "no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type", "hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above", "memory_below", "mo...
(file: &mut io::Read, longnames: bool) -> Result<TermInfo, String> { macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ); let (bnames, snames, nnames) = if longnames { (boolfnames, stringfnames, numfnames) ...
parse
identifier_name
compiled.rs
sure if portable. pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin", "no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type", "hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above", "memory_below"...
let numbers_map: HashMap<String, u16> = try!( (0..numbers_count).filter_map(|i| match read_le_u16(file) { Ok(0xFFFF) => None, Ok(n) => Some(Ok((nnames[i].to_string(), n))), Err(e) => Some(Err(e)) }).collect()); let string_map: HashMap<String, Vec<u8>> = if s...
random_line_split
compiled.rs
if portable. pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin", "no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type", "hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above", "memory_below", "mo...
else { snames[i] }; if offset == 0xFFFE { // undocumented: FFFE indicates cap@, which means the capability is not present // unsure if the handling for this is correct return Ok((name.to_string(), Vec::new())); } ...
{ stringfnames[i] }
conditional_block
gstr.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Softwa...
(&mut self) { unsafe { ffi::g_free(self.ptr as gpointer) } } } impl Clone for OwnedGStr { fn clone(&self) -> OwnedGStr { unsafe { OwnedGStr::from_ptr(ffi::g_strdup(self.ptr)) } } } impl PartialEq for OwnedGStr { fn eq(&self, other: &OwnedGStr) -> bool { unsa...
drop
identifier_name
gstr.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Softwa...
inner: CString } impl Deref for Utf8String { type Target = Utf8; fn deref(&self) -> &Utf8 { unsafe { Utf8::from_ptr(self.inner.as_ptr()) } } } impl Utf8String { pub fn new<T>(t: T) -> Result<Utf8String, NulError> where T: Into<String> { let c_str = try!(CString::new(t...
#[inline] fn as_ref(&self) -> &CStr { &self.inner } } pub struct Utf8String {
random_line_split
gstr.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Softwa...
pub unsafe fn from_ptr<'a>(ptr: *const gchar) -> &'a Utf8 { mem::transmute(CStr::from_ptr(ptr)) } } impl AsRef<CStr> for Utf8 { #[inline] fn as_ref(&self) -> &CStr { &self.inner } } pub struct Utf8String { inner: CString } impl Deref for Utf8String { type Target = Utf8; fn der...
{ assert!(s.ends_with("\0"), "static string is not null-terminated: \"{}\"", s); unsafe { Utf8::from_ptr(s.as_ptr() as *const gchar) } }
identifier_body
interval.rs
//! Support for creating futures that represent intervals. //! //! This module contains the `Interval` type which is a stream that will //! resolve at a fixed intervals in future use std::io; use std::time::{Duration, Instant}; use futures::{Poll, Async}; use futures::stream::{Stream}; use reactor::{Remote, Handle};...
#[test] fn fast_forward() { let tm = Timeline::new(); assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(10)), tm.at(1001)); assert_eq!(next_interval(tm.at(7777), tm.at(8888), dur(100)), tm.at(8977)); assert_eq!...
{ let tm = Timeline::new(); assert_eq!(next_interval(tm.at(1), tm.at(2), dur(10)), tm.at(11)); assert_eq!(next_interval(tm.at(7777), tm.at(7788), dur(100)), tm.at(7877)); assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(2100)), ...
identifier_body
interval.rs
//! Support for creating futures that represent intervals. //! //! This module contains the `Interval` type which is a stream that will //! resolve at a fixed intervals in future use std::io; use std::time::{Duration, Instant}; use futures::{Poll, Async}; use futures::stream::{Stream}; use reactor::{Remote, Handle};...
(at: Instant, dur: Duration, handle: &Handle) -> io::Result<Interval> { Ok(Interval { token: try!(TimeoutToken::new(at, &handle)), next: at, interval: dur, handle: handle.remote().clone(), }) } } impl Stream for Interval { type Item = ...
new_at
identifier_name
interval.rs
//! Support for creating futures that represent intervals. //! //! This module contains the `Interval` type which is a stream that will //! resolve at a fixed intervals in future use std::io; use std::time::{Duration, Instant}; use futures::{Poll, Async}; use futures::stream::{Stream}; use reactor::{Remote, Handle};...
else { self.token.update_timeout(&self.handle); Ok(Async::NotReady) } } } impl Drop for Interval { fn drop(&mut self) { self.token.cancel_timeout(&self.handle); } } /// Converts Duration object to raw nanoseconds if possible /// /// This is useful to divide interva...
{ self.next = next_interval(self.next, now, self.interval); self.token.reset_timeout(self.next, &self.handle); Ok(Async::Ready(Some(()))) }
conditional_block
interval.rs
//! Support for creating futures that represent intervals. //! //! This module contains the `Interval` type which is a stream that will //! resolve at a fixed intervals in future use std::io; use std::time::{Duration, Instant}; use futures::{Poll, Async}; use futures::stream::{Stream}; use reactor::{Remote, Handle};...
/// otherwise indicated to fire at. pub struct Interval { token: TimeoutToken, next: Instant, interval: Duration, handle: Remote, } impl Interval { /// Creates a new interval which will fire at `dur` time into the future, /// and will repeat every `dur` interval after /// /// This funct...
/// they will likely fire some granularity after the exact instant that they're
random_line_split
location.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::LocationBinding; use dom::bindings::js::{JSRef, Temporary}; use dom::binding...
else { "?".to_string().append(query.as_slice()) } } } impl Reflectable for Location { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
{ query }
conditional_block
location.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::LocationBinding; use dom::bindings::js::{JSRef, Temporary}; use dom::binding...
(&self) -> DOMString { let query = query_to_str(&self.page.get_url().query); if query.as_slice() == "" { query } else { "?".to_string().append(query.as_slice()) } } } impl Reflectable for Location { fn reflector<'a>(&'a self) -> &'a Reflector { &s...
Search
identifier_name
location.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::LocationBinding; use dom::bindings::js::{JSRef, Temporary}; use dom::binding...
pub fn new(window: &JSRef<Window>, page: Rc<Page>) -> Temporary<Location> { reflect_dom_object(box Location::new_inherited(page), window, LocationBinding::Wrap) } } pub trait LocationMethods { fn Href(&self) -> DOMString; fn Search(&self) -...
Location { reflector_: Reflector::new(), page: page } }
random_line_split
location.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::LocationBinding; use dom::bindings::js::{JSRef, Temporary}; use dom::binding...
fn Search(&self) -> DOMString { let query = query_to_str(&self.page.get_url().query); if query.as_slice() == "" { query } else { "?".to_string().append(query.as_slice()) } } } impl Reflectable for Location { fn reflector<'a>(&'a self) -> &'a Reflect...
{ self.page.get_url().to_str() }
identifier_body
main.rs
extern crate chrono; #[macro_use] extern crate derive_builder; extern crate fern; extern crate inflector; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate rand; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate anyhow; extern crate clap; exter...
{ fern::Dispatch::new() .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) ...
identifier_body
main.rs
extern crate chrono; #[macro_use] extern crate derive_builder; extern crate fern; extern crate inflector; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate rand; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate anyhow; extern crate clap; exter...
} /// This doc string acts as a help message when the user runs '--help' /// as do all doc strings on fields #[derive(Clap)] #[clap(version = "1.0", author = "Viktor H. <viktor.holmgren@gmail.com>")] #[clap(setting = AppSettings::ColoredHelp)] struct Opts { /// A level of verbosity, and can be used multiple times ...
simulator.new_game(); } } // TODO: Implement the rest of the program.
random_line_split
main.rs
extern crate chrono; #[macro_use] extern crate derive_builder; extern crate fern; extern crate inflector; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate rand; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate anyhow; extern crate clap; exter...
{ #[clap(version = "1.3", author = "Viktor H. <viktor.holmgren@gmail.com>")] NewGame(NewGame), //TODO: Add additional subcommands; serve (for server) etc. } /// Subcommand for generating a new world. #[derive(Clap)] struct NewGame { #[clap(short, long, default_value = "genconfig.toml")] config_pat...
SubCommand
identifier_name
main.rs
extern crate serenity; use serenity::prelude::*; use serenity::model::*; use std::env; // Serenity implements transparent sharding in a way that you do not need to // manually handle separate processes or connections manually. // // Transparent sharding is useful for a shared cache. Instead of having caches // with d...
(&self, ctx: Context, msg: Message) { if msg.content == "!ping" { // The current shard needs to be unlocked so it can be read from, as // multiple threads may otherwise attempt to read from or mutate it // concurrently. { let shard = ctx.shard.lock(...
on_message
identifier_name