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
wrapper.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 core::nonzero::NonZero; use dom::bindings::js::{MutNullableJS, Root}; use dom::bindings::reflector::DomObject;...
unsafe { NonZero::new(extension.reflector().get_jsobject().get()) } } fn is_supported(&self, ext: &WebGLExtensions) -> bool { self.extension.get().is_some() || T::is_supported(ext) } fn enable(&self, ext: &WebGLExtensions) { T::enable(ext); } fn na...
{ self.enable(ext); }
conditional_block
uint.rs
// Copyright 2015-2017 Parity Technologies (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 lat...
#[test] fn uint_into() { assert_eq!(U256::from(10), Uint(U256::from(10)).into()); } }
{ let s = r#"["0xa", "10", "", "0x", 0]"#; let deserialized: Vec<Uint> = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, vec![ Uint(U256::from(10)), Uint(U256::from(10)), Uint(U256::from(0)), Uint(U256::from(0)), Uint(U256::from(0)) ]); }
identifier_body
uint.rs
// Copyright 2015-2017 Parity Technologies (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 lat...
<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer { deserializer.deserialize(UintVisitor) } } struct UintVisitor; impl Visitor for UintVisitor { type Value = Uint; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a hex encoded or decimal uint") } ...
deserialize
identifier_name
uint.rs
// Copyright 2015-2017 Parity Technologies (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 lat...
// along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Lenient uint json deserialization for test json files. use std::fmt; use std::str::FromStr; use serde::{Deserialize, Deserializer}; use serde::de::{Error, Visitor}; use util::U256; /// Lenient uint json deserialization for test json files. #[deri...
// You should have received a copy of the GNU General Public License
random_line_split
instr_ktestq.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test;
fn ktestq_1() { run_test(&Instruction { mnemonic: Mnemonic::KTESTQ, operand1: Some(Direct(K4)), operand2: Some(Direct(K1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 248, 153, 225], OperandSize::Dword) } #[test] fn kte...
#[test]
random_line_split
instr_ktestq.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn ktestq_1() { run_test(&Instruction { mnemonic: Mnemonic::KTESTQ, operand1: Some(Direct(K4...
{ run_test(&Instruction { mnemonic: Mnemonic::KTESTQ, operand1: Some(Direct(K2)), operand2: Some(Direct(K5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 248, 153, 213], OperandSize::Qword) }
identifier_body
instr_ktestq.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn ktestq_1() { run_test(&Instruction { mnemonic: Mnemonic::KTESTQ, operand1: Some(Direct(K4...
() { run_test(&Instruction { mnemonic: Mnemonic::KTESTQ, operand1: Some(Direct(K2)), operand2: Some(Direct(K5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 248, 153, 213], OperandSize::Qword) }
ktestq_2
identifier_name
config-helloworld.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_config::model::ResourceType; use aws_sdk_config::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt...
/// * `-resource_type RESOURCE-TYPE` - The type of resource, such as **AWS::EC2::SecurityGroup**. /// * `[-r REGION]` - The AWS Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**...
/// NOTE: AWS Config must be enabled to discover resources /// # Arguments /// /// * `-resource_id RESOURCE-ID` - The ID of the resource.
random_line_split
config-helloworld.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_config::model::ResourceType; use aws_sdk_config::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt...
get_history(&client, &resource_id, parsed).await }
{ panic!( "unknown resource type: `{}`. Valid resource types: {:#?}", &resource_type, ResourceType::values() ) }
conditional_block
config-helloworld.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_config::model::ResourceType; use aws_sdk_config::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt...
{ /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The resource id. #[structopt(long)] resource_id: String, /// The resource type, eg. "AWS::EC2::SecurityGroup" #[structopt(long)] resource_type: String, /// Whether to display additional information. ...
Opt
identifier_name
uievent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
pub fn new(window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, view: Option<&Window>, detail: i32) -> DomRoot<UIEvent> { let ev = UIEvent::new_uninitialized(window); ev.InitUIEvent(type...
{ reflect_dom_object(Box::new(UIEvent::new_inherited()), window, UIEventBinding::Wrap) }
identifier_body
uievent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
() -> UIEvent { UIEvent { event: Event::new_inherited(), view: Default::default(), detail: Cell::new(0), } } pub fn new_uninitialized(window: &Window) -> DomRoot<UIEvent> { reflect_dom_object(Box::new(UIEvent::new_inherited()), ...
new_inherited
identifier_name
uievent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
event.init_event(Atom::from(type_), can_bubble, cancelable); self.view.set(view); self.detail.set(detail); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ return; }
conditional_block
uievent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32) { let event = self.upcast::<Event>(); if event.dispatching() { return; } event.init_event(...
// https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent fn InitUIEvent(&self,
random_line_split
snapshot.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::collections::HashMap; use std::fmt; use std::hash; use std::iter::Iterator; use std::path::{Path, PathBuf}; use std::sync::Arc; use deepsize::DeepSizeOf; use futures::future; u...
(store: Store, digest: DirectoryDigest) -> Result<Snapshot, String> { Ok(Self { digest: digest.as_digest(), tree: store.load_digest_trie(digest).await?, }) } pub async fn get_directory_or_err( store: Store, digest: Digest, ) -> Result<remexec::Directory, String> { let maybe_dir = ...
from_digest
identifier_name
snapshot.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::collections::HashMap; use std::fmt; use std::hash; use std::iter::Iterator; use std::path::{Path, PathBuf}; use std::sync::Arc; use deepsize::DeepSizeOf; use futures::future; u...
Self::new(s.digest, s.tree) } } // StoreFileByDigest allows a File to be saved to an underlying Store, in such a way that it can be // looked up by the Digest produced by the store_by_digest method. // It is a separate trait so that caching implementations can be written which wrap the Store (used // to store th...
impl From<Snapshot> for DirectoryDigest { fn from(s: Snapshot) -> Self {
random_line_split
snapshot.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::collections::HashMap; use std::fmt; use std::hash; use std::iter::Iterator; use std::path::{Path, PathBuf}; use std::sync::Arc; use deepsize::DeepSizeOf; use futures::future; u...
} /// # Safety /// /// This should only be used for testing, as this will always create an invalid Snapshot. pub unsafe fn create_for_testing_ffi( digest: Digest, files: Vec<String>, dirs: Vec<String>, ) -> Result<Self, String> { // NB: All files receive the EMPTY_DIGEST. let file_dige...
{ let posix_fs = Arc::new(PosixFS::new_with_symlink_behavior( root_path, GitignoreStyleExcludes::create(vec![])?, executor, SymlinkBehavior::Oblivious, )?); let path_stats = posix_fs .expand_globs(path_globs, None) .await .map_err(|err| format!(...
conditional_block
to_hilbert.rs
extern crate byteorder; extern crate COST; use std::fs::File; use std::io::BufWriter; use byteorder::{WriteBytesExt, LittleEndian}; use COST::graph_iterator::NodesEdgesMemMapper; fn
() { if std::env::args().len()!= 2 && std::env::args().len()!= 3 { println!("Usage: to_hilbert <prefix> [--dense]"); println!("NOTE: <prefix>.upper and <prefix>.lower will be overwritten."); return; } let prefix = std::env::args().nth(1).expect("name unavailable"); let dense = ...
main
identifier_name
to_hilbert.rs
extern crate byteorder; extern crate COST; use std::fs::File; use std::io::BufWriter; use byteorder::{WriteBytesExt, LittleEndian}; use COST::graph_iterator::NodesEdgesMemMapper; fn main() { if std::env::args().len()!= 2 && std::env::args().len()!= 3
let prefix = std::env::args().nth(1).expect("name unavailable"); let dense = std::env::args().nth(2) == Some("--dense".to_string()); let graph = NodesEdgesMemMapper::new(&prefix); let mut u_writer = BufWriter::new(File::create(format!("{}.upper", prefix)).unwrap()); let mut l_writer = BufWriter::...
{ println!("Usage: to_hilbert <prefix> [--dense]"); println!("NOTE: <prefix>.upper and <prefix>.lower will be overwritten."); return; }
conditional_block
to_hilbert.rs
extern crate byteorder; extern crate COST; use std::fs::File; use std::io::BufWriter; use byteorder::{WriteBytesExt, LittleEndian}; use COST::graph_iterator::NodesEdgesMemMapper; fn main()
l_writer.write_u16::<LittleEndian>(lx).unwrap(); l_writer.write_u16::<LittleEndian>(ly).unwrap(); } }); }
{ if std::env::args().len() != 2 && std::env::args().len() != 3 { println!("Usage: to_hilbert <prefix> [--dense]"); println!("NOTE: <prefix>.upper and <prefix>.lower will be overwritten."); return; } let prefix = std::env::args().nth(1).expect("name unavailable"); let dense = s...
identifier_body
to_hilbert.rs
extern crate byteorder; extern crate COST; use std::fs::File; use std::io::BufWriter; use byteorder::{WriteBytesExt, LittleEndian}; use COST::graph_iterator::NodesEdgesMemMapper; fn main() { if std::env::args().len()!= 2 && std::env::args().len()!= 3 { println!("Usage: to_hilbert <prefix> [--dense]");
let prefix = std::env::args().nth(1).expect("name unavailable"); let dense = std::env::args().nth(2) == Some("--dense".to_string()); let graph = NodesEdgesMemMapper::new(&prefix); let mut u_writer = BufWriter::new(File::create(format!("{}.upper", prefix)).unwrap()); let mut l_writer = BufWriter::ne...
println!("NOTE: <prefix>.upper and <prefix>.lower will be overwritten."); return; }
random_line_split
auth.rs
use iron::status; use iron::{BeforeMiddleware, IronError, IronResult, Request, Response}; use crate::util::StringError; pub struct AuthChecker { username: String, password: String, } impl AuthChecker { pub fn
(s: &str) -> Result<AuthChecker, StringError> { let parts = s.splitn(2, ':').collect::<Vec<&str>>(); if parts.len() == 2 { Ok(AuthChecker { username: parts[0].to_owned(), password: parts[1].to_owned(), }) } else { Err(StringErro...
new
identifier_name
auth.rs
use iron::status; use iron::{BeforeMiddleware, IronError, IronResult, Request, Response}; use crate::util::StringError;
} impl AuthChecker { pub fn new(s: &str) -> Result<AuthChecker, StringError> { let parts = s.splitn(2, ':').collect::<Vec<&str>>(); if parts.len() == 2 { Ok(AuthChecker { username: parts[0].to_owned(), password: parts[1].to_owned(), }) ...
pub struct AuthChecker { username: String, password: String,
random_line_split
auth.rs
use iron::status; use iron::{BeforeMiddleware, IronError, IronResult, Request, Response}; use crate::util::StringError; pub struct AuthChecker { username: String, password: String, } impl AuthChecker { pub fn new(s: &str) -> Result<AuthChecker, StringError> { let parts = s.splitn(2, ':').collect:...
None => { let mut resp = Response::with(status::Unauthorized); resp.headers .set_raw("WWW-Authenticate", vec![b"Basic realm=\"main\"".to_vec()]); Err(IronError { error: Box::new(StringError("authorization error".to_owned(...
{ use iron::headers::{Authorization, Basic}; match req.headers.get::<Authorization<Basic>>() { Some(&Authorization(Basic { ref username, ref password, })) => { if username == self.username.as_str() && password == &Some(self.passwor...
identifier_body
auth.rs
use iron::status; use iron::{BeforeMiddleware, IronError, IronResult, Request, Response}; use crate::util::StringError; pub struct AuthChecker { username: String, password: String, } impl AuthChecker { pub fn new(s: &str) -> Result<AuthChecker, StringError> { let parts = s.splitn(2, ':').collect:...
} None => { let mut resp = Response::with(status::Unauthorized); resp.headers .set_raw("WWW-Authenticate", vec![b"Basic realm=\"main\"".to_vec()]); Err(IronError { error: Box::new(StringError("authorization e...
{ Err(IronError { error: Box::new(StringError("authorization error".to_owned())), response: Response::with(( status::Unauthorized, "Wrong username or password.", )), ...
conditional_block
uname.rs
#![crate_name = "uu_uname"] /* * This file is part of the uutils coreutils package. * * (c) Joao Oliveira <joaoxsouls@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: uname (GNU coreutils) 8.21 */ ...
static NAME: &'static str = "uname"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("a", "all", "Behave as though all of the options -mnrsv w...
{ let mut uts: utsname = uninitialized(); uname(&mut uts); Uts { sysname: string_from_c_str(uts.sysname.as_ptr() as *const i8), nodename: string_from_c_str(uts.nodename.as_ptr() as *const i8), release: string_from_c_str(uts.release.as_ptr() as *const i8), version: stri...
identifier_body
uname.rs
#![crate_name = "uu_uname"] /*
* This file is part of the uutils coreutils package. * * (c) Joao Oliveira <joaoxsouls@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: uname (GNU coreutils) 8.21 */ extern crate getopts; extern cra...
random_line_split
uname.rs
#![crate_name = "uu_uname"] /* * This file is part of the uutils coreutils package. * * (c) Joao Oliveira <joaoxsouls@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: uname (GNU coreutils) 8.21 */ ...
() -> Uts { let mut uts: utsname = uninitialized(); uname(&mut uts); Uts { sysname: string_from_c_str(uts.sysname.as_ptr() as *const i8), nodename: string_from_c_str(uts.nodename.as_ptr() as *const i8), release: string_from_c_str(uts.release.as_ptr() as *const i8), vers...
getuname
identifier_name
main.rs
extern crate txtpic_lib; extern crate image; extern crate clap; use clap::{App, Arg}; use std::path::Path; use txtpic_lib::character_set::CharacterSet; use txtpic_lib::text_image::TextImage; fn
() { let additional_help = "\ Note: the --width option attempts find a width close to the target width that preserves the \ aspect ratio of the original image. For certain images, there may be only one or two valid \ widths within a reasonable range, so the --width option may not appear to have an effect. In this \...
main
identifier_name
main.rs
extern crate txtpic_lib; extern crate image; extern crate clap; use clap::{App, Arg}; use std::path::Path; use txtpic_lib::character_set::CharacterSet; use txtpic_lib::text_image::TextImage; fn main() { let additional_help = "\ Note: the --width option attempts find a width close to the target width that preserves...
} }; if matches.is_present("invert") { char_set = char_set.invert(); }; let width = matches.value_of("width").unwrap().parse::<u32>().unwrap(); let txt_img = TextImage::from(img, char_set, width); print!("{}", txt_img); }
"large" => CharacterSet::preset_large(), "emoji" => CharacterSet::preset_emoji(), &_ => panic!("Unknown preset: {}", matches.value_of("preset").unwrap())
random_line_split
main.rs
extern crate txtpic_lib; extern crate image; extern crate clap; use clap::{App, Arg}; use std::path::Path; use txtpic_lib::character_set::CharacterSet; use txtpic_lib::text_image::TextImage; fn main()
.default_value("80") .help("An approximate width value for the result") .validator(|arg: String| { match arg.parse::<u32>() { Err(_) => Err("Width must be a positive ...
{ let additional_help = "\ Note: the --width option attempts find a width close to the target width that preserves the \ aspect ratio of the original image. For certain images, there may be only one or two valid \ widths within a reasonable range, so the --width option may not appear to have an effect. In this \ ca...
identifier_body
mod.rs
// The MIT License (MIT) // // Copyright (c) 2015 dinowernli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy...
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pub mod environment;
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
random_line_split
mod.rs
// Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <apoelstra@wpsoftware.net> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warrant...
(&self) -> Option<&error::Error> { match *self { Error::Io(ref e) => Some(e), Error::ByteOrder(ref e) => Some(e), Error::Detail(_, ref e) => Some(e), _ => None } } fn description(&self) -> &str { match *self { Error::Io(ref e) ...
cause
identifier_name
mod.rs
// Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <apoelstra@wpsoftware.net> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warrant...
Error::ParseFailed => "parsing error", Error::PrevHashNotFound => "prevhash not found", Error::SpvBadTarget => "target incorrect", Error::SpvBadProofOfWork => "target correct but not attained", Error::Detail(_, ref e) => e.description() } } } /// ...
Error::DuplicateHash => "duplicate hash", Error::BlockNotFound => "no such block",
random_line_split
mod.rs
// Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <apoelstra@wpsoftware.net> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warrant...
} impl error::Error for Error { fn cause(&self) -> Option<&error::Error> { match *self { Error::Io(ref e) => Some(e), Error::ByteOrder(ref e) => Some(e), Error::Detail(_, ref e) => Some(e), _ => None } } fn description(&self) -> &str { ...
{ match *self { Error::Io(ref e) => fmt::Display::fmt(e, f), Error::ByteOrder(ref e) => fmt::Display::fmt(e, f), Error::BadNetworkMagic(exp, got) => write!(f, "expected network magic 0x{:x}, got 0x{:x}", exp, got), Error::BadNetworkMessage(ref got) => write!(f, "i...
identifier_body
main.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...
(&self, _ctx: ExecutionContext<'_>, _arg: String) -> Self::Output { Ok(()) } } impl Service for TimestampingService {} fn main() { let instance_id = 512; // Create a testkit for a network with four validators. let service = TimestampingService; let mut testkit = TestKitBuilder::validator()...
timestamp
identifier_name
main.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...
} impl Service for TimestampingService {} fn main() { let instance_id = 512; // Create a testkit for a network with four validators. let service = TimestampingService; let mut testkit = TestKitBuilder::validator() .with_validators(4) .with(Spec::new(service).with_instance(instance_id, "...
{ Ok(()) }
identifier_body
main.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...
struct TimestampingService; impl TimestampingInterface<ExecutionContext<'_>> for TimestampingService { type Output = Result<(), ExecutionError>; fn timestamp(&self, _ctx: ExecutionContext<'_>, _arg: String) -> Self::Output { Ok(()) } } impl Service for TimestampingService {} fn main() { let ...
#[derive(Debug, ServiceDispatcher, ServiceFactory)] #[service_factory(artifact_name = "timestamping", artifact_version = "1.0.0")] #[service_dispatcher(implements("TimestampingInterface"))]
random_line_split
map.rs
//! An immutable map constructed at compile time. use core::borrow::Borrow; use core::ops::Index; use core::slice; use core::fmt; use core::iter::IntoIterator; use phf_shared::{self, PhfHash}; use Slice; /// An immutable map constructed at compile time. /// /// ## Note /// /// The fields of this struct are public so t...
else { None } } /// Returns an iterator over the key/value pairs in the map. /// /// Entries are returned in an arbitrary but fixed order. pub fn entries<'a>(&'a self) -> Entries<'a, K, V> { Entries { iter: self.entries.iter() } } /// Returns an iterator over t...
{ Some((&entry.0, &entry.1)) }
conditional_block
map.rs
//! An immutable map constructed at compile time. use core::borrow::Borrow; use core::ops::Index; use core::slice; use core::fmt; use core::iter::IntoIterator; use phf_shared::{self, PhfHash}; use Slice; /// An immutable map constructed at compile time. /// /// ## Note /// /// The fields of this struct are public so t...
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a, K, V> DoubleEndedIterator for Entries<'a, K, V> { fn next_back(&mut self) -> Option<(&'a K, &'a V)> { self.iter.next_back().map(|e| (&e.0, &e.1)) } } impl<'a, K, V> ExactSizeIterator for Entries<'a, K,...
{ self.iter.next().map(|&(ref k, ref v)| (k, v)) }
identifier_body
map.rs
//! An immutable map constructed at compile time. use core::borrow::Borrow; use core::ops::Index; use core::slice;
use phf_shared::{self, PhfHash}; use Slice; /// An immutable map constructed at compile time. /// /// ## Note /// /// The fields of this struct are public so that they may be initialized by the /// `phf_map!` macro and code generation. They are subject to change at any /// time and should never be accessed directly. p...
use core::fmt; use core::iter::IntoIterator;
random_line_split
map.rs
//! An immutable map constructed at compile time. use core::borrow::Borrow; use core::ops::Index; use core::slice; use core::fmt; use core::iter::IntoIterator; use phf_shared::{self, PhfHash}; use Slice; /// An immutable map constructed at compile time. /// /// ## Note /// /// The fields of this struct are public so t...
<T:?Sized>(&self, key: &T) -> Option<&V> where T: Eq + PhfHash, K: Borrow<T> { self.get_entry(key).map(|e| e.1) } /// Returns a reference to the map's internal static instance of the given /// key. /// /// This can be useful for interning schemes. pub fn get_ke...
get
identifier_name
build.rs
// build.rs use std::env; use std::fs; use std::path::Path; use std::path::PathBuf; fn main() { // from aow-rust let root_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let dest_dir = get_out_path(&root_dir, "assets/"); let asset_source_path = Path::new(&root_dir).join("assets"); println!("Copyin...
(out_dir: &str, file_name: &str) -> PathBuf { let debug = match env::var("DEBUG") { Ok(s) => s == "true", _ => false, }; if debug { return Path::new(&out_dir).join("target/debug/").join(file_name); } Path::new(&out_dir).join("target/release/").join(file_name) }
get_out_path
identifier_name
build.rs
// build.rs use std::env; use std::fs; use std::path::Path; use std::path::PathBuf; fn main() { // from aow-rust let root_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let dest_dir = get_out_path(&root_dir, "assets/"); let asset_source_path = Path::new(&root_dir).join("assets"); println!("Copyin...
_ => false, }; if debug { return Path::new(&out_dir).join("target/debug/").join(file_name); } Path::new(&out_dir).join("target/release/").join(file_name) }
let debug = match env::var("DEBUG") { Ok(s) => s == "true",
random_line_split
build.rs
// build.rs use std::env; use std::fs; use std::path::Path; use std::path::PathBuf; fn main() { // from aow-rust let root_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let dest_dir = get_out_path(&root_dir, "assets/"); let asset_source_path = Path::new(&root_dir).join("assets"); println!("Copyin...
{ let debug = match env::var("DEBUG") { Ok(s) => s == "true", _ => false, }; if debug { return Path::new(&out_dir).join("target/debug/").join(file_name); } Path::new(&out_dir).join("target/release/").join(file_name) }
identifier_body
main.rs
extern crate docopt; extern crate futures; extern crate http; extern crate hyper; #[macro_use] extern crate serde_derive; use docopt::Docopt; use std::env; mod server; const USAGE: &'static str = " HTTP server for theremins.club Usage: theremins-http-server [--port <port>] [--ws-url <url>] theremins-http-server...
let port = args.flag_port .or_else(|| { env::var("THEREMINS_HTTP_PORT") .ok() .and_then(|foo| foo.parse().ok()) }) .unwrap_or(8000); let ws_url = args.flag_ws_url .or_else(|| env::var("THEREMINS_WS_URL").ok()) .unwrap_or("ws://local...
random_line_split
main.rs
extern crate docopt; extern crate futures; extern crate http; extern crate hyper; #[macro_use] extern crate serde_derive; use docopt::Docopt; use std::env; mod server; const USAGE: &'static str = " HTTP server for theremins.club Usage: theremins-http-server [--port <port>] [--ws-url <url>] theremins-http-server...
() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); let port = args.flag_port .or_else(|| { env::var("THEREMINS_HTTP_PORT") .ok() .and_then(|foo| foo.parse().ok()) }) .unwrap_or(8000...
main
identifier_name
type_enforcement.rs
use crate::ast::AstNode; use secsp_parser::syntax::{SyntaxKind, SyntaxNode}; use secsp_syntax_derive::AstType; #[derive(AstType)] #[ast(kind = "NODE_TE_RULE")] pub struct TeRule(SyntaxNode); #[derive(Debug, PartialEq, Eq)] pub enum TeRuleKind { Allow, AuditAllow, DontAudit, NeverAllow, } impl TeRule...
() { test_rule_kind(TeRuleKind::Allow, "allow src dest : perms;"); } #[test] fn test_dont_audit() { test_rule_kind(TeRuleKind::DontAudit, "dont_audit src dest : perms;"); } #[test] fn test_audit_allow() { test_rule_kind(TeRuleKind::AuditAllow, "audit_allow src dest : pe...
test_allow
identifier_name
type_enforcement.rs
use crate::ast::AstNode; use secsp_parser::syntax::{SyntaxKind, SyntaxNode}; use secsp_syntax_derive::AstType; #[derive(AstType)] #[ast(kind = "NODE_TE_RULE")] pub struct TeRule(SyntaxNode); #[derive(Debug, PartialEq, Eq)] pub enum TeRuleKind { Allow, AuditAllow, DontAudit, NeverAllow, } impl TeRule...
#[test] fn test_never_allow() { test_rule_kind(TeRuleKind::NeverAllow, "never_allow src dest : perms;"); } }
{ test_rule_kind(TeRuleKind::AuditAllow, "audit_allow src dest : perms;"); }
identifier_body
type_enforcement.rs
use crate::ast::AstNode; use secsp_parser::syntax::{SyntaxKind, SyntaxNode}; use secsp_syntax_derive::AstType; #[derive(AstType)] #[ast(kind = "NODE_TE_RULE")] pub struct TeRule(SyntaxNode); #[derive(Debug, PartialEq, Eq)] pub enum TeRuleKind { Allow, AuditAllow, DontAudit, NeverAllow, } impl TeRule...
.children_with_tokens() .find_map(|child| { if let Some(tok) = child.into_token() { let rule_kind = match tok.kind() { SyntaxKind::KW_ALLOW => TeRuleKind::Allow, SyntaxKind::KW_AUDIT_ALLOW => TeRuleKind::AuditAllow...
random_line_split
check-static-values-constraints.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 ...
; impl Drop for UnsafeStruct { fn drop(&mut self) {} } // Types with destructors are not allowed for statics static STATIC10: UnsafeStruct = UnsafeStruct; //~^ ERROR statics are not allowed to have destructor struct MyOwned; static STATIC11: Box<MyOwned> = box MyOwned; //~^ ERROR statics are not allowed to have...
UnsafeStruct
identifier_name
check-static-values-constraints.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 ...
} impl Drop for UnsafeEnum { fn drop(&mut self) {} } static STATIC4: UnsafeEnum = UnsafeEnum::Variant5; //~^ ERROR statics are not allowed to have destructors static STATIC5: UnsafeEnum = UnsafeEnum::Variant6(0); //~^ ERROR statics are not allowed to have destructors struct SafeStruct { field1: SafeEnum, ...
// are considered unsafe if their enum type implements // a destructor. enum UnsafeEnum { Variant5, Variant6(int)
random_line_split
check-static-values-constraints.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let y = { static x: Box<int> = box 3; x }; //~^ ERROR statics are not allowed to have custom pointers }
identifier_body
while-loop-constraints-2.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 mut y: isize = 42; let mut z: isize = 42; let mut x: isize; while z < 50 { z += 1; while false { x = y; y = z; } println!("{}", y); } assert!((y == 42 && z == 50)); }
identifier_body
while-loop-constraints-2.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 mut y: isize = 42; let mut z: isize = 42; let mut x: isize; while z < 50 { z += 1; while false { x = y; y = z; } println!("{}", y); } assert!((y == 42 && z == 50)); }
main
identifier_name
while-loop-constraints-2.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 ...
}
random_line_split
state.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 treediff::{self, Delegate}; use serde::{Deserialize, Serialize}; use serde_json; pub struct State<T> { cu...
pub fn has_changed(&self) -> bool { self.has_changed } } // FIXME: can we generate all of these with macros? // FIXME: I'm not even sure everything bound to a string #[allow(non_camel_case_types)] #[derive(Clone, Debug, PartialEq)] pub enum DiffKey { // Don't keep the string Unknown(String),...
{ if self.has_changed() { let from = serde_json::to_value(&self.last_state).unwrap(); let to = serde_json::to_value(&self.current_state).unwrap(); let mut recorder = DiffRecorder::new(); treediff::diff(&from, &to, &mut recorder); recorder.changes ...
identifier_body
state.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 treediff::{self, Delegate}; use serde::{Deserialize, Serialize}; use serde_json; pub struct State<T> { cu...
{ // Don't keep the string Unknown(String), Index(usize), Alive, Dead, is_background, dark_theme, cursor, tabs, sidebar_is_open, logs_visible, debug_options, status, urlbar_focused, options_open, title, id, zoom, url, user_input, can_g...
DiffKey
identifier_name
state.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 treediff::{self, Delegate}; use serde::{Deserialize, Serialize}; use serde_json; pub struct State<T> { cu...
// FIXME: I'm not even sure everything bound to a string #[allow(non_camel_case_types)] #[derive(Clone, Debug, PartialEq)] pub enum DiffKey { // Don't keep the string Unknown(String), Index(usize), Alive, Dead, is_background, dark_theme, cursor, tabs, sidebar_is_open, logs_v...
self.has_changed } } // FIXME: can we generate all of these with macros?
random_line_split
json_aid.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
fn u256_from_str(s: &str) -> U256 { if s.len() >= 2 && &s[0..2] == "0x" { U256::from_str(&s[2..]).unwrap_or_else(|_| U256::zero()) } else { U256::from_dec_str(s).unwrap_or_else(|_| U256::zero()) } } impl FromJson for Bytes { fn from_json(json: &Json) -> Self { match *json { Json::String(ref s) => match s.len(...
{ if s.len() >= 2 && &s[0..2] == "0x" { &s[2..] } else { s } }
identifier_body
json_aid.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....
} #[test] fn u256_from_json() { let j = Json::from_str("{ \"dec\": \"10\", \"hex\": \"0x0a\", \"int\": 10 }").unwrap(); let v: U256 = xjson!(&j["dec"]); assert_eq!(U256::from(10), v); let v: U256 = xjson!(&j["hex"]); assert_eq!(U256::from(10), v); let v: U256 = xjson!(&j["int"]); assert_eq!(U256::from(10), v);...
impl FromJson for u16 { fn from_json(json: &Json) -> Self { U256::from_json(json).low_u64() as u16 }
random_line_split
json_aid.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....
(json: &Json) -> Self { match *json { Json::String(ref o) if o.is_empty() => None, Json::Null => None, _ => Some(FromJson::from_json(json)), } } } impl FromJson for u64 { fn from_json(json: &Json) -> Self { U256::from_json(json).low_u64() } } impl FromJson for u32 { fn from_json(json: &Json) -> Sel...
from_json
identifier_name
mod.rs
pub mod addr; pub mod alloc; pub mod page; use core::iter::IntoIterator; use arrayvec::ArrayVec; use itertools::put_back; use itertools::structs::PutBack; pub use addr::*; /// A map of the machine's physical memory. #[derive(Clone)] #[repr(C)] pub struct Map { entries: [MapEntry; 128], num_entries: u64, } ...
.copied(), ) .collect(); assert_eq!( result, [ Extent::from_raw(3, 2), Extent::from_raw(10, 2), Extent::from_raw(16, 4), Extent::from_raw(25, 2), Extent::from_raw(36, 8) ...
{ let result: Vec<_> = remove_reserved( [ Extent::from_raw(0, 5), Extent::from_raw(7, 2), Extent::from_raw(10, 10), Extent::from_raw(25, 5), Extent::from_raw(35, 10), ] .iter() .copied...
identifier_body
mod.rs
pub mod addr; pub mod alloc; pub mod page; use core::iter::IntoIterator; use arrayvec::ArrayVec; use itertools::put_back; use itertools::structs::PutBack; pub use addr::*; /// A map of the machine's physical memory. #[derive(Clone)] #[repr(C)] pub struct Map { entries: [MapEntry; 128], num_entries: u64, } ...
(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("Map") .field("entries", &self.entries()) .field("num_entries", &self.num_entries) .finish() } } #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct MapEntry { pub extent: PhysExtent, pu...
fmt
identifier_name
mod.rs
pub mod addr; pub mod alloc; pub mod page; use core::iter::IntoIterator; use arrayvec::ArrayVec; use itertools::put_back; use itertools::structs::PutBack; pub use addr::*; /// A map of the machine's physical memory. #[derive(Clone)] #[repr(C)] pub struct Map { entries: [MapEntry; 128], num_entries: u64, } ...
} // Get the next hole. If there are none left, we can simply return // `block`. let hole = match self.holes.next() { Some(hole) => hole, None => return Some(Some(block)), }; // If `hole` is completely after `block`, we can return `block`. ...
{ self.holes.put_back(hole); break; }
conditional_block
mod.rs
pub mod addr; pub mod alloc; pub mod page; use core::iter::IntoIterator; use arrayvec::ArrayVec; use itertools::put_back; use itertools::structs::PutBack; pub use addr::*; /// A map of the machine's physical memory. #[derive(Clone)] #[repr(C)] pub struct Map { entries: [MapEntry; 128], num_entries: u64, } ...
let result: Vec<_> = remove_reserved([].iter().copied(), [].iter().copied()).collect(); assert_eq!(result, []); } #[test] fn remove_reserved_no_blocks() { let result: Vec<_> = remove_reserved( [].iter().copied(), [Extent::from_raw(5, 5), Extent::from_raw(15, ...
[].iter().copied(), ) .collect(); assert_eq!(result, [Extent::from_raw(1, 4), Extent::from_raw(10, 4)]);
random_line_split
vec-matching.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x = [1, 2, 3]; match x { [a, b, c..] => { assert_eq!(a, 1); assert_eq!(b, 2); let expected: &[_] = &[3]; assert_eq!(c, expected); } } match x { [a.., b, c] => { let expected: &[_] = &[1]; assert_eq!(...
b
identifier_name
vec-matching.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 d() { let x = [1, 2, 3]; let branch = match x { [1, 1,..] => 0, [1, 2, 3,..] => 1, [1, 2,..] => 2, _ => 3 }; assert_eq!(branch, 1); } fn e() { let x: &[isize] = &[1, 2, 3]; match x { [1, 2] => (), [..] => () } } ...
random_line_split
vec-matching.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 e() { let x: &[isize] = &[1, 2, 3]; match x { [1, 2] => (), [..] => () } } pub fn main() { a(); b(); c(); d(); e(); }
{ let x = [1, 2, 3]; let branch = match x { [1, 1, ..] => 0, [1, 2, 3, ..] => 1, [1, 2, ..] => 2, _ => 3 }; assert_eq!(branch, 1); }
identifier_body
interface.rs
/** * Websocket implementation taken from https://github.com/nbaksalyar/mio-websocket */ /// High-level WebSocket library interface use std::net::SocketAddr; use std::thread; use std::sync::mpsc; use std::time::Duration; use mio::{Token, EventLoop, EventSet, PollOpt, Sender, NotifyError}; use mio::tcp::{TcpListene...
result @ _ => return result, } } } }
{ // The notify queue is full, retry after some time. val = ret; thread::sleep(Duration::from_millis(10)); }
conditional_block
interface.rs
/** * Websocket implementation taken from https://github.com/nbaksalyar/mio-websocket */ /// High-level WebSocket library interface use std::net::SocketAddr; use std::thread; use std::sync::mpsc; use std::time::Duration; use mio::{Token, EventLoop, EventSet, PollOpt, Sender, NotifyError}; use mio::tcp::{TcpListene...
fn send_internal(&mut self, msg: WebSocketInternalMessage) -> Result<(), NotifyError<WebSocketInternalMessage>> { let mut val = msg; loop { match self.event_loop_tx.send(val) { Err(NotifyError::Full(ret)) => { // The notify queue is full, retry after some time. val = ret; ...
{ self.send_internal(WebSocketInternalMessage::SendMessage(msg)).expect("Can't send data to socket"); }
identifier_body
interface.rs
/** * Websocket implementation taken from https://github.com/nbaksalyar/mio-websocket */ /// High-level WebSocket library interface use std::net::SocketAddr; use std::thread; use std::sync::mpsc; use std::time::Duration; use mio::{Token, EventLoop, EventSet, PollOpt, Sender, NotifyError}; use mio::tcp::{TcpListene...
{ GetPeers(mpsc::Sender<Vec<Token>>), SendMessage((Token, WebSocketEvent)), Reregister(Token), } pub struct WebSocket { events: mpsc::Receiver<(Token, WebSocketEvent)>, event_loop_tx: Sender<WebSocketInternalMessage>, } impl WebSocket { pub fn new(address: SocketAddr) -> WebSocket { let (tx, rx) = mp...
WebSocketInternalMessage
identifier_name
interface.rs
/** * Websocket implementation taken from https://github.com/nbaksalyar/mio-websocket */ /// High-level WebSocket library interface use std::net::SocketAddr; use std::thread; use std::sync::mpsc; use std::time::Duration;
use crate::ws_essentials::StatusCode; use crate::ws_lib::server::{SERVER_TOKEN, WebSocketServer}; #[derive(Clone)] pub enum WebSocketEvent { Connect, Close(StatusCode), TextMessage(String), #[allow(dead_code)] Ping(Box<[u8]>), #[allow(dead_code)] Pong(Box<[u8]>), BinaryMessage(Vec<u8>), } pub enum We...
use mio::{Token, EventLoop, EventSet, PollOpt, Sender, NotifyError}; use mio::tcp::{TcpListener};
random_line_split
fuse.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::Fuse; struct
<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } els...
A
identifier_name
fuse.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::Fuse; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> {
let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } // fn fuse(self) -> Fuse<Self> where Self: Sized { // Fuse{iter: self, done: false} // } } } } type T = i32; Iterator_impl!(T); #[test...
type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end {
random_line_split
unnecessary-private.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 ...
() {} //~ ERROR: visibility has no effect } struct D { priv foo: int, //~ ERROR: visibility has no effect } pub fn foo() {} //~ ERROR: visibility has no effect pub mod bar {} //~ ERROR: visibility has no effect }
foo
identifier_name
unnecessary-private.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 ...
struct D { priv foo: int, //~ ERROR: visibility has no effect } pub fn foo() {} //~ ERROR: visibility has no effect pub mod bar {} //~ ERROR: visibility has no effect }
} impl A { pub fn foo() {} //~ ERROR: visibility has no effect }
random_line_split
svh-a-comment.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 ...
<T:U>(_: int) -> int { // a comment does not affect the svh 3 } pub fn an_unused_name() -> int { 4 }
foo
identifier_name
svh-a-comment.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 ...
}
random_line_split
svh-a-comment.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 ...
{ 4 }
identifier_body
color.rs
use std::fmt; pub struct Color { desc: &'static str, } impl Copy for Color {} impl Color { pub fn desc(&self) -> &str { return self.desc } } impl fmt::Show for Color { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.desc()) } } impl PartialEq for Color...
(&self, other: &Color) -> bool { self.desc == other.desc } } pub const RED: Color= Color{desc:"red"}; pub const BLACK: Color= Color{desc:"black"}; pub const COLORS: [Color;2] = [BLACK, RED]; #[test] fn test_colors() { assert_eq!("red", "red"); assert_eq!(RED.desc(), RED.desc()); assert_eq!(R...
eq
identifier_name
color.rs
use std::fmt; pub struct Color { desc: &'static str, } impl Copy for Color {} impl Color { pub fn desc(&self) -> &str { return self.desc } } impl fmt::Show for Color { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.desc()) } } impl PartialEq for Color...
} pub const RED: Color= Color{desc:"red"}; pub const BLACK: Color= Color{desc:"black"}; pub const COLORS: [Color;2] = [BLACK, RED]; #[test] fn test_colors() { assert_eq!("red", "red"); assert_eq!(RED.desc(), RED.desc()); assert_eq!(RED, RED); assert_eq!("red", RED.desc()); assert_eq!("black", B...
{ self.desc == other.desc }
identifier_body
color.rs
use std::fmt; pub struct Color { desc: &'static str, } impl Copy for Color {} impl Color { pub fn desc(&self) -> &str { return self.desc } } impl fmt::Show for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.desc()) } } impl PartialEq for Color { fn eq(&self, other: &Color) -> bool { self.desc == other.desc } } pub const RED: Color= Color{desc:"red"}; pub const BLACK: Color= Color{desc:"black"}; pub const COLORS:...
random_line_split
bilock.rs
use std::boxed::Box; use std::cell::UnsafeCell; use std::mem; use std::ops::{Deref, DerefMut}; use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use {Async, Future, Poll}; use task::{self, Task}; /// A type of futures-powered synchronization primitive which is a mutex be...
(&mut self) -> &mut T { unsafe { &mut *self.inner.inner.inner.get() } } } impl<T> Drop for BiLockAcquired<T> { fn drop(&mut self) { self.inner.unlock(); } }
deref_mut
identifier_name
bilock.rs
use std::boxed::Box; use std::cell::UnsafeCell; use std::mem; use std::ops::{Deref, DerefMut}; use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use {Async, Future, Poll}; use task::{self, Task}; /// A type of futures-powered synchronization primitive which is a mutex be...
/// This structure acts as a sentinel to the data in the `BiLock<T>` itself, /// implementing `Deref` and `DerefMut` to `T`. When dropped, the lock will be /// unlocked. pub struct BiLockGuard<'a, T: 'a> { inner: &'a BiLock<T>, } impl<'a, T> Deref for BiLockGuard<'a, T> { type Target = T; fn deref(&self) -...
random_line_split
bilock.rs
use std::boxed::Box; use std::cell::UnsafeCell; use std::mem; use std::ops::{Deref, DerefMut}; use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use {Async, Future, Poll}; use task::{self, Task}; /// A type of futures-powered synchronization primitive which is a mutex be...
} /// Future returned by `BiLock::lock` which will resolve when the lock is /// acquired. pub struct BiLockAcquire<T> { inner: BiLock<T>, } impl<T> Future for BiLockAcquire<T> { type Item = BiLockAcquired<T>; type Error = (); fn poll(&mut self) -> Poll<BiLockAcquired<T>, ()> { match self.inn...
{ self.inner.unlock(); }
identifier_body
mod.rs
mod cursor; pub mod raw; #[doc(hidden)] pub mod result; mod row; mod stmt; use std::ffi::CString; use std::os::raw as libc; use self::cursor::*; use self::raw::RawConnection; use self::result::PgResult; use self::stmt::Statement; use crate::connection::*; use crate::deserialize::FromSqlRow; use crate::expression::Que...
query.execute(self, &Vec::new()) } fn set_config_options(&self) -> QueryResult<()> { self.execute("SET TIME ZONE 'UTC'")?; self.execute("SET CLIENT_ENCODING TO 'UTF8'")?; self.raw_connection .set_notice_processor(noop_notice_processor); Ok(()) } } extern ...
let query = Statement::prepare(self, query, None, &[])?;
random_line_split
mod.rs
mod cursor; pub mod raw; #[doc(hidden)] pub mod result; mod row; mod stmt; use std::ffi::CString; use std::os::raw as libc; use self::cursor::*; use self::raw::RawConnection; use self::result::PgResult; use self::stmt::Statement; use crate::connection::*; use crate::deserialize::FromSqlRow; use crate::expression::Que...
fn connection() -> PgConnection { dotenv().ok(); let database_url = env::var("PG_DATABASE_URL") .or_else(|_| env::var("DATABASE_URL")) .expect("DATABASE_URL must be set in order to run tests"); PgConnection::establish(&database_url).unwrap() } }
{ let connection = connection(); let query = crate::select(sql::<Integer>("1")); assert_eq!(Ok(1), query.get_result(&connection)); assert_eq!(0, connection.statement_cache.len()); }
identifier_body
mod.rs
mod cursor; pub mod raw; #[doc(hidden)] pub mod result; mod row; mod stmt; use std::ffi::CString; use std::os::raw as libc; use self::cursor::*; use self::raw::RawConnection; use self::result::PgResult; use self::stmt::Statement; use crate::connection::*; use crate::deserialize::FromSqlRow; use crate::expression::Que...
} else { unreachable!(); } } #[test] fn prepared_statements_are_cached() { let connection = connection(); let query = crate::select(1.into_sql::<Integer>()); assert_eq!(Ok(1), query.get_result(&connection)); assert_eq!(Ok(1), query.get_result(&...
{ unreachable!(); }
conditional_block
mod.rs
mod cursor; pub mod raw; #[doc(hidden)] pub mod result; mod row; mod stmt; use std::ffi::CString; use std::os::raw as libc; use self::cursor::*; use self::raw::RawConnection; use self::result::PgResult; use self::stmt::Statement; use crate::connection::*; use crate::deserialize::FromSqlRow; use crate::expression::Que...
<T, U>(&self, source: T) -> QueryResult<Vec<U>> where T: AsQuery, T::Query: QueryFragment<Self::Backend> + QueryId, U: FromSqlRow<T::SqlType, Self::Backend>, Self::Backend: QueryMetadata<T::SqlType>, { let (query, params) = self.prepare_query(&source.as_query())?; ...
load
identifier_name
callee.rs
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. use super::autoderef; use super::check_argument_types; use super::check_expr; ...
// Call the generic checker. let expected_arg_tys = expected_types_for_fn_args(fcx, call_expr.span, expected, fn_sig.output, ...
let fn_sig = fcx.normalize_associated_types_in(call_expr.span, &fn_sig);
random_line_split
callee.rs
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. use super::autoderef; use super::check_argument_types; use super::check_expr; use su...
<'tcx> { call_expr: &'tcx ast::Expr, callee_expr: &'tcx ast::Expr, adjusted_ty: Ty<'tcx>, autoderefs: usize, fn_sig: ty::FnSig<'tcx>, closure_def_id: ast::DefId, } impl<'tcx> DeferredCallResolution<'tcx> for CallResolution<'tcx> { fn resolve<'a>(&mut self, fcx: &FnCtxt<'a,'tcx>) { d...
CallResolution
identifier_name
callee.rs
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. use super::autoderef; use super::check_argument_types; use super::check_expr; use su...
#[derive(Debug)] struct CallResolution<'tcx> { call_expr: &'tcx ast::Expr, callee_expr: &'tcx ast::Expr, adjusted_ty: Ty<'tcx>, autoderefs: usize, fn_sig: ty::FnSig<'tcx>, closure_def_id: ast::DefId, } impl<'tcx> DeferredCallResolution<'tcx> for CallResolution<'tcx> { fn resolve<'a>(&mut ...
{ let method_call = ty::MethodCall::expr(call_expr.id); fcx.inh.method_map.borrow_mut().insert(method_call, method_callee); }
identifier_body
io.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...
<P, T>(path: P) -> Result<T, Error> where T: for<'r> Deserialize<'r>, P: AsRef<Path>, { let path = path.as_ref(); let res = do_load(path).with_context(|| format!("loading config from {}", path.display()))?; Ok(res) } /// Saves TOML-encoded file. /// /// Creates directory if needed. pub fn save_conf...
load_config_file
identifier_name
io.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...
fn do_load<T: DeserializeOwned>(path: &Path) -> Result<T, Error> { let mut file = File::open(path)?; let mut toml = String::new(); file.read_to_string(&mut toml)?; Ok(toml::de::from_str(&toml)?) } fn do_save<T: Serialize>(value: &T, path: &Path) -> Result<(), Error> { if let Some(dir) = path.pare...
{ let path = path.as_ref(); do_save(value, path).with_context(|| format!("saving config to {}", path.display()))?; Ok(()) }
identifier_body
io.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 mut file = File::create(path)?; let value_toml = toml::Value::try_from(value)?; file.write_all(value_toml.to_string().as_bytes())?; Ok(()) }
{ fs::create_dir_all(dir)?; }
conditional_block
io.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 mut toml = String::new(); file.read_to_string(&mut toml)?; Ok(toml::de::from_str(&toml)?) } fn do_save<T: Serialize>(value: &T, path: &Path) -> Result<(), Error> { if let Some(dir) = path.parent() { fs::create_dir_all(dir)?; } let mut file = File::create(path)?; let value_toml =...
} fn do_load<T: DeserializeOwned>(path: &Path) -> Result<T, Error> { let mut file = File::open(path)?;
random_line_split
connect_analysis.rs
// Copyright (c) 2016 srither-solver developers // // 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 co...
} *last_rev = Some(side_map.revision()); let sides = &[(Side::In, Side::Out), (Side::Out, Side::In)]; for &(set_side, exclude_side) in sides { let (pts, sides, graph) = create_conn_graph(conn_map, exclude_side); let mut arts = vec![]; let mut gvisited = vec![false; graph.len(...
{ return Ok(()); }
conditional_block
connect_analysis.rs
// Copyright (c) 2016 srither-solver developers // // 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 co...
dfs(graph, u, v, arts, gvisited, visited, ord, low, ord_cnt); let low_u = *low.get_unchecked(u); num_child += 1; *low.get_unchecked_mut(v) = cmp::min(*low.get_unchecked(v), low_u); if ord_v <= low_u { is_articulation = ...
{ debug_assert!(!visited[v]); *visited.get_unchecked_mut(v) = true; *gvisited.get_unchecked_mut(v) = true; let ord_v = *ord_cnt; *ord.get_unchecked_mut(v) = ord_v; *low.get_unchecked_mut(v) = ord_v; *ord_cnt += 1; let mut is_articulation = false; ...
identifier_body
connect_analysis.rs
// Copyright (c) 2016 srither-solver developers // // 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 co...
unsafe fn dfs(graph: &[Vec<usize>], v: usize, prev: usize, arts: &mut Vec<usize>, gvisited: &mut [bool], visited: &mut [bool], ord: &mut [usize], low: &mut [usize], ord_cnt...
return visited;
random_line_split