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
lib.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
lazy_static! { static ref RE: Regex = Regex::new("\x1b\\[[^m]+m").unwrap(); } RE.replace_all(s, "") } #[test] fn should_remove_colour() { let before = "test"; let after = kill_color(&Colour::Red.bold().paint(before)); assert_eq!(after, "test"); } #[test] fn should_remove_multiple_colour() { let t = format!("...
} fn kill_color(s: &str) -> String {
random_line_split
lib.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
ret }; builder.format(format); builder.init().expect("Logger initialized only once."); Ok(logs) } fn kill_color(s: &str) -> String { lazy_static! { static ref RE: Regex = Regex::new("\x1b\\[[^m]+m").unwrap(); } RE.replace_all(s, "") } #[test] fn should_remove_colour() { let before = "test"; let af...
{ // duplicate INFO/WARN output to console println!("{}", ret); }
conditional_block
lib.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
(config: &Config) -> Result<Arc<RotatingLogger>, String> { use rlog::*; let mut levels = String::new(); let mut builder = LogBuilder::new(); // Disable ws info logging by default. builder.filter(Some("ws"), LogLevelFilter::Warn); // Disable rustls info logging by default. builder.filter(Some("rustls"), LogLevel...
setup_log
identifier_name
key_generator.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...
() { let args = Arguments::from_args(); let result = generate_json(&args.passphrase, &args.seed).unwrap(); println!( "{}", serde_json::to_string_pretty(&result).expect("Couldn't convert json object to string") ); } fn generate_json(passphrase: &str, seed: &str) -> anyhow::Result<serde_...
main
identifier_name
key_generator.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...
); assert_eq!( json["consensus_pub_key"].as_str().unwrap(), r_keys.consensus.public_key().to_hex() ); }
json["service_pub_key"].as_str().unwrap(), r_keys.service.public_key().to_hex()
random_line_split
tcp_client.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <zexavexxe@gmail.com> Copyright © 2017 Roman Proskuryakov <humbug@deeptown.org> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Pu...
let client = client.select(packet_sender).map_err(|_| ()); // variant 2. send packets in a separate thread //thread::spawn(move || send_packets(tx)); core.run( client ).unwrap(); }
env_logger::init().unwrap(); let (tx, rx) = mpsc::channel(1); let mut core = Core::new().unwrap(); let handle = core.handle(); let client = create_client(rx, tx.clone(), &handle); // variant 1. send packets in the same thread, combine with select(...) let packet_sender = future::loop_fn(t...
identifier_body
tcp_client.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <zexavexxe@gmail.com> Copyright © 2017 Roman Proskuryakov <humbug@deeptown.org> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Pu...
2 => { // remote tcp relay server let server_pk_bytes = FromHex::from_hex("461FA3776EF0FA655F1A05477DF1B3B614F7D6B124F7DB1DD4FE3C08B03B640F").unwrap(); let server_pk = PublicKey::from_slice(&server_pk_bytes).unwrap(); let addr = "130.133.110.14:33445".parse().unwr...
// local tcp relay server from example let addr = "0.0.0.0:12345".parse().unwrap(); // Server constant PK for examples/tests let server_pk = PublicKey([177, 185, 54, 250, 10, 168, 174, 148, 0, 93, 99, 13, 131, 131, 239, ...
conditional_block
tcp_client.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <zexavexxe@gmail.com> Copyright © 2017 Roman Proskuryakov <humbug@deeptown.org> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Pu...
{ env_logger::init().unwrap(); let (tx, rx) = mpsc::channel(1); let mut core = Core::new().unwrap(); let handle = core.handle(); let client = create_client(rx, tx.clone(), &handle); // variant 1. send packets in the same thread, combine with select(...) let packet_sender = future::loop_f...
in()
identifier_name
tcp_client.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <zexavexxe@gmail.com> Copyright © 2017 Roman Proskuryakov <humbug@deeptown.org> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Pu...
tx.send(Packet::RouteRequest(RouteRequest {pk: friend_pk } )) .and_then(|tx| Ok(future::Loop::Continue(tx)) ) .or_else(|e| Ok(future::Loop::Break(e)) ) }).map(|_| ()); let client = client.select(packet_sender).map_err(|_| ()); // variant 2. send packets in a separate thread ...
192, 117, 0, 225, 119, 43, 48, 117, 84, 109, 112, 57, 243, 216, 4, 171, 185, 111, 33, 146, 221, 31, 77, 118]);
random_line_split
errors.rs
//! Representations of various client errors use hyper::{self, http, StatusCode}; use serde_json::Error as SerdeError; use std::{error::Error as StdError, fmt, string::FromUtf8Error}; use futures_util::io::Error as IoError; /// Represents the result of all docker operations pub type Result<T> = std::result::Result<T...
} impl From<FromUtf8Error> for Error { fn from(error: FromUtf8Error) -> Error { Error::Encoding(error) } } impl fmt::Display for Error { fn fmt( &self, f: &mut fmt::Formatter, ) -> fmt::Result { write!(f, "Docker Error: ")?; match self { Error::Serd...
{ Error::IO(error) }
identifier_body
errors.rs
//! Representations of various client errors use hyper::{self, http, StatusCode}; use serde_json::Error as SerdeError; use std::{error::Error as StdError, fmt, string::FromUtf8Error}; use futures_util::io::Error as IoError; /// Represents the result of all docker operations pub type Result<T> = std::result::Result<T...
(error: http::uri::InvalidUri) -> Self { let http_error: http::Error = error.into(); http_error.into() } } impl From<IoError> for Error { fn from(error: IoError) -> Error { Error::IO(error) } } impl From<FromUtf8Error> for Error { fn from(error: FromUtf8Error) -> Error { ...
from
identifier_name
errors.rs
use hyper::{self, http, StatusCode}; use serde_json::Error as SerdeError; use std::{error::Error as StdError, fmt, string::FromUtf8Error}; use futures_util::io::Error as IoError; /// Represents the result of all docker operations pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { ...
//! Representations of various client errors
random_line_split
errors.rs
//! Representations of various client errors use hyper::{self, http, StatusCode}; use serde_json::Error as SerdeError; use std::{error::Error as StdError, fmt, string::FromUtf8Error}; use futures_util::io::Error as IoError; /// Represents the result of all docker operations pub type Result<T> = std::result::Result<T...
Error::Fault { code, message } => write!(f, "{}: {}", code, message), Error::ConnectionNotUpgraded => write!( f, "expected the docker host to upgrade the HTTP connection but it did not" ), } } } impl StdError for Error { fn source(&se...
{ write!(f, "Response doesn't have the expected format: {}", cause) }
conditional_block
group.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(&self, view: &View) -> usize { let midpoint = vec2_div(vec2_add(self.extents[0], self.extents[1]), [2, 2]); let mouse_dist = view.mouse_dist(midpoint); vec2_square_len(mouse_dist) as usize } }
mouse_dist
identifier_name
group.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
let image = ::image::load_from_memory(&data).expect("load image"); // TODO: Would be great to move off thread. let image = Texture::from_image(texture_context, &image.to_rgba(), &texture_settings) .expect("texture"); ...
random_line_split
keys.rs
use crypto; use crypto::mac::Mac; use gmp::Mpz; use num::FromPrimitive; use rand; use std::io::Write; use util; lazy_static! { static ref DH_GENERATOR: Mpz = Mpz::from_u64(0x2).unwrap(); static ref DH_PRIME: Mpz = Mpz::from_bytes_be(&[ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f...
}
pub fn recv_key(&self) -> &[u8] { &self.recv_key }
random_line_split
keys.rs
use crypto; use crypto::mac::Mac; use gmp::Mpz; use num::FromPrimitive; use rand; use std::io::Write; use util; lazy_static! { static ref DH_GENERATOR: Mpz = Mpz::from_u64(0x2).unwrap(); static ref DH_PRIME: Mpz = Mpz::from_bytes_be(&[ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f...
() -> PrivateKeys { let key_data = util::rand_vec(&mut rand::thread_rng(), 95); Self::new_with_key(&key_data) } pub fn new_with_key(key_data: &[u8]) -> PrivateKeys { let private_key = Mpz::from_bytes_be(key_data); let public_key = DH_GENERATOR.powm(&private_key, &DH_PRIME); ...
new
identifier_name
keys.rs
use crypto; use crypto::mac::Mac; use gmp::Mpz; use num::FromPrimitive; use rand; use std::io::Write; use util; lazy_static! { static ref DH_GENERATOR: Mpz = Mpz::from_u64(0x2).unwrap(); static ref DH_PRIME: Mpz = Mpz::from_bytes_be(&[ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f...
}
{ &self.recv_key }
identifier_body
metadata.rs
extern crate env_logger; extern crate gluon_base as base; extern crate gluon_parser as parser; extern crate gluon_check as check; use base::metadata::{Metadata, MetadataEnv}; use base::symbol::Symbol; use check::metadata::metadata; mod support; struct MockEnv; impl MetadataEnv for MockEnv { fn get_metadata(&se...
#[test] fn propagate_metadata_type_record() { let _ = env_logger::init(); let text = r#" /// A test type type Test = Int { Test } "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); ass...
{ let _ = env_logger::init(); let text = r#" /// The identity function let id x = x { id } "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata.module.get("id"), ...
identifier_body
metadata.rs
extern crate env_logger; extern crate gluon_base as base; extern crate gluon_parser as parser; extern crate gluon_check as check; use base::metadata::{Metadata, MetadataEnv}; use base::symbol::Symbol; use check::metadata::metadata; mod support; struct
; impl MetadataEnv for MockEnv { fn get_metadata(&self, _id: &Symbol) -> Option<&Metadata> { None } } #[test] fn propagate_metadata_let_in() { let _ = env_logger::init(); let text = r#" /// The identity function let id x = x id "#; let (mut expr, result) = support::typecheck_expr(text); ...
MockEnv
identifier_name
metadata.rs
extern crate env_logger; extern crate gluon_base as base; extern crate gluon_parser as parser; extern crate gluon_check as check; use base::metadata::{Metadata, MetadataEnv}; use base::symbol::Symbol; use check::metadata::metadata; mod support; struct MockEnv; impl MetadataEnv for MockEnv { fn get_metadata(&se...
let _ = env_logger::init(); let text = r#" /// The identity function let id x = x id "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata, Metadata { ...
} } #[test] fn propagate_metadata_let_in() {
random_line_split
mod.rs
//! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide] //! chapter for more info. //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html use hir::Node; use rustc_arena::DroplessArena; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle:...
fn crate_variances(tcx: TyCtxt<'_>, (): ()) -> CrateVariancesMap<'_> { let arena = DroplessArena::default(); let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &arena); let constraints_cx = constraints::add_constraints_from_crate(terms_cx); solve::solve_constraints(constraints_cx) } fn va...
{ *providers = Providers { variances_of, crate_variances, ..*providers }; }
identifier_body
mod.rs
//! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide] //! chapter for more info. //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html use hir::Node; use rustc_arena::DroplessArena; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle:...
(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] { let id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local()); let unsupported = || { // Variance not relevant. span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item") }; match tcx.hir().get(id) ...
variances_of
identifier_name
mod.rs
//! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide] //! chapter for more info. //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html use hir::Node; use rustc_arena::DroplessArena; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle:...
_ => unsupported(), }, Node::ImplItem(item) => match item.kind { hir::ImplItemKind::Fn(..) => {} _ => unsupported(), }, Node::ForeignItem(item) => match item.kind { hir::ForeignItemKind::Fn(..) => {} _ => unsupported(), ...
{}
conditional_block
mod.rs
//! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide] //! chapter for more info. //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html use hir::Node; use rustc_arena::DroplessArena; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle:...
_ => unsupported(), } // Everything else must be inferred. let crate_map = tcx.crate_variances(()); crate_map.variances.get(&item_def_id).copied().unwrap_or(&[]) }
random_line_split
prf.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...
}
{ Box::new(self.clone()) }
identifier_body
prf.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...
(&self) -> Box<dyn Prf> { Box::new(self.clone()) } }
box_clone
identifier_name
prf.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...
/// same key is used. `compute_prf(input, length1)` will be a prefix of `compute_prf(input, /// length2)` if `length1` < `length2` and the same key is used. /// * It is indistinguishable from a random function: Given the evaluation of n different inputs, /// an attacker cannot distinguish between the PRF ...
/// The `Prf` trait is an abstraction for an element of a pseudo random /// function family, selected by a key. It has the following property: /// * It is deterministic. `compute_prf(input, length)` will always return the same output if the
random_line_split
infinite-loops.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
loop { } } pub fn main() { // Commenting this out, as this will hang forever otherwise. // Even after seeing the comment above, I'm not sure what the // intention of this test is. // spawn(move|| { loopy(5) }); }
{ spawn(move|| { loopy(n - 1) }); spawn(move|| { loopy(n - 1) }); }
conditional_block
infinite-loops.rs
// Copyright 2012-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. /* A simple wa...
// http://rust-lang.org/COPYRIGHT.
random_line_split
infinite-loops.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ // Commenting this out, as this will hang forever otherwise. // Even after seeing the comment above, I'm not sure what the // intention of this test is. // spawn(move|| { loopy(5) }); }
identifier_body
infinite-loops.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(n: isize) { if n > 0 { spawn(move|| { loopy(n - 1) }); spawn(move|| { loopy(n - 1) }); } loop { } } pub fn main() { // Commenting this out, as this will hang forever otherwise. // Even after seeing the comment above, I'm not sure what the // intention of this test is. // spawn(move|| { loopy(5...
loopy
identifier_name
lib.rs
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to g...
pub use custom::*; pub use generated::*;
random_line_split
deriving-via-extension-struct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let a = Foo { x: 1, y: 2, z: 3 }; let b = Foo { x: 1, y: 2, z: 3 }; assert_eq!(a, b); assert!(!(a!= b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); }
x: int, y: int, z: int, }
random_line_split
deriving-via-extension-struct.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 a = Foo { x: 1, y: 2, z: 3 }; let b = Foo { x: 1, y: 2, z: 3 }; assert_eq!(a, b); assert!(!(a!= b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); }
main
identifier_name
buffer_map.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 std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; ...
mem: usize, /// The maximum allowed memory. Unused buffers will be deleted /// when this threshold is exceeded. max_mem: usize, /// A monotonically increasing counter to track how recently tile sizes were used. counter: usize, } /// A key with which to store buffers. It is based on the size of ...
pub struct BufferMap { /// A HashMap that stores the Buffers. map: HashMap<BufferKey, BufferValue>, /// The current amount of memory stored by the BufferMap's buffers.
random_line_split
buffer_map.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 std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; ...
}; if { let list = &mut self.map.get_mut(&old_key).unwrap().buffers; let condemned_buffer = list.pop().take().unwrap(); self.mem -= condemned_buffer.get_mem(); condemned_buffer.destroy(graphics_context); list.is_emp...
{ match self.map.iter().min_by(|&(_, x)| x.last_action) { Some((k, _)) => *k, None => panic!("BufferMap: tried to delete with no elements in map"), } }
conditional_block
buffer_map.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 std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; ...
{ /// An array of buffers, all the same size buffers: Vec<Box<LayerBuffer>>, /// The counter when this size was last requested last_action: usize, } impl BufferMap { // Creates a new BufferMap with a given buffer limit. pub fn new(max_mem: usize) -> BufferMap { BufferMap { ...
BufferValue
identifier_name
engine_aware.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use crate::core::Value; use crate::externs; use crate::nodes::{lift_directory_digest, lift_file_digest}; use crate::Failure; use crate::Types; use cpython::{PyDict, PyString, Python}; u...
}; output.push((key_name, artifact_output)); } Some(output) } } pub struct DebugHint {} impl EngineAwareInformation for DebugHint { type MaybeOutput = String; fn retrieve(_types: &Types, value: &Value) -> Option<String> { externs::call_method(&value, "debug_hint", &[]) .ok() ....
return None; } }
random_line_split
engine_aware.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use crate::core::Value; use crate::externs; use crate::nodes::{lift_directory_digest, lift_file_digest}; use crate::Failure; use crate::Types; use cpython::{PyDict, PyString, Python}; u...
(_types: &Types, value: &Value) -> Option<Level> { let new_level_val = externs::call_method(value.as_ref(), "level", &[]).ok()?; let new_level_val = externs::check_for_python_none(new_level_val)?; externs::val_to_log_level(&new_level_val).ok() } } pub struct Message {} impl EngineAwareInformation for Me...
retrieve
identifier_name
engine_aware.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use crate::core::Value; use crate::externs; use crate::nodes::{lift_directory_digest, lift_file_digest}; use crate::Failure; use crate::Types; use cpython::{PyDict, PyString, Python}; u...
}; output.push((key_name, Value::from(value))); } Some(output) } } pub struct Artifacts {} impl EngineAwareInformation for Artifacts { type MaybeOutput = Vec<(String, ArtifactOutput)>; fn retrieve(types: &Types, value: &Value) -> Option<Self::MaybeOutput> { let artifacts_val = match e...
{ log::error!( "Error in EngineAware.metadata() implementation - non-string key: {:?}", e ); return None; }
conditional_block
generator-yielding-or-returning-itself.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 ...
pub fn want_cyclic_generator_yield<T>(_: T) where T: Generator<Yield = T, Return = ()> { } fn supply_cyclic_generator_yield() { want_cyclic_generator_yield(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) } fn main() { }
{ want_cyclic_generator_return(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) }
identifier_body
generator-yielding-or-returning-itself.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 ...
<T>(_: T) where T: Generator<Yield = T, Return = ()> { } fn supply_cyclic_generator_yield() { want_cyclic_generator_yield(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) } fn main() { }
want_cyclic_generator_yield
identifier_name
generator-yielding-or-returning-itself.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 ...
fn supply_cyclic_generator_yield() { want_cyclic_generator_yield(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) } fn main() { }
where T: Generator<Yield = T, Return = ()> { }
random_line_split
generator-yielding-or-returning-itself.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 ...
None.unwrap() }) } pub fn want_cyclic_generator_yield<T>(_: T) where T: Generator<Yield = T, Return = ()> { } fn supply_cyclic_generator_yield() { want_cyclic_generator_yield(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) } fn main() ...
{ yield None.unwrap(); }
conditional_block
errors.rs
use next_swc::{ disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic, }; use std::path::PathBuf; use swc_common::FileName; use swc_ecma_transforms_testing::test_fixture_allowing_error; use swc_ecmascript::parser::{EsConfig, Syntax}; use testing::fixture; fn syntax() -> Syntax ...
}) } #[fixture("tests/errors/re-export-all-in-page/**/input.js")] fn re_export_all_in_page(input: PathBuf) { let output = input.parent().unwrap().join("output.js"); test_fixture_allowing_error( syntax(), &|_tr| disallow_re_export_all_in_page(true), &input, &output, ); } ...
..Default::default()
random_line_split
errors.rs
use next_swc::{ disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic, }; use std::path::PathBuf; use swc_common::FileName; use swc_ecma_transforms_testing::test_fixture_allowing_error; use swc_ecmascript::parser::{EsConfig, Syntax}; use testing::fixture; fn syntax() -> Syntax
#[fixture("tests/errors/re-export-all-in-page/**/input.js")] fn re_export_all_in_page(input: PathBuf) { let output = input.parent().unwrap().join("output.js"); test_fixture_allowing_error( syntax(), &|_tr| disallow_re_export_all_in_page(true), &input, &output, ); } #[fixtu...
{ Syntax::Es(EsConfig { jsx: true, ..Default::default() }) }
identifier_body
errors.rs
use next_swc::{ disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic, }; use std::path::PathBuf; use swc_common::FileName; use swc_ecma_transforms_testing::test_fixture_allowing_error; use swc_ecmascript::parser::{EsConfig, Syntax}; use testing::fixture; fn
() -> Syntax { Syntax::Es(EsConfig { jsx: true, ..Default::default() }) } #[fixture("tests/errors/re-export-all-in-page/**/input.js")] fn re_export_all_in_page(input: PathBuf) { let output = input.parent().unwrap().join("output.js"); test_fixture_allowing_error( syntax(), ...
syntax
identifier_name
wheelevent.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/. */ use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; use crate::dom::bindings::code...
// https://w3c.github.io/uievents/#widl-WheelEvent-deltaZ fn DeltaZ(&self) -> Finite<f64> { self.delta_z.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaMode fn DeltaMode(&self) -> u32 { self.delta_mode.get() } // https://w3c.github.io/uievents/#widl-Wheel...
{ self.delta_y.get() }
identifier_body
wheelevent.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/. */ use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; use crate::dom::bindings::code...
self.upcast::<MouseEvent>().InitMouseEvent( type_arg, can_bubble_arg, cancelable_arg, view_arg, detail_arg, self.mouseevent.ScreenX(), self.mouseevent.ScreenY(), self.mouseevent.ClientX(), self.mouseeve...
{ return; }
conditional_block
wheelevent.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/. */ use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; use crate::dom::bindings::code...
self.delta_y.set(delta_y_arg); self.delta_z.set(delta_z_arg); self.delta_mode.set(delta_mode_arg); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.mouseevent.IsTrusted() } }
self.delta_x.set(delta_x_arg);
random_line_split
wheelevent.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/. */ use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; use crate::dom::bindings::code...
(&self) -> u32 { self.delta_mode.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-initWheelEvent fn InitWheelEvent( &self, type_arg: DOMString, can_bubble_arg: bool, cancelable_arg: bool, view_arg: Option<&Window>, detail_arg: i32, d...
DeltaMode
identifier_name
unboxed-closure-sugar-region.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 test<'a,'b>() { // Parens are equivalent to omitting default in angle. eq::< Foo<(isize,),()>, Foo(isize) >(); // Here we specify'static explicitly in angle-bracket version. // Parenthesized winds up getting inferred. eq::< Foo<'static, (isize,),()>, Foo...
{ }
identifier_body
unboxed-closure-sugar-region.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 ...
() { }
main
identifier_name
unboxed-closure-sugar-region.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 test<'a,'b>() { // Parens are equivalent to omitting default in angle. eq::< Foo<(isize,),()>, Foo(isize) >(); // Here we specify'static explicitly in angle-bracket version. // Parenthesized winds up getting inferred. eq::< Foo<'static, (isize,),()>, Foo(...
fn same_type<A,B:Eq<A>>(a: A, b: B) { }
random_line_split
group_by.rs
/* Copyright ⓒ 2015 grabbag contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or...
state.last_group = Some(g.clone()); // Construct the sub-iterator and yield it. Some(( g.clone(), Group { state: self.state.clone(), group_value: g, first_value: Some(e), } )) } fn size_hint(&se...
// Remember this group.
random_line_split
group_by.rs
/* Copyright ⓒ 2015 grabbag contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or...
assert_eq!(g, 1); assert_eq!(ii.next(), Some(3)); assert_eq!(ii.next(), Some(5)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(4)); assert_eq!(ii.next(), Some(6)); assert_eq!(ii.ne...
{ let v = vec![0usize, 1, 2, 3, 5, 4, 6, 8, 7]; let mut oi = v.into_iter().group_by(|&e| e & 1); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(0)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); ...
identifier_body
group_by.rs
/* Copyright ⓒ 2015 grabbag contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or...
t, GroupFn, E, G> { state: Rc<RefCell<GroupByShared<It, GroupFn, E, G>>>, } pub struct GroupByShared<It, GroupFn, E, G> { iter: It, group: GroupFn, last_group: Option<G>, push_back: Option<(G, E)>, } impl<It, GroupFn, E, G> Iterator for GroupBy<It, GroupFn, E, G> where GroupFn: FnMut(&E) -> G, It...
oupBy<I
identifier_name
condvar.rs
use crate::sys::condvar as imp; use crate::sys::mutex as mutex_imp; use crate::sys_common::mutex::MovableMutex; use crate::time::Duration; mod check; type CondvarCheck = <mutex_imp::MovableMutex as check::CondvarCheck>::Check; /// An OS-based condition variable. pub struct Condvar { inner: imp::MovableCondvar, ...
(&self) { unsafe { self.inner.notify_one() }; } /// Awakens all current waiters on this condition variable. #[inline] pub fn notify_all(&self) { unsafe { self.inner.notify_all() }; } /// Waits for a signal on the specified mutex. /// /// Behavior is undefined if the mut...
notify_one
identifier_name
condvar.rs
use crate::sys::condvar as imp; use crate::sys::mutex as mutex_imp; use crate::sys_common::mutex::MovableMutex; use crate::time::Duration; mod check; type CondvarCheck = <mutex_imp::MovableMutex as check::CondvarCheck>::Check; /// An OS-based condition variable. pub struct Condvar { inner: imp::MovableCondvar, ...
pub fn notify_all(&self) { unsafe { self.inner.notify_all() }; } /// Waits for a signal on the specified mutex. /// /// Behavior is undefined if the mutex is not locked by the current thread. /// /// May panic if used with more than one mutex. #[inline] pub unsafe fn wait(&s...
#[inline]
random_line_split
condvar.rs
use crate::sys::condvar as imp; use crate::sys::mutex as mutex_imp; use crate::sys_common::mutex::MovableMutex; use crate::time::Duration; mod check; type CondvarCheck = <mutex_imp::MovableMutex as check::CondvarCheck>::Check; /// An OS-based condition variable. pub struct Condvar { inner: imp::MovableCondvar, ...
/// Waits for a signal on the specified mutex with a timeout duration /// specified by `dur` (a relative time into the future). /// /// Behavior is undefined if the mutex is not locked by the current thread. /// /// May panic if used with more than one mutex. #[inline] pub unsafe fn wa...
{ self.check.verify(mutex); self.inner.wait(mutex.raw()) }
identifier_body
split_check.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::sync::mpsc::{self, sync_channel}; use std::sync::Arc; use std::time::Duration; use engine_rocks::raw::DB; use engine_rocks::Compat; use raftstore::coprocessor::{ config::{Config, SplitCheckConfigManager}, Coproces...
(cfg: TiKvConfig, engine: Arc<DB>) -> (ConfigController, LazyWorker<Task>) { let (router, _) = sync_channel(1); let runner = Runner::new( engine.c().clone(), router.clone(), CoprocessorHost::new(router), cfg.coprocessor.clone(), ); let share_worker = Worker::new("split-ch...
setup
identifier_name
split_check.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::sync::mpsc::{self, sync_channel}; use std::sync::Arc; use std::time::Duration; use engine_rocks::raw::DB; use engine_rocks::Compat; use raftstore::coprocessor::{ config::{Config, SplitCheckConfigManager}, Coproces...
"true".to_owned(), ); m.insert("coprocessor.batch_split_limit".to_owned(), "123".to_owned()); m.insert( "coprocessor.region_split_keys".to_owned(), "12345".to_owned(), ); m }; cfg_controller.update(change).unwrap(); // config shoul...
{ let (mut cfg, _dir) = TiKvConfig::with_tmp().unwrap(); cfg.validate().unwrap(); let engine = tmp_engine(&cfg.storage.data_dir); let (cfg_controller, mut worker) = setup(cfg.clone(), engine); let scheduler = worker.scheduler(); let cop_config = cfg.coprocessor.clone(); // update of other m...
identifier_body
split_check.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::sync::mpsc::{self, sync_channel}; use std::sync::Arc; use std::time::Duration; use engine_rocks::raw::DB; use engine_rocks::Compat; use raftstore::coprocessor::{ config::{Config, SplitCheckConfigManager}, Coproces...
validate(&scheduler, move |cfg: &Config| { assert_eq!(cfg, &cop_config); }); worker.stop(); }
};
random_line_split
world.rs
use std::any::TypeId; use std::collections::HashMap; use std::hash::Hash; use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use mopa::Any; use bitset::{AtomicBitSet, BitSet, BitSetLike, BitSetOr}; use join::Join; use storage::{Storage, MaskedStorage, Unprotected...
<T: Any+Send+Sync>(&self) -> RwLockWriteGuard<T> { self.resources.get(&TypeId::of::<T>()) .expect("Resource was not registered") .downcast_ref::<RwLock<T>>() .unwrap() .write() .unwrap() } } impl World<()> { /// Creates a new empty `World`. pub...
write_resource
identifier_name
world.rs
use std::any::TypeId; use std::collections::HashMap; use std::hash::Hash; use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use mopa::Any; use bitset::{AtomicBitSet, BitSet, BitSetLike, BitSetOr}; use join::Join; use storage::{Storage, MaskedStorage, Unprotected...
components: HashMap::new(), allocator: RwLock::new(Allocator::new()), resources: HashMap::new() } } /// Registers a new component type and id pair. pub fn register_w_comp_id<T: Component>(&mut self, comp_id: C) { let any = RwLock::new(MaskedStorage::<T>::n...
/// Creates a new empty `World` with the associated component id. pub fn new_w_comp_id() -> World<C> { World {
random_line_split
world.rs
use std::any::TypeId; use std::collections::HashMap; use std::hash::Hash; use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use mopa::Any; use bitset::{AtomicBitSet, BitSet, BitSetLike, BitSetOr}; use join::Join; use storage::{Storage, MaskedStorage, Unprotected...
/// add a new resource to the world pub fn add_resource<T: Any+Send+Sync>(&mut self, resource: T) { let resource = Box::new(RwLock::new(resource)); self.resources.insert(TypeId::of::<T>(), resource); } /// check to see if a resource is present pub fn has_resource<T: Any+Send+Sync>(&...
{ let mut allocator = self.allocator.write().unwrap(); let temp_list = allocator.merge(); for comp in self.components.values() { comp.del_slice(&temp_list); } }
identifier_body
world.rs
use std::any::TypeId; use std::collections::HashMap; use std::hash::Hash; use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use mopa::Any; use bitset::{AtomicBitSet, BitSet, BitSetLike, BitSetOr}; use join::Join; use storage::{Storage, MaskedStorage, Unprotected...
else { gen.raised() }) .unwrap_or(Generation(1)); return Entity(i as Index, gen); } } panic!("No entities left to allocate") } /// Allocate a new entity fn allocate(&mut self) -> Entity { let idx = self.start_from.load(Ordering::Relax...
{ gen }
conditional_block
io_compat.rs
// there's no real io error on a byte slice pub type Error = (); pub type Result<T> = core::result::Result<T, Error>; pub trait Write { fn write(&mut self, buf: &[u8]) -> Result<usize>; } impl Write for &mut [u8] { fn write(&mut self, data: &[u8]) -> Result<usize> { let amt = core::cmp::min(data.len()...
pub fn into_inner(self) -> &'a mut [u8] { self.0 } pub fn position(&self) -> u64 { self.1 as u64 } pub fn set_position(&mut self, pos: u64) { self.1 = pos; } pub fn get_mut(&mut self) -> &mut [u8] { self.0 } pub fn get_ref(&self) -> &[u8] { ...
{ Self(inner, 0) }
identifier_body
io_compat.rs
// there's no real io error on a byte slice pub type Error = (); pub type Result<T> = core::result::Result<T, Error>; pub trait Write { fn write(&mut self, buf: &[u8]) -> Result<usize>; } impl Write for &mut [u8] { fn write(&mut self, data: &[u8]) -> Result<usize> { let amt = core::cmp::min(data.len()...
(inner: &'a mut [u8]) -> Self { Self(inner, 0) } pub fn into_inner(self) -> &'a mut [u8] { self.0 } pub fn position(&self) -> u64 { self.1 as u64 } pub fn set_position(&mut self, pos: u64) { self.1 = pos; } pub fn get_mut(&mut self) -> &mut [u8] { ...
new
identifier_name
io_compat.rs
// there's no real io error on a byte slice pub type Error = (); pub type Result<T> = core::result::Result<T, Error>; pub trait Write { fn write(&mut self, buf: &[u8]) -> Result<usize>; } impl Write for &mut [u8] { fn write(&mut self, data: &[u8]) -> Result<usize> { let amt = core::cmp::min(data.len()...
impl<'a> Seek for Cursor<&'a mut [u8]> { fn seek(&mut self, pos: SeekFrom) -> Result<u64> { let (start, offset) = match pos { SeekFrom::Start(n) => { self.1 = n; return Ok(n); } SeekFrom::Current(n) => (self.1 as u64, n), }; ...
} }
random_line_split
decoder.rs
u8, /// The dc prediction of the component pub dc_pred: i32 } // Markers // Baseline DCT const SOF0: u8 = 0xC0; // Progressive DCT const SOF2: u8 = 0xC2; // Huffman Tables const DHT: u8 = 0xC4; // Restart Interval start and End (standalone) const RST0: u8 = 0xD0; const RST7: u8 = 0xD7; // Start of Image (sta...
(&mut self) -> ImageResult<()> { let _frame_length = try!(self.r.read_u16::<BigEndian>()); let sample_precision = try!(self.r.read_u8()); if sample_precision!= 8 { return Err(image::ImageError::UnsupportedError(format!( "A sample precision of {} is not supported", ...
read_frame_header
identifier_name
decoder.rs
hmax: 0, vmax: 0, interval: 0, mcucount: 0, expected_rst: RST0, row_count: 0, decoded_rows: 0, state: JPEGState::Start, padded_width: 0 } } fn decode_mcu_row(&mut self) -> ImageResult<()> { ...
(r, g, b) } // Section F.2.2.1
random_line_split
decoder.rs
u8, /// The dc prediction of the component pub dc_pred: i32 } // Markers // Baseline DCT const SOF0: u8 = 0xC0; // Progressive DCT const SOF2: u8 = 0xC2; // Huffman Tables const DHT: u8 = 0xC4; // Restart Interval start and End (standalone) const RST0: u8 = 0xD0; const RST7: u8 = 0xD7; // Start of Image (sta...
return Err(image::ImageError::UnsupportedError(format!( "Frames with {} components are not supported", self.num_components ))) } self.padded_width = 8 * ((self.width as usize + 7) / 8); let num_components = self.num_components; se...
{ let _frame_length = try!(self.r.read_u16::<BigEndian>()); let sample_precision = try!(self.r.read_u8()); if sample_precision != 8 { return Err(image::ImageError::UnsupportedError(format!( "A sample precision of {} is not supported", sample_precision...
identifier_body
nist-spce.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! Testing energy computation for SPC/E water using data from //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff
use lumol::consts::K_BOLTZMANN; use lumol::energy::{CoulombicPotential, Ewald, PairRestriction, SharedEwald}; use lumol::energy::{LennardJones, NullPotential, PairInteraction}; use lumol::sys::{System, UnitCell}; use lumol::sys::TrajectoryBuilder; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub ...
//! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-10å-cutoff extern crate lumol;
random_line_split
nist-spce.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! Testing energy computation for SPC/E water using data from //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff //! https://www.nist.gov/mml/csd/c...
.expect("'c' cell parameter is not a float"); system.cell = UnitCell::ortho(a, b, c); for i in 0..system.size() { if i % 3 == 0 { system.add_bond(i, i + 1); system.add_bond(i, i + 2); } } for particle in system.particles_mut() { m...
let path = Path::new(file!()).parent().unwrap().join("data").join("nist-spce").join(path); let mut system = TrajectoryBuilder::new().open(&path).and_then(|mut traj| traj.read()).unwrap(); let mut file = File::open(path).unwrap(); let mut buffer = String::new(); file.read_to_string(&mut buffer).unwra...
identifier_body
nist-spce.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! Testing energy computation for SPC/E water using data from //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff //! https://www.nist.gov/mml/csd/c...
{ let system = get_system("spce-2.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.06590e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist3() { let system = get_system("spce-3.xyz", 10.0); let...
t2()
identifier_name
weakref.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/. */ //! Weak-referenceable JS-managed DOM objects. //! //! IDL interfaces marked as `weakReferenceable` in `Bindings.c...
mem::forget(self); ref_ } } impl<'a, T: WeakReferenceable + 'a> Deref for WeakRefEntry<'a, T> { type Target = WeakRef<T>; fn deref(&self) -> &WeakRef<T> { &self.vec[*self.index] } } impl<'a, T: WeakReferenceable + 'a> Drop for WeakRefEntry<'a, T> { fn drop(&mut self) { ...
/// Remove the entry from the underlying vector of weak references. pub fn remove(self) -> WeakRef<T> { let ref_ = self.vec.swap_remove(*self.index);
random_line_split
weakref.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/. */ //! Weak-referenceable JS-managed DOM objects. //! //! IDL interfaces marked as `weakReferenceable` in `Bindings.c...
else { self.vec.swap_remove(i); } } } /// Clears the vector of its dead references. pub fn retain_alive(&mut self) { self.update(|_| ()); } } impl<T: WeakReferenceable> Deref for WeakRefVec<T> { type Target = Vec<WeakRef<T>>; fn deref(&self) -> &Ve...
{ f(WeakRefEntry { vec: self, index: &mut i }); }
conditional_block
weakref.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/. */ //! Weak-referenceable JS-managed DOM objects. //! //! IDL interfaces marked as `weakReferenceable` in `Bindings.c...
} impl<T: WeakReferenceable> Drop for WeakRef<T> { fn drop(&mut self) { unsafe { let (count, value) = { let weak_box = &*self.ptr.get(); assert!(weak_box.count.get() > 0); let count = weak_box.count.get() - 1; weak_box.count.set(c...
{ // Do nothing. }
identifier_body
weakref.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/. */ //! Weak-referenceable JS-managed DOM objects. //! //! IDL interfaces marked as `weakReferenceable` in `Bindings.c...
<T: WeakReferenceable> { vec: Vec<WeakRef<T>>, } impl<T: WeakReferenceable> WeakRefVec<T> { /// Create a new vector of weak references. pub fn new() -> Self { WeakRefVec { vec: vec![] } } /// Calls a function on each reference which still points to a /// live object. The order of the r...
WeakRefVec
identifier_name
refcounted.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/. */ //! A generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task ...
(&self) -> Temporary<T> { assert!(LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); self.owner_thread == (&*live_references) as *const _ as *const libc::c_void })); unsafe { Temporary::from_unrooted(Unroo...
to_temporary
identifier_name
refcounted.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/. */ //! A generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task ...
pub struct Trusted<T: Reflectable> { /// A pointer to the Rust DOM object of type T, but void to allow /// sending `Trusted<T>` between tasks, regardless of T's sendability. ptr: *const libc::c_void, refcount: Arc<Mutex<usize>>, script_chan: Box<ScriptChan + Send>, owner_thread: *const libc::c_v...
/// A safe wrapper around a raw pointer to a DOM object that can be /// shared among tasks for use in asynchronous operations. The underlying /// DOM object is guaranteed to live at least as long as the last outstanding /// `Trusted<T>` instance.
random_line_split
refcounted.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/. */ //! A generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task ...
} impl<T: Reflectable> Clone for Trusted<T> { fn clone(&self) -> Trusted<T> { { let mut refcount = self.refcount.lock().unwrap(); *refcount += 1; } Trusted { ptr: self.ptr, refcount: self.refcount.clone(), script_chan: self.scrip...
{ assert!(LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); self.owner_thread == (&*live_references) as *const _ as *const libc::c_void })); unsafe { Temporary::from_unrooted(Unrooted::from_raw(self.ptr a...
identifier_body
refcounted.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/. */ //! A generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task ...
} } /// Unpin the given DOM object if its refcount is 0. pub fn cleanup(cx: *mut JSContext, raw_reflectable: TrustedReference) { let TrustedReference(raw_reflectable) = raw_reflectable; LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references =...
{ unsafe { let rootable = (*ptr).reflector().rootable(); JS_AddObjectRoot(cx, rootable); } let refcount = Arc::new(Mutex::new(1)); entry.insert(refcount.clone()); refcount }
conditional_block
mod.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
//! other fns cycle around. The handoff works like this: //! //! - `into(place)` -> fallback is to create a rvalue with `as_rvalue` and assign it to `place` //! - `as_rvalue` -> fallback is to create an Operand with `as_operand` and use `Rvalue::use` //! - `as_operand` -> either invokes `as_constant` or `as_temp` //! -...
random_line_split
screenshot-asynchronous.rs
#[macro_use] extern crate glium; use std::thread; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod screenshot { use glium::Surface; use std::collections::VecDeque; use std::vec::Vec; use std::borrow::Cow; // Container that holds image data as vector of ...
else { None } } } pub struct AsyncScreenshotTaker { screenshot_delay: u64, frame: u64, screenshot_tasks: VecDeque<AsyncScreenshotTask>, } impl AsyncScreenshotTaker { pub fn new(screenshot_delay: u64) -> Self { AsyncScreen...
{ let task = self.0.screenshot_tasks.pop_front().unwrap(); Some(task.read_image_data()) }
conditional_block
screenshot-asynchronous.rs
#[macro_use] extern crate glium; use std::thread; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod screenshot { use glium::Surface; use std::collections::VecDeque; use std::vec::Vec; use std::borrow::Cow; // Container that holds image data as vector of ...
let pixels = { let mut v = Vec::with_capacity(image_data.data.len() * 4); for (a, b, c, d) in image_data.data { v.push(a); v.push(b); v.push(c); v.push(d); ...
// Convert (u8, u8, u8, u8) given by glium's PixelBuffer to flat u8 required by // image's ImageBuffer.
random_line_split
screenshot-asynchronous.rs
#[macro_use] extern crate glium; use std::thread; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod screenshot { use glium::Surface; use std::collections::VecDeque; use std::vec::Vec; use std::borrow::Cow; // Container that holds image data as vector of ...
framebuffer.blit_from_frame(&rect, &blit_target, glium::uniforms::MagnifySamplerFilter::Nearest); // Read the texture into new pixel buffer let pixel_buffer = texture.read_to_pixel_buffer(); ...
{ // Get information about current framebuffer let dimensions = facade.get_context().get_framebuffer_dimensions(); let rect = glium::Rect { left: 0, bottom: 0, width: dimensions.0, height: dimensions.1, }; ...
identifier_body
screenshot-asynchronous.rs
#[macro_use] extern crate glium; use std::thread; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod screenshot { use glium::Surface; use std::collections::VecDeque; use std::vec::Vec; use std::borrow::Cow; // Container that holds image data as vector of ...
{ pub data: Vec<(u8, u8, u8, u8)>, pub width: u32, pub height: u32, } impl glium::texture::Texture2dDataSink<(u8, u8, u8, u8)> for RGBAImageData { fn from_raw(data: Cow<'_, [(u8, u8, u8, u8)]>, width: u32, height: u32) -> Self { RGBAImageData { data:...
RGBAImageData
identifier_name
condvar.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, mutex: &Mutex, dur: Duration) -> bool { let r = ffi::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), dur.num_milliseconds() as DWORD, 0); if...
wait_timeout
identifier_name
condvar.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 ...
#[inline] pub unsafe fn notify_one(&self) { ffi::WakeConditionVariable(self.inner.get()) } #[inline] pub unsafe fn notify_all(&self) { ffi::WakeAllConditionVariable(self.inner.get()) } pub unsafe fn destroy(&self) { //... } }
{ let r = ffi::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), dur.num_milliseconds() as DWORD, 0); if r == 0 { const ERROR_TIMEOUT: DWO...
identifier_body
condvar.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 ...
inner: UnsafeCell { value: ffi::CONDITION_VARIABLE_INIT } }; impl Condvar { #[inline] pub unsafe fn new() -> Condvar { CONDVAR_INIT } #[inline] pub unsafe fn wait(&self, mutex: &Mutex) { let r = ffi::SleepConditionVariableSRW(self.inner.get(), ...
unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} pub const CONDVAR_INIT: Condvar = Condvar {
random_line_split
condvar.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 ...
} #[inline] pub unsafe fn notify_one(&self) { ffi::WakeConditionVariable(self.inner.get()) } #[inline] pub unsafe fn notify_all(&self) { ffi::WakeAllConditionVariable(self.inner.get()) } pub unsafe fn destroy(&self) { //... } }
{ true }
conditional_block
step_by.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. This file may not be copied, modified, or distributed // except according to those terms. /// This module jus...
}
{ StepUp { next: self.start, end: self.end, ammount: ammount } }
identifier_body
step_by.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. This file may not be copied, modified, or distributed // except according to those terms. /// This module jus...
else { None } } } pub trait RangeExt<T> { fn step_up(self, ammount: T) -> StepUp<T>; } impl <T> RangeExt<T> for Range<T> where T: Add<T, Output = T> + PartialOrd + Copy { fn step_up(self, ammount: T) -> StepUp<T> { StepUp { next: self.start, end...
{ let n = self.next; self.next = self.next + self.ammount; Some(n) }
conditional_block
step_by.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. This file may not be copied, modified, or distributed // except according to those terms. /// This module jus...
T: Add<T, Output = T> + PartialOrd + Copy { type Item = T; #[inline] fn next(&mut self) -> Option<T> { if self.next < self.end { let n = self.next; self.next = self.next + self.ammount; Some(n) } else { None } } } pub trai...
end: T, ammount: T } impl <T> Iterator for StepUp<T> where
random_line_split
step_by.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. This file may not be copied, modified, or distributed // except according to those terms. /// This module jus...
<T> { next: T, end: T, ammount: T } impl <T> Iterator for StepUp<T> where T: Add<T, Output = T> + PartialOrd + Copy { type Item = T; #[inline] fn next(&mut self) -> Option<T> { if self.next < self.end { let n = self.next; self.next = self.next + self.amm...
StepUp
identifier_name
kqueue.rs
use std::{cmp, fmt, ptr}; #[cfg(not(target_os = "netbsd"))] use std::os::raw::{c_int, c_short}; use std::os::unix::io::AsRawFd; use std::os::unix::io::RawFd; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::time::Duration; use libc::{self, time_t}; use {io, Re...
#[inline] pub fn is_empty(&self) -> bool { self.events.is_empty() } pub fn get(&self, idx: usize) -> Option<Event> { self.events.get(idx).map(|e| *e) } fn coalesce(&mut self, awakener: Token) -> bool { let mut ret = false; self.events.clear(); self.eve...
{ self.events.capacity() }
identifier_body
kqueue.rs
use std::{cmp, fmt, ptr}; #[cfg(not(target_os = "netbsd"))] use std::os::raw::{c_int, c_short}; use std::os::unix::io::AsRawFd; use std::os::unix::io::RawFd; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::time::Duration; use libc::{self, time_t}; use {io, Re...
for change in changes.iter() { debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR); if change.data!= 0 && change.data as i32!= libc::ENOENT { return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32)); } ...
{ return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32)); }
conditional_block