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
typing.rs
use std::sync::Arc; #[cfg(all(feature = "tokio_compat", not(feature = "tokio")))] use tokio::time::delay_for as sleep; #[cfg(feature = "tokio")] use tokio::time::sleep; use tokio::{ sync::oneshot::{self, error::TryRecvError, Sender}, time::Duration, };
/// It indicates that the current user is currently typing in the channel. /// /// Typing is started by using the [`Typing::start`] method /// and stopped by using the [`Typing::stop`] method. /// Note that on some clients, typing may persist for a few seconds after [`Typing::stop`] is called. /// Typing is also stoppe...
use crate::{error::Result, http::Http}; /// A struct to start typing in a [`Channel`] for an indefinite period of time. ///
random_line_split
typing.rs
use std::sync::Arc; #[cfg(all(feature = "tokio_compat", not(feature = "tokio")))] use tokio::time::delay_for as sleep; #[cfg(feature = "tokio")] use tokio::time::sleep; use tokio::{ sync::oneshot::{self, error::TryRecvError, Sender}, time::Duration, }; use crate::{error::Result, http::Http}; /// A struct to ...
Ok(Self(sx)) } /// Stops typing in [`Channel`]. /// /// This should be used to stop typing after it is started using [`Typing::start`]. /// Typing may persist for a few seconds on some clients after this is called. /// /// [`Channel`]: crate::model::channel::Channel pub fn stop...
{ let (sx, mut rx) = oneshot::channel(); tokio::spawn(async move { loop { match rx.try_recv() { Ok(_) | Err(TryRecvError::Closed) => break, _ => (), } http.broadcast_typing(channel_id).await?; ...
identifier_body
view.rs
/* * Copyright (c) 2015-2021 Mathias Hällman * * 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 std::cmp; use unicode_width::UnicodeWidthChar as CharWidth;...
else { None }; // helper to put a character on the screen let put = |character, cell: screen::Cell, screen: &mut Screen| { use screen::Color::*; let highlight = caret_cell.map(|c| c!= cell).unwrap_or(false); let (fg, bg) = if highlight { ...
Some(position + self.caret_position(caret, buffer)) }
conditional_block
view.rs
/* * Copyright (c) 2015-2021 Mathias Hällman * * 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 std::cmp; use unicode_width::UnicodeWidthChar as CharWidth;...
let (line, column) = (caret.line(), caret.column()); let screen::Size(rows, cols) = self.size; let rows = rows as usize; let cols = cols as usize; self.scroll_line = if line < self.scroll_line { line } else if line >= self.scroll_line + rows { lin...
self.scroll_column = column; } pub fn scroll_into_view(&mut self, caret: Caret, buffer: &Buffer) {
random_line_split
view.rs
/* * Copyright (c) 2015-2021 Mathias Hällman * * 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 std::cmp; use unicode_width::UnicodeWidthChar as CharWidth;...
) -> View { View { scroll_line: 0, scroll_column: 0, size: screen::Size(MIN_VIEW_SIZE, MIN_VIEW_SIZE), } } pub fn scroll_line(&self) -> usize { self.scroll_line } pub fn scroll_column(&self) -> usize { self.scroll_column } //...
ew(
identifier_name
view.rs
/* * Copyright (c) 2015-2021 Mathias Hällman * * 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 std::cmp; use unicode_width::UnicodeWidthChar as CharWidth;...
let screen::Size(rows, cols) = self.size; // draw line by line let mut row: u16 = 0; for chars in buffer .line_iter() .from(self.scroll_line) .take(rows as usize) { let line_offset = screen::Cell(row, 0) + position; // draw...
// calculate caret screen position if focused let caret_cell = if focused { Some(position + self.caret_position(caret, buffer)) } else { None }; // helper to put a character on the screen let put = |character, cell: screen::Cell, screen: &mut Scr...
identifier_body
callables.rs
use std::fmt; use std::convert::TryInto; use std::collections::{HashMap}; use std::iter::FromIterator; use chainstate::stacks::events::StacksTransactionEvent; use vm::costs::{cost_functions, SimpleCostSpecification}; use vm::errors::{InterpreterResult as Result, Error, check_argument_count}; use vm::analysis::errors...
if let Some(_) = context.variables.insert(name.clone(), value.clone()) { return Err(CheckErrors::NameAlreadyUsed(name.to_string()).into()) } } } } let result = eval(&self.body, env, &context); /...
if !type_sig.admits(value) { return Err(CheckErrors::TypeValueError(type_sig.clone(), value.clone()).into()) }
random_line_split
callables.rs
use std::fmt; use std::convert::TryInto; use std::collections::{HashMap}; use std::iter::FromIterator; use chainstate::stacks::events::StacksTransactionEvent; use vm::costs::{cost_functions, SimpleCostSpecification}; use vm::errors::{InterpreterResult as Result, Error, check_argument_count}; use vm::analysis::errors...
{ SingleArg(&'static dyn Fn(Value) -> Result<Value>), DoubleArg(&'static dyn Fn(Value, Value) -> Result<Value>), MoreArg(&'static dyn Fn(Vec<Value>) -> Result<Value>) } impl NativeHandle { pub fn apply(&self, mut args: Vec<Value>) -> Result<Value> { match self { NativeHandle::Singl...
NativeHandle
identifier_name
layout_interface.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/. */ //! The high-level interface from script to layout. Using this abstract //! interface helps reduce coupling betwee...
{ /// An opaque reference to the DOM node participating in the animation. pub node: OpaqueNode, /// A description of the property animation that is occurring. pub property_animation: PropertyAnimation, /// The start time of the animation, as returned by `time::precise_time_s()`. pub start_time:...
Animation
identifier_name
layout_interface.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/. */ //! The high-level interface from script to layout. Using this abstract //! interface helps reduce coupling betwee...
CollectReports(ReportsChan), /// Requests that the layout task enter a quiescent state in which no more messages are /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when /// this happens. PrepareToExit(Sender<()>), /// Requests that the layout task immedi...
random_line_split
posterize.rs
/* * Copyright (C) 2014 The Android Open Source Project * * 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 app...
rs_allocation inputImage; float intensityLow = 0.f; float intensityHigh; uchar4 color; const static float3 mono = {0.299f, 0.587f, 0.114f}; void setParams(float intensHigh, float intensLow, uchar r, uchar g, uchar b) { intensityLow = intensLow; intensityHigh = intensHigh; uchar4 hats = {r, g, b, 255}; ...
random_line_split
posterize.rs
/* * Copyright (C) 2014 The Android Open Source Project * * 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 app...
}
{ return v_in; }
conditional_block
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::fmt; use std::io::{Write, Result}; use blake2_rfc::blake2b::Blake2b; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pu...
(self) -> Fingerprint { Fingerprint::from_bytes_unsafe(&self.hasher.finalize().as_bytes()) } } impl<W: Write> Write for WriterHasher<W> { fn write(&mut self, buf: &[u8]) -> Result<usize> { let written = self.inner.write(buf)?; // Hash the bytes that were successfully written. self.hasher.update(&bu...
finish
identifier_name
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::fmt; use std::io::{Write, Result}; use blake2_rfc::blake2b::Blake2b; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pu...
let mut fingerprint = [0;FINGERPRINT_SIZE]; fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]); Fingerprint(fingerprint) } pub fn to_hex(&self) -> String { let mut s = String::new(); for &byte in self.0.iter() { fmt::Write::write_fmt(&mut s, format_args!("{:02x}", byte)).unwrap()...
{ panic!("Input value was not a fingerprint; had length: {}", bytes.len()); }
conditional_block
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::fmt; use std::io::{Write, Result}; use blake2_rfc::blake2b::Blake2b; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pu...
/// /// Returns the result of fingerprinting this stream, and Drops the stream. /// pub fn finish(self) -> Fingerprint { Fingerprint::from_bytes_unsafe(&self.hasher.finalize().as_bytes()) } } impl<W: Write> Write for WriterHasher<W> { fn write(&mut self, buf: &[u8]) -> Result<usize> { let written...
{ WriterHasher { hasher: Blake2b::new(FINGERPRINT_SIZE), inner: inner, } }
identifier_body
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::fmt; use std::io::{Write, Result}; use blake2_rfc::blake2b::Blake2b; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pu...
self.inner.flush() } }
fn flush(&mut self) -> Result<()> {
random_line_split
test.rs
, and synthesizing a main test harness pub fn modify_for_testing(sess: &ParseSess, cfg: &ast::CrateConfig, krate: ast::Crate, span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate { // We generate the test harness when building in the ...
diag.span_err(i.span, "functions used as benches must have signature \ `fn(&mut Bencher) -> ()`"); } return has_bench_attr && has_test_signature(i); } fn is_ignored(i: &ast::Item) -> bool { i.attrs.iter().any(|attr| attr.check_name("ignore")) } fn should_fail(i: &ast::Item) ...
} if has_bench_attr && !has_test_signature(i) { let diag = cx.span_diagnostic;
random_line_split
test.rs
and synthesizing a main test harness pub fn
(sess: &ParseSess, cfg: &ast::CrateConfig, krate: ast::Crate, span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate { // We generate the test harness when building in the 'test' // configuration, either with the '--test' or '--cfg ...
modify_for_testing
identifier_name
test.rs
and synthesizing a main test harness pub fn modify_for_testing(sess: &ParseSess, cfg: &ast::CrateConfig, krate: ast::Crate, span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate { // We generate the test harness when building in the '...
// cx.testfns.len()); } } } // We don't want to recurse into anything other than mods, since // mods or tests inside of functions will break things let res = match i.node { ast::ItemMod(..) => fold::noop_fold_item(i, se...
{ match i.node { ast::ItemFn(_, ast::UnsafeFn, _, _, _) => { let diag = self.cx.span_diagnostic; diag.span_fatal(i.span, "unsafe functions cannot be used for \ tests"); ...
conditional_block
subspace.rs
//! Implements traits for tuples such subspaces can be constructed. use Construct; use Count; use ToIndex; use ToPos; use Zero; impl<T, U> Construct for (T, U) where T: Construct, U: Construct { fn new() -> (T, U) { (Construct::new(), Construct::new()) } } impl<T, U, V, W> Count<(V, W)>...
impl<T, U, V, W, X, Y> Zero<(V, W), (X, Y)> for (T, U) where T: Construct + Zero<V, X>, U: Construct + Zero<W, Y> { fn zero(&self, &(ref dim_t, ref dim_u): &(V, W)) -> (X, Y) { let t: T = Construct::new(); let u: U = Construct::new(); (t.zero(dim_t), u.zero(dim_u)) } } im...
} }
random_line_split
subspace.rs
//! Implements traits for tuples such subspaces can be constructed. use Construct; use Count; use ToIndex; use ToPos; use Zero; impl<T, U> Construct for (T, U) where T: Construct, U: Construct { fn new() -> (T, U) { (Construct::new(), Construct::new()) } } impl<T, U, V, W> Count<(V, W)>...
}
{ let t: T = Construct::new(); let u: U = Construct::new(); let count = u.count(dim_u); let x = ind / count; t.to_pos(dim_t, x, pt); u.to_pos(dim_u, ind - x * count, pu); }
identifier_body
subspace.rs
//! Implements traits for tuples such subspaces can be constructed. use Construct; use Count; use ToIndex; use ToPos; use Zero; impl<T, U> Construct for (T, U) where T: Construct, U: Construct { fn new() -> (T, U) { (Construct::new(), Construct::new()) } } impl<T, U, V, W> Count<(V, W)>...
(&self, &(ref dim_t, ref dim_u): &(V, W)) -> usize { let t: T = Construct::new(); let u: U = Construct::new(); t.count(dim_t) * u.count(dim_u) } } impl<T, U, V, W, X, Y> Zero<(V, W), (X, Y)> for (T, U) where T: Construct + Zero<V, X>, U: Construct + Zero<W, Y> { fn zero(&s...
count
identifier_name
clear_strategy.rs
use clear_strategy::ClearStrategy::*; use std::iter; pub enum ClearStrategy { Vertical, Horizontal, DiagonalUp, DiagonalDown, } impl ClearStrategy { pub fn get_starting_points(&self, height: usize, width: usize) -> Vec<(usize, usize)> { match *self { Vertical => (iter::repeat(0...
Some((new_row, new_col)) } } }
} else {
random_line_split
clear_strategy.rs
use clear_strategy::ClearStrategy::*; use std::iter; pub enum ClearStrategy { Vertical, Horizontal, DiagonalUp, DiagonalDown, } impl ClearStrategy { pub fn get_starting_points(&self, height: usize, width: usize) -> Vec<(usize, usize)> { match *self { Vertical => (iter::repeat(0...
( &self, row: usize, col: usize, height: usize, width: usize ) -> Option<(usize, usize)> { let (new_row, new_col) = match *self { Vertical => (row + 1, col), Horizontal => (row, col + 1), DiagonalUp if row > 0 => (row - 1, col + 1)...
get_next_point
identifier_name
clear_strategy.rs
use clear_strategy::ClearStrategy::*; use std::iter; pub enum ClearStrategy { Vertical, Horizontal, DiagonalUp, DiagonalDown, } impl ClearStrategy { pub fn get_starting_points(&self, height: usize, width: usize) -> Vec<(usize, usize)> { match *self { Vertical => (iter::repeat(0...
}
{ let (new_row, new_col) = match *self { Vertical => (row + 1, col), Horizontal => (row, col + 1), DiagonalUp if row > 0 => (row - 1, col + 1), DiagonalDown => (row + 1, col + 1), _ => return None }; let is_invalid_point = new_row >= ...
identifier_body
ws2bth.rs
// 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according ...
pub const RFCOMM_CMD_RPN: UCHAR = 3; pub const RFCOMM_CMD_RPN_REQUEST: UCHAR = 4; pub const RFCOMM_CMD_RPN_RESPONSE: UCHAR = 5; UNION!{#[repr(packed)] union RFCOMM_COMMAND_Data { [u8; 7], MSC MSC_mut: RFCOMM_MSC_DATA, RLS RLS_mut: RFCOMM_RLS_DATA, RPN RPN_mut: RFCOMM_RPN_DATA, }} STRUCT!{#[repr(packed)]...
pub const RFCOMM_CMD_NONE: UCHAR = 0; pub const RFCOMM_CMD_MSC: UCHAR = 1; pub const RFCOMM_CMD_RLS: UCHAR = 2;
random_line_split
issue-9446.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 ...
(StrBuf); impl Wrapper { pub fn new(wrapped: StrBuf) -> Wrapper { Wrapper(wrapped) } pub fn say_hi(&self) { let Wrapper(ref s) = *self; println!("hello {}", *s); } } impl Drop for Wrapper { fn drop(&mut self) {} } pub fn main() { { // This runs without complai...
Wrapper
identifier_name
issue-9446.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 ...
// except according to those terms. struct Wrapper(StrBuf); impl Wrapper { pub fn new(wrapped: StrBuf) -> Wrapper { Wrapper(wrapped) } pub fn say_hi(&self) { let Wrapper(ref s) = *self; println!("hello {}", *s); } } impl Drop for Wrapper { fn drop(&mut self) {} } pub fn ...
random_line_split
binding.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use std::fmt; use translate::*; use BindingFlags; use GString; use Object; glib_wrapper! { pub struct Binding(Object<gobject_sys::GBinding, BindingClass>); ...
impl fmt::Display for Binding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Binding") } }
random_line_split
binding.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use std::fmt; use translate::*; use BindingFlags; use GString; use Object; glib_wrapper! { pub struct Binding(Object<gobject_sys::GBinding, BindingClass>); ...
pub fn get_target_property(&self) -> GString { unsafe { from_glib_none(gobject_sys::g_binding_get_target_property( self.to_glib_none().0, )) } } pub fn unbind(&self) { unsafe { gobject_sys::g_binding_unbind(self.to_glib_full()); ...
{ unsafe { from_glib_none(gobject_sys::g_binding_get_target(self.to_glib_none().0)) } }
identifier_body
binding.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use std::fmt; use translate::*; use BindingFlags; use GString; use Object; glib_wrapper! { pub struct Binding(Object<gobject_sys::GBinding, BindingClass>); ...
(&self) -> Option<Object> { unsafe { from_glib_none(gobject_sys::g_binding_get_source(self.to_glib_none().0)) } } pub fn get_source_property(&self) -> GString { unsafe { from_glib_none(gobject_sys::g_binding_get_source_property( self.to_glib_none().0, )) ...
get_source
identifier_name
db.rs
use std::path::Path; use std::fs::File; use std::io::{Write, Read, self, Error, ErrorKind}; use db::Entry; use nacl::secretbox::{SecretKey, SecretMsg}; use rand::{ Rng, OsRng }; use crypto::bcrypt::bcrypt; use serde_json; const DB_VERSION: u8 = 1u8; const SALT_SIZE: usize = 16; const PASS_SIZE: usize = 24; const BCRY...
} #[cfg(test)] mod tests { use db::Entry; use db::Database; use std::io::Cursor; use std::io::Read; #[test] fn test_save_and_load() { let mut buff: Cursor<Vec<u8>> = Cursor::new(vec![]); { let mut db = Database::empty("test"); db.add(Entry::new("servic...
{ Err(Error::new(ErrorKind::InvalidData, text)) }
identifier_body
db.rs
use std::path::Path; use std::fs::File; use std::io::{Write, Read, self, Error, ErrorKind}; use db::Entry; use nacl::secretbox::{SecretKey, SecretMsg}; use rand::{ Rng, OsRng }; use crypto::bcrypt::bcrypt; use serde_json; const DB_VERSION: u8 = 1u8; const SALT_SIZE: usize = 16; const PASS_SIZE: usize = 24; const BCRY...
let mut bcrypt_output = [0u8; PASS_SIZE]; // output 24 bytes let mut version_buffer = [0u8; 1]; match src.read(&mut version_buffer){ Ok(_) => (), Err(why) => return Err(why) }; if version_buffer[0]!= DB_VERSION { return Database::invalid_data_...
random_line_split
db.rs
use std::path::Path; use std::fs::File; use std::io::{Write, Read, self, Error, ErrorKind}; use db::Entry; use nacl::secretbox::{SecretKey, SecretMsg}; use rand::{ Rng, OsRng }; use crypto::bcrypt::bcrypt; use serde_json; const DB_VERSION: u8 = 1u8; const SALT_SIZE: usize = 16; const PASS_SIZE: usize = 24; const BCRY...
{ pub db: Database, pub filepath: String } impl DatabaseInFile { pub fn save(&self) -> io::Result<()>{ self.db.save_to_file(Path::new(&self.filepath)) } } pub struct Database { bcrypt_salt: [u8; SALT_SIZE], bcrypt_pass: [u8; PASS_SIZE], pub entries: Vec<Entry> } impl Database { ...
DatabaseInFile
identifier_name
rand.rs
//! Utilities for generating random values //! //! This module provides a much, much simpler version of the very robust [`rand`] crate. The //! purpose of this is to give people teaching/learning Rust an easier target for doing interesting //! things with random numbers. You don't need to know very much Rust to use thi...
/// struct Product { /// price: f64, /// quantity: u32, /// } /// ``` /// /// What would `random_range(1.5, 5.2)` mean for this type? It's hard to say because while you /// could generate a random value for `price`, it doesn't make sense to generate a `quantity` /// given that range. /// /// A notable exception...
/// #[derive(Debug, Clone)]
random_line_split
rand.rs
//! Utilities for generating random values //! //! This module provides a much, much simpler version of the very robust [`rand`] crate. The //! purpose of this is to give people teaching/learning Rust an easier target for doing interesting //! things with random numbers. You don't need to know very much Rust to use thi...
/// Chooses a random element from the slice and returns a reference to it. /// /// If the slice is empty, returns None. /// /// # Example /// /// ```rust,no_run /// use turtle::{Turtle, rand::choose, colors::{RED, BLUE, GREEN, YELLOW}}; /// /// let mut turtle = Turtle::new(); /// /// let pen_colors = [RED, BLUE, GREE...
{ slice.shuffle(); }
identifier_body
rand.rs
//! Utilities for generating random values //! //! This module provides a much, much simpler version of the very robust [`rand`] crate. The //! purpose of this is to give people teaching/learning Rust an easier target for doing interesting //! things with random numbers. You don't need to know very much Rust to use thi...
else { None } } } impl<T: Random> Random for Wrapping<T> { fn random() -> Self { Wrapping(Random::random()) } } /// Generates a single random value of the type `T`. /// /// # Specifying the type to generate /// /// Since `T` can be any of a number of different types, you may n...
{ Some(Random::random()) }
conditional_block
rand.rs
//! Utilities for generating random values //! //! This module provides a much, much simpler version of the very robust [`rand`] crate. The //! purpose of this is to give people teaching/learning Rust an easier target for doing interesting //! things with random numbers. You don't need to know very much Rust to use thi...
(&mut self) { use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); <Self as SliceRandom>::shuffle(self, &mut rng); } fn choose(&self) -> Option<&Self::Item> { use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); <Self as SliceRandom>::choose(sel...
shuffle
identifier_name
minimax_test.rs
use crate::minimax::{Minimax, MinimaxConfig, MinimaxMovesSorting, MinimaxType}; use env_logger; use oppai_field::construct_field::construct_field; use oppai_field::player::Player; use oppai_test_images::*; use rand::SeedableRng; use rand_xorshift::XorShiftRng; const SEED: [u8; 16] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29...
macro_rules! minimax_test { ($(#[$($attr:meta),+])* $name:ident, $config:ident, $image:ident, $depth:expr) => { #[test] $(#[$($attr),+])* fn $name() { env_logger::try_init().ok(); let mut rng = XorShiftRng::from_seed(SEED); let mut field = construct_field(&mut rng, $image.image); ...
rebuild_trajectories: false, };
random_line_split
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod performance...
<T: Runnable + Send +'static>(&self, msg: Box<T>, global: &GlobalScope) -> Result<(), ()> { self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) } }
queue
identifier_name
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod performance...
self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) } }
-> Result<(), ()> where T: Runnable + Send + 'static; fn queue<T: Runnable + Send + 'static>(&self, msg: Box<T>, global: &GlobalScope) -> Result<(), ()> {
random_line_split
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod performance...
}
{ self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) }
identifier_body
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capac...
(&mut self, key: u32) { self.insert_elem(key, ()) } //pub(super) fn keys<'a>(&'a self) -> IterType<'a, ()> { pub(super) fn keys(&self) -> IterType<()> { self.data.iter().filter_map(|i| i.get().map(|e| e.key)) } } impl IHM<u32> { pub fn insert(&mut self, key: u32, val: u32) { ...
insert
identifier_name
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capac...
pub fn get(&self, key: u32) -> Option<u32> { let mut addr = self.hash(key); loop { /* let entry = unsafe { self.data.get_unchecked(addr) }; match entry.get() { */ match self.data[addr].get() { None => return None, ...
{ self.insert_elem(key, val) }
identifier_body
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capac...
self.size += 1; let mut addr = self.hash(key); loop { let entry = &mut self.data[addr]; //let entry = unsafe { self.data.get_unchecked_mut(addr) }; if entry.is_none() { // wasn't present, insert and continue *entry = Entry { ke...
{ self.resize(); }
conditional_block
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capac...
fn none() -> Self { Entry { key: ENTRY_RESERVED, val: Default::default(), } } } /// Integer hash map: map keyed by integers for a very specific application. /// Has some restrictions: Can't remove entries, capacity must be a power of 2, /// input must be relatively ran...
} } #[inline]
random_line_split
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetwork...
Ok(()) } } impl Debug for BitcoinNetworkConnection { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, r"BitcoinNetworkConnection {{ , }}",) } }
*self.needed.borrow_mut() -= read; } else { *self.needed.borrow_mut() = 0; return Ok(()); }
random_line_split
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetwork...
(host: String, socket: TcpStream) -> Result<BitcoinNetworkConnection, Error> { socket.set_read_timeout(Some(Duration::from_secs(2)))?; //.expect("set_read_timeout call failed"); socket.set_write_timeout(Some(Duration::from_secs(2)))?; Ok(BitcoinNetworkConnection { ho...
with_stream
identifier_name
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetwork...
if let Some(message) = self.try_parse() { return Some(message); } None } fn try_parse(&self) -> Option<Result<Message, BitcoinNetworkError>> { let available_data = self.buffer.borrow().available_data(); if available_data == 0 { return None; ...
{ let len = self.buffer.borrow().available_data(); trace!("[{}] Buffer len: {}", self.host, len); if let Some(message) = self.try_parse() { return Some(message); } match self.read() { Ok(_) => {}, Err(e) => { return Some(Err(e)...
identifier_body
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetwork...
let mut trim = false; let mut consume = 0; let parsed = match message(&self.buffer.borrow().data(), &self.host) { IResult::Done(remaining, msg) => Some((msg, remaining.len())), IResult::Incomplete(len) => { if let Needed::Size(s) = len { ...
{ return None; }
conditional_block
glyph.rs
_ligature, glyph_count); let mut val = FLAG_NOT_MISSING; if!starts_cluster { val |= FLAG_NOT_CLUSTER_START; } if!starts_ligature { val |= FLAG_NOT_LIGATURE_GROUP_START; } val |= (glyph_count as u32) << GLYPH_COUNT_SHIFT; G...
<'a> { SimpleGlyphInfo(&'a GlyphStore, uint), DetailGlyphInfo(&'a GlyphStore, uint, u16) } impl<'a> GlyphInfo<'a> { pub fn index(self) -> GlyphIndex { match self { SimpleGlyphInfo(store, entry_i) => store.entry_buffer[entry_i].index(), DetailGlyphInfo(store, entry_i, detail_...
GlyphInfo
identifier_name
glyph.rs
_ligature, glyph_count); let mut val = FLAG_NOT_MISSING; if!starts_cluster { val |= FLAG_NOT_CLUSTER_START; } if!starts_ligature { val |= FLAG_NOT_LIGATURE_GROUP_START; } val |= (glyph_count as u32) << GLYPH_COUNT_SHIFT; G...
self.entry_buffer[i] = entry; } pub fn add_glyphs_for_char_index(&mut self, i: uint, data_for_glyphs: &[GlyphData]) { assert!(i < self.entry_buffer.len()); assert!(data_for_glyphs.len() > 0); let glyph_count = data_for_glyphs.len(); let first_glyph_data = data_for_gl...
{ fn glyph_is_compressible(data: &GlyphData) -> bool { is_simple_glyph_id(data.index) && is_simple_advance(data.advance) && data.offset == geometry::zero_point() && data.cluster_start // others are stored in detail buffer } assert!(da...
identifier_body
glyph.rs
starts_ligature, glyph_count); let mut val = FLAG_NOT_MISSING; if!starts_cluster { val |= FLAG_NOT_CLUSTER_START; } if!starts_ligature { val |= FLAG_NOT_LIGATURE_GROUP_START; } val |= (glyph_count as u32) << GLYPH_COUNT_SHIFT; ...
advance: Au, offset: Point2D<Au>, is_missing: bool, cluster_start: bool, ligature_start: bool, } impl GlyphData { pub fn new(index: GlyphIndex, advance: Au, offset: Option<Point2D<Au>>, is_missing: bool, cluster_start: bool, ...
random_line_split
mod.rs
// Copyright 2020 The Tink-Rust Authors // // 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...
"legacy primitives do not match the input key" ); } #[test] fn test_add_with_invalid_input() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); let dummy_mac = Box::new(DummyMac { name: "".to_string(), }); // unknown prefix type let invalid_key = new_dummy_key(0, KeySt...
),
random_line_split
mod.rs
// Copyright 2020 The Tink-Rust Authors // // 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...
if let Primitive::Mac(dummy_mac) = &entry.primitive { let mut data = vec![1, 2, 3, 4, 5]; let digest = dummy_mac.compute_mac(&data).unwrap(); data.extend_from_slice(test_mac.name.as_bytes()); if digest!= data { return false; } } else { panic!("failed ...
{ return false; }
conditional_block
mod.rs
// Copyright 2020 The Tink-Rust Authors // // 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...
() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); assert!(ps.primary.is_none()); assert!(ps.entries.is_empty()); // generate test keys let keys = create_keyset(); // add all test primitives let mut macs = Vec::with_capacity(keys.len()); let mut entries = Vec::with_capacity(...
test_primitive_set_basic
identifier_name
mod.rs
// Copyright 2020 The Tink-Rust Authors // // 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...
{ if entry.key_id != key_id || entry.status != *status || entry.prefix_type != *output_prefix_type { return false; } if let Primitive::Mac(dummy_mac) = &entry.primitive { let mut data = vec![1, 2, 3, 4, 5]; let digest = dummy_mac.compute_mac(&data).unwrap(); data.extend_f...
identifier_body
sanity_checks.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/. */ //! Different static asserts that ensure the build does what it's expected to. //! //! TODO: maybe cfg(test) this?...
() { let mut saw_before = false; let mut saw_after = false; macro_rules! pseudo_element { (":before", $atom:expr, false) => { saw_before = true; }; (":after", $atom:expr, false) => { saw_after = true; }; ($pseudo_str_with_colon:expr, $atom:exp...
assert_basic_pseudo_elements
identifier_name
sanity_checks.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/. */ //! Different static asserts that ensure the build does what it's expected to. //! //! TODO: maybe cfg(test) this?...
assert!(saw_after); }
random_line_split
sanity_checks.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/. */ //! Different static asserts that ensure the build does what it's expected to. //! //! TODO: maybe cfg(test) this?...
}
{ let mut saw_before = false; let mut saw_after = false; macro_rules! pseudo_element { (":before", $atom:expr, false) => { saw_before = true; }; (":after", $atom:expr, false) => { saw_after = true; }; ($pseudo_str_with_colon:expr, $atom:expr, ...
identifier_body
coercion.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 ...
debug!("coerce_borrowed_fn(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let fn_ty = match *sty_a { ty::ty_closure(ref f) if f.sigil == ast::ManagedSigil => copy *f, ty::ty_closure(ref f) if f.sigil == ast::OwnedSigil...
a: ty::t, sty_a: &ty::sty, b: ty::t) -> CoerceResult {
random_line_split
coercion.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, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_unsafe_ptr(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), st...
coerce_unsafe_ptr
identifier_name
coercion.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}; let r_a = self.infcx.next_region_var(Coercion(self.trace)); let a_borrowed = ty::mk_estr(self.infcx.tcx, vstore_slice(r_a)); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowVec(r_a, m_im...
{ return self.subtype(a, b); }
conditional_block
coercion.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 ...
sigil: ast::BorrowedSigil, region: r_borrow, ..fn_ty }); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowFn(r_borrow)) }))) } pub fn coer...
{ debug!("coerce_borrowed_fn(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let fn_ty = match *sty_a { ty::ty_closure(ref f) if f.sigil == ast::ManagedSigil => copy *f, ty::ty_closure(ref f) if f.sigil == ast::OwnedSig...
identifier_body
nodeinfo.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. */ use serde_derive::{Deserialize, Serialize}; use crate::{hgid::HgId, key::Key}; #[derive( Clone, Debug, Default, Eq, Has...
}
{ NodeInfo { parents: [Key::arbitrary(g), Key::arbitrary(g)], linknode: HgId::arbitrary(g), } }
identifier_body
nodeinfo.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. */ use serde_derive::{Deserialize, Serialize}; use crate::{hgid::HgId, key::Key}; #[derive( Clone, Debug, Default, Eq, Has...
linknode: HgId::arbitrary(g), } } }
random_line_split
nodeinfo.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. */ use serde_derive::{Deserialize, Serialize}; use crate::{hgid::HgId, key::Key}; #[derive( Clone, Debug, Default, Eq, Has...
(g: &mut quickcheck::Gen) -> Self { NodeInfo { parents: [Key::arbitrary(g), Key::arbitrary(g)], linknode: HgId::arbitrary(g), } } }
arbitrary
identifier_name
vfpclasssd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn vfpclasssd_1() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Dir...
}
run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(IndirectScaledIndexed(RSI, RDX, Eight, Some(OperandSize::Qword), None)), operand3: Some(Literal8(3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K1), broadcast:...
random_line_split
vfpclasssd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn vfpclasssd_1() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Dir...
fn vfpclasssd_4() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(IndirectScaledIndexed(RSI, RDX, Eight, Some(OperandSize::Qword), None)), operand3: Some(Literal8(3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(Ma...
{ run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM16)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 179, 253, 10, 103, 208, 38], OperandSiz...
identifier_body
vfpclasssd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn
() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM4)), operand3: Some(Literal8(5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 253, 11, 103, 212, 5], OperandSiz...
vfpclasssd_1
identifier_name
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: S...
() { let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); assert_eq!(&headers.get::<Authorization<String>>().unwrap().0[], "foo bar baz"); } #[test] fn test_basic_auth() { let mut headers = Headers::new(); headers.set(Authorization(Basic ...
test_raw_auth_parse
identifier_name
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: S...
}, Err(e) => { debug!("Basic::from_base64 error={:?}", e); None } } } } #[cfg(test)] mod tests { use std::io::MemReader; use super::{Authorization, Basic}; use super::super::super::{Headers}; fn mem(s: &str) -> MemReader ...
{ debug!("Basic::from_utf8 error={:?}", e); None }
conditional_block
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: S...
None } }, Err(e) => { debug!("Basic::from_base64 error={:?}", e); None } } } } #[cfg(test)] mod tests { use std::io::MemReader; use super::{Authorization, Basic}; use super::super::super::{H...
{ match s.from_base64() { Ok(decoded) => match String::from_utf8(decoded) { Ok(text) => { let mut parts = &mut text[].split(':'); let user = match parts.next() { Some(part) => part.to_string(), No...
identifier_body
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: S...
headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: None })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjo=\r\n".to_string()); } #[test] fn test_basic_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRp...
random_line_split
ridged.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::ridgedmulti::RidgedMulti; use image::GenericImage; use std::io::File; use time::precise_time_s; fn main() { // octaves, gain, lac, offset, h let mut ngen = RidgedMulti::new_rand(24...
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0); }
random_line_split
ridged.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::ridgedmulti::RidgedMulti; use image::GenericImage; use std::io::File; use time::precise_time_s; fn main()
let fout = File::create(&Path::new("ridged.png")).unwrap(); let _ = image::ImageLuma8(imbuf).save(fout, image::PNG); println!("ridged.png saved") println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0); }
{ // octaves, gain, lac, offset, h let mut ngen = RidgedMulti::new_rand(24, 1.7, 1.9, 1.0, 0.75, 100.0); println!("Noise seed is {}", ngen.get_seed()); let img_size = 512 as u32; let mut imbuf = image::ImageBuf::new(img_size, img_size); let start = precise_time_s(); for ...
identifier_body
ridged.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::ridgedmulti::RidgedMulti; use image::GenericImage; use std::io::File; use time::precise_time_s; fn
() { // octaves, gain, lac, offset, h let mut ngen = RidgedMulti::new_rand(24, 1.7, 1.9, 1.0, 0.75, 100.0); println!("Noise seed is {}", ngen.get_seed()); let img_size = 512 as u32; let mut imbuf = image::ImageBuf::new(img_size, img_size); let start = precise_time_s(); f...
main
identifier_name
middleware.rs
use std::error::Error; use std::result::Result; use nickel::{Request, Response, Middleware, Continue, MiddlewareResult}; use nickel::status::StatusCode; use r2d2_postgres::{PostgresConnectionManager, SslMode}; use r2d2::{Config, Pool, PooledConnection, GetTimeout}; use typemap::Key; use plugin::Extensible; pub struct ...
/// /// Example: /// /// ```ignore /// app.get("/my_counter", middleware! { |request, response| /// let db = try_with!(response, request.pg_conn()); /// }); /// ``` pub trait PostgresRequestExtensions { fn pg_conn(&self) -> Result<PooledConnection<PostgresConnectionManager>, (StatusCode, GetTimeout)>; } impl<'a, ...
/// /// On error, the method returns a tuple per Nickel convention. This allows the route to use the /// `try_with!` macro.
random_line_split
middleware.rs
use std::error::Error; use std::result::Result; use nickel::{Request, Response, Middleware, Continue, MiddlewareResult}; use nickel::status::StatusCode; use r2d2_postgres::{PostgresConnectionManager, SslMode}; use r2d2::{Config, Pool, PooledConnection, GetTimeout}; use typemap::Key; use plugin::Extensible; pub struct ...
} /// Add `pg_conn()` helper method to `nickel::Request` /// /// This trait must only be used in conjunction with `PostgresMiddleware`. /// /// On error, the method returns a tuple per Nickel convention. This allows the route to use the /// `try_with!` macro. /// /// Example: /// /// ```ignore /// app.get("/my_counte...
{ req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) }
identifier_body
middleware.rs
use std::error::Error; use std::result::Result; use nickel::{Request, Response, Middleware, Continue, MiddlewareResult}; use nickel::status::StatusCode; use r2d2_postgres::{PostgresConnectionManager, SslMode}; use r2d2::{Config, Pool, PooledConnection, GetTimeout}; use typemap::Key; use plugin::Extensible; pub struct ...
<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) } } /// Add `pg_conn()` helper method to `nickel::Request` /// /// This trait must only be used in conj...
invoke
identifier_name
htmlhtmlelement.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::HTMLHtmlElementBinding; use dom::bindings::js::Root; use dom::bindings::str:...
Node::reflect_node(box element, document, HTMLHtmlElementBinding::Wrap) } }
random_line_split
htmlhtmlelement.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::HTMLHtmlElementBinding; use dom::bindings::js::Root; use dom::bindings::str:...
{ htmlelement: HTMLElement } impl HTMLHtmlElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLHtmlElement { HTMLHtmlElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)...
HTMLHtmlElement
identifier_name
htmlhtmlelement.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::HTMLHtmlElementBinding; use dom::bindings::js::Root; use dom::bindings::str:...
#[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLHtmlElement> { let element = HTMLHtmlElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHtmlElement...
{ HTMLHtmlElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
identifier_body
example.rs
extern crate bmfont; #[macro_use] extern crate glium; extern crate image; use bmfont::{BMFont, OrdinateOrientation}; use glium::{Display, Program, VertexBuffer}; use std::io::Cursor; fn create_program(display: &Display) -> Program { let vertex_shader_src = r#" #version 140 in vec2 position; ...
.to_rgba(); let image_dimensions = image.dimensions(); println!("{:?}", image_dimensions); let image = glium::texture::RawImage2d::from_raw_rgba(image.into_raw(), image_dimensions); let texture = glium::texture::Texture2d::new(&display, image).unwrap(); #[derive(Copy, Clone, Debug)] stru...
.unwrap()
random_line_split
example.rs
extern crate bmfont; #[macro_use] extern crate glium; extern crate image; use bmfont::{BMFont, OrdinateOrientation}; use glium::{Display, Program, VertexBuffer}; use std::io::Cursor; fn create_program(display: &Display) -> Program { let vertex_shader_src = r#" #version 140 in vec2 position; ...
() { use glium::{DisplayBuild, DrawParameters, Surface}; let display = glium::glutin::WindowBuilder::new().build_glium().unwrap(); let image = image::load(Cursor::new(&include_bytes!("../font.png")[..]), image::PNG) .unwrap() .to_rgba(); let image_dimensions = image.dimensions(); prin...
main
identifier_name
p027.rs
//! [Problem 27](https://projecteuler.net/problem=27) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_cmp)] #[macro_use(problem)] extern crate common; extern crate prime; use prime::PrimeSet; // p(n) = n^2 + an ...
fn solve() -> String { compute(1000).to_string() } problem!("-59231", solve); #[cfg(test)] mod tests { use prime::PrimeSet; #[test] fn primes() { let ps = PrimeSet::new(); assert_eq!(39, super::get_limit_n(&ps, 1, 41)); assert_eq!(79, super::get_limit_n(&ps, -79, 1601)) ...
{ let ps = PrimeSet::new(); let (a, b, _len) = ps.iter() .take_while(|&p| p < limit) .filter_map(|p| { let b = p as i32; (-b .. 1000) .map(|a| (a, b, get_limit_n(&ps, a, b))) .max_by(|&(_a, _b, len)| len) }).max_by(|&(_a, _b, len)| ...
identifier_body
p027.rs
//! [Problem 27](https://projecteuler.net/problem=27) solver.
unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_cmp)] #[macro_use(problem)] extern crate common; extern crate prime; use prime::PrimeSet; // p(n) = n^2 + an + b is prime for n = 0.. N // p(0) = b => b must be prime // p(1) = 1 + a ...
#![warn(bad_style,
random_line_split
p027.rs
//! [Problem 27](https://projecteuler.net/problem=27) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_cmp)] #[macro_use(problem)] extern crate common; extern crate prime; use prime::PrimeSet; // p(n) = n^2 + an ...
() -> String { compute(1000).to_string() } problem!("-59231", solve); #[cfg(test)] mod tests { use prime::PrimeSet; #[test] fn primes() { let ps = PrimeSet::new(); assert_eq!(39, super::get_limit_n(&ps, 1, 41)); assert_eq!(79, super::get_limit_n(&ps, -79, 1601)) } }
solve
identifier_name
system_model.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. /* | Video | # of | Visible | Cycles/ | Visible Type | system | lines | lines | line | pixels/line ----...
pub fn c64_pal() -> SystemModel { SystemModel { color_ram: 1024, cpu_freq: 985_248, cycles_per_frame: 19656, frame_buffer_size: (504, 312), memory_size: 65536, refresh_rate: 50.125, sid_model: SidModel::Mos6581, ...
{ SystemModel { color_ram: 1024, cpu_freq: 1_022_727, cycles_per_frame: 17095, frame_buffer_size: (512, 263), memory_size: 65536, refresh_rate: 59.826, sid_model: SidModel::Mos6581, vic_model: VicModel::Mos6567, ...
identifier_body
system_model.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. /* | Video | # of | Visible | Cycles/ | Visible Type | system | lines | lines | line | pixels/line ----...
frame_buffer_size: (512, 263), memory_size: 65536, refresh_rate: 59.826, sid_model: SidModel::Mos6581, vic_model: VicModel::Mos6567, viewport_offset: (77, 16), viewport_size: (418, 235), } } pub fn c64_pal() -> SystemMo...
pub fn c64_ntsc() -> SystemModel { SystemModel { color_ram: 1024, cpu_freq: 1_022_727, cycles_per_frame: 17095,
random_line_split
system_model.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. /* | Video | # of | Visible | Cycles/ | Visible Type | system | lines | lines | line | pixels/line ----...
(model: &str) -> SystemModel { match model { "ntsc" => SystemModel::c64_ntsc(), "pal" => SystemModel::c64_pal(), "c64-ntsc" => SystemModel::c64_ntsc(), "c64-pal" => SystemModel::c64_pal(), _ => panic!("invalid model {}", model), } } pu...
from
identifier_name
text_buffer.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_char, c_int}; use ffi; use glib::translate::*; use TextBuffer; use TextIter; im...
pub fn insert_interactive_at_cursor(&self, text: &str, default_editable: bool) -> bool { unsafe { from_glib(ffi::gtk_text_buffer_insert_interactive_at_cursor(self.to_glib_none().0, text.as_ptr() as *const c_char, text.len() as c_int, default_editable.to_glib())) } }...
{ unsafe { from_glib( ffi::gtk_text_buffer_insert_interactive(self.to_glib_none().0, iter.to_glib_none_mut().0, text.as_ptr() as *const c_char, text.len() as c_int, default_editable.to_glib())) } }
identifier_body
text_buffer.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_char, c_int}; use ffi; use glib::translate::*; use TextBuffer; use TextIter; im...
(&self, iter: &mut TextIter, text: &str, default_editable: bool) -> bool { unsafe { from_glib( ffi::gtk_text_buffer_insert_interactive(self.to_glib_none().0, iter.to_glib_none_mut().0, text.as_ptr() as *const c_char, text.len() as c_int, ...
insert_interactive
identifier_name
text_buffer.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_char, c_int}; use ffi; use glib::translate::*; use TextBuffer; use TextIter; im...
text.as_ptr() as *const c_char, text.len() as c_int); } } pub fn insert_interactive(&self, iter: &mut TextIter, text: &str, default_editable: bool) -> bool { unsafe { from_glib( ffi::gtk_text_buffer_insert_interactive(self.to_glib_none().0...
pub fn insert_at_cursor(&self, text: &str) { unsafe { ffi::gtk_text_buffer_insert_at_cursor(self.to_glib_none().0,
random_line_split
main.rs
extern crate rsedis; extern crate config; extern crate logger; extern crate networking; extern crate compat; use std::env::args; use std::process::exit; use std::thread; use compat::getpid; use config::Config; use networking::Server; use logger::{Logger, Level}; fn main() { let mut config = Config::new(Logger::n...
} let (port, daemonize) = (config.port, config.daemonize); let mut server = Server::new(config); if!daemonize { println!("Port: {}", port); println!("PID: {}", getpid()); } server.run(); }
}, }, None => (),
random_line_split
main.rs
extern crate rsedis; extern crate config; extern crate logger; extern crate networking; extern crate compat; use std::env::args; use std::process::exit; use std::thread; use compat::getpid; use config::Config; use networking::Server; use logger::{Logger, Level}; fn main()
server.run(); }
{ let mut config = Config::new(Logger::new(Level::Notice)); match args().nth(1) { Some(f) => match config.parsefile(f) { Ok(_) => (), Err(_) => { thread::sleep_ms(100); // I'm not proud, but fatal errors are logged in a background thread ...
identifier_body
main.rs
extern crate rsedis; extern crate config; extern crate logger; extern crate networking; extern crate compat; use std::env::args; use std::process::exit; use std::thread; use compat::getpid; use config::Config; use networking::Server; use logger::{Logger, Level}; fn
() { let mut config = Config::new(Logger::new(Level::Notice)); match args().nth(1) { Some(f) => match config.parsefile(f) { Ok(_) => (), Err(_) => { thread::sleep_ms(100); // I'm not proud, but fatal errors are logged in a background thread ...
main
identifier_name
instruction_def.rs
use instruction::Reg; use operand::OperandSize; pub struct InstructionDefinition { pub mnemonic: String, pub allow_prefix: bool, pub operand_size_prefix: OperandSizePrefixBehavior, pub address_size_prefix: Option<bool>, pub f2_prefix: PrefixBehavior, pub f3_prefix: PrefixBehavior, pub compo...
{ Reg(Reg), Constant(u32) } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VexOperandBehavior { Nds, Ndd, Dds }
FixedOperand
identifier_name
instruction_def.rs
use instruction::Reg; use operand::OperandSize; pub struct InstructionDefinition { pub mnemonic: String, pub allow_prefix: bool, pub operand_size_prefix: OperandSizePrefixBehavior, pub address_size_prefix: Option<bool>, pub f2_prefix: PrefixBehavior, pub f3_prefix: PrefixBehavior, pub compo...
#[derive(Clone, Copy, Debug)] pub enum OperandAccess { Read, Write, ReadWrite } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RegType { General, Mmx, Avx, Fpu, Bound, Mask, Segment, Control, Debug } #[derive(Clone, Copy, Debug)] pub enum FixedOperand { Reg(...
}
random_line_split
read-scale.rs
// Copyright 2016 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 ...
for key in &[gdk_unscaled_dpi, gdk_xft_dpi, gdk_window_scaling_factor] { let key_str = str::from_utf8(key).unwrap(); match client.get_setting(*key) { Err(err) => println!("{}: {:?}", key_str, err), Ok(setting) => println!("{}={:?}", key_str, setting), } } }
{ let display; let client; let xlib = Xlib::open().unwrap(); unsafe { display = (xlib.XOpenDisplay)(ptr::null_mut()); // Enumerate all properties. client = Client::new(display, (xlib.XDefaultScreen)(display), Box::new(|na...
identifier_body