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 |
|---|---|---|---|---|
point_alga.rs | use alga::general::{Field, JoinSemilattice, Lattice, MeetSemilattice, RealField};
use alga::linear::{AffineSpace, EuclideanSpace};
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, Scalar, VectorN};
use crate::geometry::Point;
impl<N: Scalar + Field, D: D... | (&self, other: &Self) -> Self {
Self::from(self.coords.meet(&other.coords))
}
}
impl<N, D: DimName> JoinSemilattice for Point<N, D>
where
N: Scalar + JoinSemilattice,
DefaultAllocator: Allocator<N, D>,
{
#[inline]
fn join(&self, other: &Self) -> Self {
Self::from(self.coords.join(&o... | meet | identifier_name |
point_alga.rs | use alga::general::{Field, JoinSemilattice, Lattice, MeetSemilattice, RealField};
use alga::linear::{AffineSpace, EuclideanSpace};
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, Scalar, VectorN};
use crate::geometry::Point;
impl<N: Scalar + Field, D: D... | }
#[inline]
fn coordinates(&self) -> Self::Coordinates {
self.coords.clone()
}
#[inline]
fn from_coordinates(coords: Self::Coordinates) -> Self {
Self::from(coords)
}
#[inline]
fn scale_by(&self, n: N) -> Self {
self * n
}
}
/*
*
* Ordering
*
*/
im... | random_line_split | |
point_alga.rs | use alga::general::{Field, JoinSemilattice, Lattice, MeetSemilattice, RealField};
use alga::linear::{AffineSpace, EuclideanSpace};
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, Scalar, VectorN};
use crate::geometry::Point;
impl<N: Scalar + Field, D: D... |
}
impl<N, D: DimName> Lattice for Point<N, D>
where
N: Scalar + Lattice,
DefaultAllocator: Allocator<N, D>,
{
#[inline]
fn meet_join(&self, other: &Self) -> (Self, Self) {
let (meet, join) = self.coords.meet_join(&other.coords);
(Self::from(meet), Self::from(join))
}
}
| {
Self::from(self.coords.join(&other.coords))
} | identifier_body |
get_id_issue.rs | extern crate gitlab_api as gitlab;
use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;
#[macro_use]
extern crate clap;
use gitlab::GitLab;
use gitlab::errors::*;
fn | () {
if let Err(ref e) = run() {
println!("error: {}", e);
for e in e.iter().skip(1) {
println!("caused by: {}", e);
}
// The backtrace is not always generated. Try to run this example
// with `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
... | main | identifier_name |
get_id_issue.rs | extern crate gitlab_api as gitlab;
use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;
#[macro_use]
extern crate clap;
use gitlab::GitLab;
use gitlab::errors::*;
fn main() {
if let Err(ref e) = run() { | println!("caused by: {}", e);
}
// The backtrace is not always generated. Try to run this example
// with `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
println!("backtrace: {:?}", backtrace);
}
::std::process::exit(1);
}
}
fn ... | println!("error: {}", e);
for e in e.iter().skip(1) { | random_line_split |
get_id_issue.rs | extern crate gitlab_api as gitlab;
use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;
#[macro_use]
extern crate clap;
use gitlab::GitLab;
use gitlab::errors::*;
fn main() {
if let Err(ref e) = run() {
println!("error: {}", e);
for e in e.iter().skip(1) {
println... |
};
let token = match env::var("GITLAB_TOKEN") {
Ok(val) => val,
Err(_) => {
panic!("Please set environment variable 'GITLAB_TOKEN'. Take it from \
http://{}/profile/account",
hostname);
}
};
let gl = GitLab::new(&hostname, &to... | {
let default = String::from("gitlab.com");
println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.",
default);
default
} | conditional_block |
get_id_issue.rs | extern crate gitlab_api as gitlab;
use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;
#[macro_use]
extern crate clap;
use gitlab::GitLab;
use gitlab::errors::*;
fn main() |
fn run() -> Result<()> {
env_logger::init().unwrap();
info!("starting up");
let hostname = match env::var("GITLAB_HOSTNAME") {
Ok(val) => val,
Err(_) => {
let default = String::from("gitlab.com");
println!("Please set environment variable 'GITLAB_HOSTNAME'. Using d... | {
if let Err(ref e) = run() {
println!("error: {}", e);
for e in e.iter().skip(1) {
println!("caused by: {}", e);
}
// The backtrace is not always generated. Try to run this example
// with `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
... | identifier_body |
htmlheadingelement.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::HTMLHeadingElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLHea... |
}
| {
let element = HTMLHeadingElement::new_inherited(localName, prefix, document, level);
Node::reflect_node(box element, document, HTMLHeadingElementBinding::Wrap)
} | identifier_body |
htmlheadingelement.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::HTMLHeadingElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLHea... | (&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHeadingElement)))
}
}
impl HTMLHeadingElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
... | is_htmlheadingelement | identifier_name |
htmlheadingelement.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::HTMLHeadingElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLHea... | level: HeadingLevel,
}
impl HTMLHeadingElementDerived for EventTarget {
fn is_htmlheadingelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHeadingElement)))
}
}
impl HTMLHeadingElem... | pub struct HTMLHeadingElement {
htmlelement: HTMLElement, | random_line_split |
bitmap_font.rs | use std::collections::HashMap;
use std::old_io::{File};
use xml::Element;
///
/// Representation of a bitmap font, generated with a tool like
/// [BMFont](http://www.angelcode.com/products/bmfont/)
///
/// A BitmapFont describes a bitmap font texture, providing a mapping from character
/// codes to a rectangular area... | {
pub scale_w: u8,
pub scale_h: u8,
pub characters: HashMap<char, BitmapCharacter>
}
#[derive(Debug)]
#[derive(Default)]
pub struct BitmapCharacter {
pub x: u8,
pub y: u8,
pub width: u8,
pub height: u8,
pub xoffset: u8,
pub yoffset: u8,
pub xadvance: u8,
}
impl BitmapFont {
... | BitmapFont | identifier_name |
bitmap_font.rs | use std::collections::HashMap;
use std::old_io::{File};
use xml::Element;
///
/// Representation of a bitmap font, generated with a tool like
/// [BMFont](http://www.angelcode.com/products/bmfont/)
///
/// A BitmapFont describes a bitmap font texture, providing a mapping from character
/// codes to a rectangular area... | ,
Err(_) => Err("Error while parsing font document."),
}
}
///
/// Constructs a BitmapFont for the given root xml element
///
fn from_xml_document(xml_root: &Element) -> Result<BitmapFont, &'static str> {
let chars_element = match xml_root.get_child("chars", None) {
... | {
BitmapFont::from_xml_document(&xml_root)
} | conditional_block |
bitmap_font.rs | use std::collections::HashMap;
use std::old_io::{File};
use xml::Element;
///
/// Representation of a bitmap font, generated with a tool like
/// [BMFont](http://www.angelcode.com/products/bmfont/)
///
/// A BitmapFont describes a bitmap font texture, providing a mapping from character
/// codes to a rectangular area... |
let mut bitmap_font = BitmapFont{
characters: HashMap::new(),
scale_w: get_attribute(&common_element, "scaleW"),
scale_h: get_attribute(&common_element, "scaleH"),
};
for char_elem in chars_element.get_children("char", None).iter() {
let characte... |
let common_element = match xml_root.get_child("common", None) {
Some(e) => e,
None => return Err("Missing <common> element"),
}; | random_line_split |
test.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 ... | ]);
let sccs: Sccs<_, usize> = Sccs::new(&graph);
assert_eq!(sccs.num_sccs(), 2);
assert_eq!(sccs.scc(0), 0);
assert_eq!(sccs.scc(1), 0);
assert_eq!(sccs.scc(2), 0);
assert_eq!(sccs.scc(3), 0);
assert_eq!(sccs.scc(4), 0);
assert_eq!(sccs.scc(5), 1);
assert_eq!(sccs.successors(0),... | {
/*
/----+
0 <--+ |
| | |
v | |
+-> 1 -> 3 4 5
| | | |
| v | |
+-- 2 <----+-+
*/
let graph = TestGraph::new(0, &[
(0, 1),
(0, 4),
(1, 2),
(1, 3),
(2, 1),
(3, 0),
(4, 2),
(5, 2), | identifier_body |
test.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 ... | () {
// The order in which things will be visited is important to this
// test. It tests part of the `find_state` behavior. Here is the
// graph:
//
//
// /----+
// 0 <--+ |
// | | |
// v | |
// +-> 1 -> 3 4
// | | |
// | v |
// +... | test_find_state_2 | identifier_name |
test.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 ... | (0, 4),
(1, 2),
(1, 3),
(2, 1),
(3, 0),
(4, 2),
(5, 2),
]);
let sccs: Sccs<_, usize> = Sccs::new(&graph);
assert_eq!(sccs.num_sccs(), 2);
assert_eq!(sccs.scc(0), 0);
assert_eq!(sccs.scc(1), 0);
assert_eq!(sccs.scc(2), 0);
assert_eq!(scc... | (0, 1), | random_line_split |
ui.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | // 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of ... | random_line_split | |
ui.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | {
app
} | identifier_body | |
ui.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | <'a>(app: App<'a, 'a>) -> App<'a, 'a> {
app
}
| build_ui | identifier_name |
auto-ref-bounded-ty-param.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn g(&self);
}
impl<T:Baz> Foo for T {
fn f(&self) {
self.g();
}
}
impl Baz for Bar {
fn g(&self) {
io::println(self.x.to_str());
}
}
pub fn main() {
let y = Bar { x: 42 };
y.f();
} |
trait Baz { | random_line_split |
auto-ref-bounded-ty-param.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 ... | {
x: int
}
trait Baz {
fn g(&self);
}
impl<T:Baz> Foo for T {
fn f(&self) {
self.g();
}
}
impl Baz for Bar {
fn g(&self) {
io::println(self.x.to_str());
}
}
pub fn main() {
let y = Bar { x: 42 };
y.f();
}
| Bar | identifier_name |
raft_server.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... |
/// Creates a Raft server using the specified ID from the list of nodes.
pub fn server(args: &Args) -> (Server<Store, HashmapStateMachine>, EventLoop<Server<Store, HashmapStateMachine>>) {
// Creating a raft server requires several things:
// A persistent log implementation, which manages the persistent, rep... | {
addr.to_socket_addrs()
.ok()
.expect(&format!("unable to parse socket address: {}", addr))
.next()
.unwrap()
} | identifier_body |
raft_server.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | {
cmd_server: bool,
// When creating a server you will necessarily need some sort of unique ID for it as well
// as a list of peers. In this example we just accept them straight from args. You might
// find it best to use a `toml` or `yaml` or `json` file.
arg_id: Option<u64>,
arg_node_address... | Args | identifier_name |
raft_server.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | /// Creates a Raft server using the specified ID from the list of nodes.
pub fn server(args: &Args) -> (Server<Store, HashmapStateMachine>, EventLoop<Server<Store, HashmapStateMachine>>) {
// Creating a raft server requires several things:
// A persistent log implementation, which manages the persistent, repli... | .expect(&format!("unable to parse socket address: {}", addr))
.next()
.unwrap()
}
| random_line_split |
unix.rs | //
// Copyright:: Copyright (c) 2015 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... |
pub fn remove_recursive<P:?Sized>(path: &P) -> Result<(), DeliveryError>
where
P: AsRef<Path>,
{
try!(
Command::new("rm")
.arg("-rf")
.arg(path.as_ref().to_str().unwrap())
.output()
);
Ok(())
}
pub fn chmod<P:?Sized>(path: &P, setting: &str) -> Result<(), Deli... | {
let from = f.as_ref();
let to = t.as_ref();
let result = try!(
Command::new("cp")
.arg("-R")
.arg("-a")
.arg(from.to_str().unwrap())
.arg(to.to_str().unwrap())
.output()
);
super::cmd_success_or_err(&result, Kind::CopyFailed)
} | identifier_body |
unix.rs | //
// Copyright:: Copyright (c) 2015 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... | <A, B>(f: &A, t: &B) -> Result<(), DeliveryError>
where
A: AsRef<Path> +?Sized,
B: AsRef<Path> +?Sized,
{
let from = f.as_ref();
let to = t.as_ref();
let result = try!(
Command::new("cp")
.arg("-R")
.arg("-a")
.arg(from.to_str().unwrap())
.arg(to.t... | copy_recursive | identifier_name |
unix.rs | //
// Copyright:: Copyright (c) 2015 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... | }
}
None
}
pub fn ca_path() -> String {
String::from("/opt/chefdk/embedded/ssl/certs/cacert.pem")
} | random_line_split | |
trailing_zeros.rs | use integer::Integer;
impl Integer {
/// Returns the number of trailing zeros in the binary expansion of an `Integer` (equivalently,
/// the multiplicity of 2 in its prime factorization) or `None` is the `Integer` is 0.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
... |
}
| {
self.abs.trailing_zeros()
} | identifier_body |
trailing_zeros.rs | use integer::Integer;
impl Integer {
/// Returns the number of trailing zeros in the binary expansion of an `Integer` (equivalently,
/// the multiplicity of 2 in its prime factorization) or `None` is the `Integer` is 0.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
... | /// use malachite_base::num::basic::traits::Zero;
/// use malachite_nz::integer::Integer;
///
/// assert_eq!(Integer::ZERO.trailing_zeros(), None);
/// assert_eq!(Integer::from(3).trailing_zeros(), Some(0));
/// assert_eq!(Integer::from(-72).trailing_zeros(), Some(3));
/// assert_eq!(Integer... | /// extern crate malachite_nz;
/// | random_line_split |
trailing_zeros.rs | use integer::Integer;
impl Integer {
/// Returns the number of trailing zeros in the binary expansion of an `Integer` (equivalently,
/// the multiplicity of 2 in its prime factorization) or `None` is the `Integer` is 0.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
... | (&self) -> Option<u64> {
self.abs.trailing_zeros()
}
}
| trailing_zeros | identifier_name |
data_loader.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/. */
extern crate hyper;
extern crate hyper_serde;
use hyper_serde::Serde;
use ipc_channel::ipc;
use msg::constellatio... | vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))),
Some("US-ASCII".to_owned()), Some(b"hello world".iter().map(|&x| x).collect()));
}
#[test]
fn plain_ct() {
assert_parse(
"data:text/plain,hello",
Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain,... | "data:,hello%20world",
Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, | random_line_split |
data_loader.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/. */
extern crate hyper;
extern crate hyper_serde;
use hyper_serde::Serde;
use ipc_channel::ipc;
use msg::constellatio... |
}
}
#[test]
fn empty_invalid() {
assert_parse("data:", None, None, None);
}
#[test]
fn plain() {
assert_parse(
"data:,hello%20world",
Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain,
vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))),
S... | {
assert_eq!(progress, Payload(dat));
assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(())));
} | conditional_block |
data_loader.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/. */
extern crate hyper;
extern crate hyper_serde;
use hyper_serde::Serde;
use ipc_channel::ipc;
use msg::constellatio... |
fn referrer_policy(&self) -> Option<ReferrerPolicy> {
None
}
fn pipeline_id(&self) -> Option<PipelineId> {
None
}
}
#[cfg(test)]
fn assert_parse(url: &'static str,
content_type: Option<ContentType>,
charset: Option<String>,
... | {
None
} | identifier_body |
data_loader.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/. */
extern crate hyper;
extern crate hyper_serde;
use hyper_serde::Serde;
use ipc_channel::ipc;
use msg::constellatio... | () {
assert_parse("data:application/octet-stream;base64,C62+7w==",
Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_owned()), vec!()))),
None,
Some(vec!(0x0B, 0xAD, 0xBE, 0xEF)));
}
#[test]
fn base64_charset() {
assert_parse("data:text/plain;charset=koi8-r;ba... | base64_ct | identifier_name |
custom_errors.rs | #![allow(dead_code)]
use nom::bytes::streaming::tag;
use nom::character::streaming::digit1 as digit;
use nom::combinator::verify;
use nom::error::{ErrorKind, ParseError};
#[cfg(feature = "alloc")]
use nom::multi::count;
use nom::sequence::terminated;
use nom::IResult;
#[derive(Debug)]
pub struct CustomError(String);
... | (input: &str) -> IResult<&str, &str, CustomError> {
//fix_error!(input, CustomError, tag!("abcd"))
tag("abcd")(input)
}
fn test2(input: &str) -> IResult<&str, &str, CustomError> {
//terminated!(input, test1, fix_error!(CustomError, digit))
terminated(test1, digit)(input)
}
fn test3(input: &str) -> IResult<&st... | test1 | identifier_name |
custom_errors.rs | #![allow(dead_code)]
use nom::bytes::streaming::tag;
use nom::character::streaming::digit1 as digit;
use nom::combinator::verify;
use nom::error::{ErrorKind, ParseError};
#[cfg(feature = "alloc")]
use nom::multi::count;
use nom::sequence::terminated;
use nom::IResult;
#[derive(Debug)]
pub struct CustomError(String);
... | count(test1, 4)(input)
} | fn test4(input: &str) -> IResult<&str, Vec<&str>, CustomError> { | random_line_split |
custom_errors.rs | #![allow(dead_code)]
use nom::bytes::streaming::tag;
use nom::character::streaming::digit1 as digit;
use nom::combinator::verify;
use nom::error::{ErrorKind, ParseError};
#[cfg(feature = "alloc")]
use nom::multi::count;
use nom::sequence::terminated;
use nom::IResult;
#[derive(Debug)]
pub struct CustomError(String);
... |
}
impl<'a> ParseError<&'a str> for CustomError {
fn from_error_kind(_: &'a str, kind: ErrorKind) -> Self {
CustomError(format!("error code was: {:?}", kind))
}
fn append(_: &'a str, kind: ErrorKind, other: CustomError) -> Self {
CustomError(format!("{:?}\nerror code was: {:?}", other, kind))
}
}
fn ... | {
CustomError(format!("error code was: {:?}", error))
} | identifier_body |
blobstore.rs | // Copyright 2018 Benjamin Bader
// Copyright 2016 Mozilla Foundation
//
// 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 req... |
let res = self
.client
.execute(request)
.await
.with_context(|| format!("failed GET: {}", &uri))?;
let (bytes, content_length) = if res.status().is_success() {
let content_length = res.content_length();
(res.bytes().await?, content_... | {
request.headers_mut().insert(
"Authorization",
HeaderValue::from_str(&auth).expect("Authorization is an invalid header value"),
);
} | conditional_block |
blobstore.rs | // Copyright 2018 Benjamin Bader
// Copyright 2016 Mozilla Foundation
//
// 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 req... | let res = self
.client
.execute(request)
.await
.with_context(|| format!("failed GET: {}", &uri))?;
let (bytes, content_length) = if res.status().is_success() {
let content_length = res.content_length();
(res.bytes().await?, content_le... | }
| random_line_split |
blobstore.rs | // Copyright 2018 Benjamin Bader
// Copyright 2016 Mozilla Foundation
//
// 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 req... |
#[test]
#[ignore]
fn test_put_blob() {
/*
NOTE:
This test assumes that you are running a local storage emulator,
such as azurite. It will fail, perhaps hanging indefinitely, if
you aren't!
You may also replace the hardcoded constants with your own Azure
... | {
let url = Url::from_str("https://testaccount.blob.core.windows.net/container/key").unwrap();
let canon = canonicalize_resource(&url, "testaccount");
assert_eq!("/testaccount/container/key", &canon);
} | identifier_body |
blobstore.rs | // Copyright 2018 Benjamin Bader
// Copyright 2016 Mozilla Foundation
//
// 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 req... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "BlobContainer(url={})", self.url)
}
}
impl BlobContainer {
pub fn new(base_url: &str, container_name: &str) -> Result<BlobContainer> {
assert!(
base_url.ends_with('/'),
"base_url is assumed to end in a trail... | fmt | identifier_name |
iri.rs | //! CSS funciri values.
use cssparser::Parser;
use crate::document::NodeId;
use crate::error::*;
use crate::parsers::Parse;
/// Used where style properties take a funciri or "none"
///
/// This is not to be used for values which don't come from properties.
/// For example, the `xlink:href` attribute in the `<image>`... | }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_none() {
assert_eq!(Iri::parse_str("none").unwrap(), Iri::None);
}
#[test]
fn parses_url() {
assert_eq!(
Iri::parse_str("url(#bar)").unwrap(),
Iri::Resource(Box::new(NodeId::Internal("bar".to_st... | Ok(Iri::Resource(Box::new(node_id)))
}
} | random_line_split |
iri.rs | //! CSS funciri values.
use cssparser::Parser;
use crate::document::NodeId;
use crate::error::*;
use crate::parsers::Parse;
/// Used where style properties take a funciri or "none"
///
/// This is not to be used for values which don't come from properties.
/// For example, the `xlink:href` attribute in the `<image>`... | () {
assert_eq!(
Iri::parse_str("url(#bar)").unwrap(),
Iri::Resource(Box::new(NodeId::Internal("bar".to_string())))
);
assert_eq!(
Iri::parse_str("url(foo#bar)").unwrap(),
Iri::Resource(Box::new(NodeId::External(
"foo".to_string(),... | parses_url | identifier_name |
iri.rs | //! CSS funciri values.
use cssparser::Parser;
use crate::document::NodeId;
use crate::error::*;
use crate::parsers::Parse;
/// Used where style properties take a funciri or "none"
///
/// This is not to be used for values which don't come from properties.
/// For example, the `xlink:href` attribute in the `<image>`... |
#[test]
fn parses_url() {
assert_eq!(
Iri::parse_str("url(#bar)").unwrap(),
Iri::Resource(Box::new(NodeId::Internal("bar".to_string())))
);
assert_eq!(
Iri::parse_str("url(foo#bar)").unwrap(),
Iri::Resource(Box::new(NodeId::External(
... | {
assert_eq!(Iri::parse_str("none").unwrap(), Iri::None);
} | identifier_body |
htmldetailselement.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::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding;
use dom::bindings::codegen::... | use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use std::cell::Cell;
use task_source::TaskSource;
#[dom_struct]
pub struct HTMLDetailsElement {
htmlelement: HTMLElement,
toggle_counter: Cell<u32>,
}
impl HTMLDetailsElement {
fn new_inherited(
... | use dom::document::Document;
use dom::element::AttributeMutation;
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, window_from_node}; | random_line_split |
htmldetailselement.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::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding;
use dom::bindings::codegen::... | (&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &local_name!("open") {
... | super_type | identifier_name |
htmldetailselement.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::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding;
use dom::bindings::codegen::... |
}
}
| {
let counter = self.toggle_counter.get() + 1;
self.toggle_counter.set(counter);
let window = window_from_node(self);
let this = Trusted::new(self);
// FIXME(nox): Why are errors silenced here?
let _ = window.dom_manipulation_task_source().queue(
... | conditional_block |
htmldetailselement.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::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding;
use dom::bindings::codegen::... |
}
impl HTMLDetailsElementMethods for HTMLDetailsElement {
// https://html.spec.whatwg.org/multipage/#dom-details-open
make_bool_getter!(Open, "open");
// https://html.spec.whatwg.org/multipage/#dom-details-open
make_bool_setter!(SetOpen, "open");
}
impl VirtualMethods for HTMLDetailsElement {
fn... | {
Node::reflect_node(
Box::new(HTMLDetailsElement::new_inherited(
local_name, prefix, document,
)),
document,
HTMLDetailsElementBinding::Wrap,
)
} | identifier_body |
test_butterfly.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 r... |
let payload = Vec::from(config.as_bytes());
let incarnation = Self::new_incarnation();
self.butterfly_client
.send_service_config(
ServiceGroup::new(None, &self.package_name, &self.service_group, None).unwrap(),
incarnation,
payload,
... | {
panic!("Invalid TOML! {:?} ==> {:?}", config, err);
} | conditional_block |
test_butterfly.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 r... |
/// Apply the given configuration to the Supervisor. It will
/// always be applied to the service group for which the client was
/// initially configured.
///
/// A time-based incarnation value is automatically used,
/// resulting in less clutter in your tests.
pub fn apply<T>(&mut self, c... | {
let gossip_addr = format!("127.0.0.1:{}", port)
.parse::<SocketAddr>()
.expect("Could not parse Butterfly gossip address!");
let c = ButterflyClient::new(&gossip_addr, None)
.expect("Could not create Butterfly Client for test!");
Client {
butterf... | identifier_body |
test_butterfly.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 r... |
extern crate habitat_butterfly;
use self::habitat_butterfly::client::Client as ButterflyClient;
extern crate habitat_core;
use self::habitat_core::service::ServiceGroup;
extern crate toml;
use std::net::SocketAddr;
use std::time::{SystemTime, UNIX_EPOCH};
pub struct Client {
butterfly_client: ButterflyClient,
... | //! No ring key or encryption abilities are currently supported. | random_line_split |
test_butterfly.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 r... | <T, U>(package_name: T, service_group: U, port: u16) -> Client
where
T: ToString,
U: ToString,
{
let gossip_addr = format!("127.0.0.1:{}", port)
.parse::<SocketAddr>()
.expect("Could not parse Butterfly gossip address!");
let c = ButterflyClient::new(&gossip... | new | identifier_name |
test_sync.rs | use std::sync::Arc;
use std::thread;
use protobuf::CodedInputStream;
use protobuf::Message;
use super::test_sync_pb::*;
// test messages are sync
#[test]
fn test_sync() {
let m = Arc::new({
let mut r = TestSync::new();
r.set_int32_field(23);
r
});
let threads: Vec<_> = (0..4)
... | .collect::<Vec<_>>();
assert_eq!(&[23, 23, 23, 23], &results[..]);
} | .map(|t| t.join().unwrap()) | random_line_split |
test_sync.rs | use std::sync::Arc;
use std::thread;
use protobuf::CodedInputStream;
use protobuf::Message;
use super::test_sync_pb::*;
// test messages are sync
#[test]
fn test_sync() | .collect();
let results = threads
.into_iter()
.map(|t| t.join().unwrap())
.collect::<Vec<_>>();
assert_eq!(&[23, 23, 23, 23], &results[..]);
}
| {
let m = Arc::new({
let mut r = TestSync::new();
r.set_int32_field(23);
r
});
let threads: Vec<_> = (0..4)
.map(|_| {
let m_copy = m.clone();
thread::spawn(move || {
let bytes = m_copy.write_to_bytes().unwrap();
let mu... | identifier_body |
test_sync.rs | use std::sync::Arc;
use std::thread;
use protobuf::CodedInputStream;
use protobuf::Message;
use super::test_sync_pb::*;
// test messages are sync
#[test]
fn | () {
let m = Arc::new({
let mut r = TestSync::new();
r.set_int32_field(23);
r
});
let threads: Vec<_> = (0..4)
.map(|_| {
let m_copy = m.clone();
thread::spawn(move || {
let bytes = m_copy.write_to_bytes().unwrap();
let ... | test_sync | identifier_name |
method-call-err-msg.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... | () {
let x = Foo;
x.zero(0) //~ ERROR this function takes 0 parameters but 1 parameter was supplied
.one() //~ ERROR this function takes 1 parameter but 0 parameters were supplied
.two(0); //~ ERROR this function takes 2 parameters but 1 parameter was supplied
let y = Foo;
y.zero()
... | main | identifier_name |
method-call-err-msg.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... | } | .one(0); | random_line_split |
method-call-err-msg.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... |
}
fn main() {
let x = Foo;
x.zero(0) //~ ERROR this function takes 0 parameters but 1 parameter was supplied
.one() //~ ERROR this function takes 1 parameter but 0 parameters were supplied
.two(0); //~ ERROR this function takes 2 parameters but 1 parameter was supplied
let y = Foo;
y.... | { self } | identifier_body |
day4.rs | use std::collections::HashMap;
use get_input::get_input;
const IS_PART1: bool = false;
fn sector_id(room_name: &str) -> Option<(&str, u32)> | ch1.cmp(&ch2)
}
});
let actual_checksum: String = v.iter().take(checksum.len()).map(|&(c,_)| c).collect();
if actual_checksum == checksum {
Some((&room_name[..room_name.rfind('-').unwrap()], sector_id))
} else {
None
}
}
fn decode(s: &str, id: u32... | {
let mut name_parts = room_name.split(|c| { c == '-' || c == '[' || c == ']' });
let _ = name_parts.next_back(); // skip empty string due to delimiter ']' at end of input
let checksum = name_parts.next_back().unwrap();
let sector_id = name_parts.next_back().unwrap().parse::<u32>().unwrap();
... | identifier_body |
day4.rs | use std::collections::HashMap;
use get_input::get_input;
const IS_PART1: bool = false;
fn | (room_name: &str) -> Option<(&str, u32)> {
let mut name_parts = room_name.split(|c| { c == '-' || c == '[' || c == ']' });
let _ = name_parts.next_back(); // skip empty string due to delimiter ']' at end of input
let checksum = name_parts.next_back().unwrap();
let sector_id = name_parts.next_back().... | sector_id | identifier_name |
day4.rs | use std::collections::HashMap;
use get_input::get_input;
const IS_PART1: bool = false;
fn sector_id(room_name: &str) -> Option<(&str, u32)> {
let mut name_parts = room_name.split(|c| { c == '-' || c == '[' || c == ']' });
let _ = name_parts.next_back(); // skip empty string due to delimiter ']' at en... |
});
let actual_checksum: String = v.iter().take(checksum.len()).map(|&(c,_)| c).collect();
if actual_checksum == checksum {
Some((&room_name[..room_name.rfind('-').unwrap()], sector_id))
} else {
None
}
}
fn decode(s: &str, id: u32) -> String {
let a = 'a' as u8;... | {
ch1.cmp(&ch2)
} | conditional_block |
day4.rs | use std::collections::HashMap;
use get_input::get_input;
const IS_PART1: bool = false;
fn sector_id(room_name: &str) -> Option<(&str, u32)> {
let mut name_parts = room_name.split(|c| { c == '-' || c == '[' || c == ']' });
let _ = name_parts.next_back(); // skip empty string due to delimiter ']' at en... | fn decode(s: &str, id: u32) -> String {
let a = 'a' as u8;
let rot = (id % 26) as u8; // get rid of full rotations
let mut decoded = String::with_capacity(s.len());
for c in s.bytes() {
if c == '-' as u8 {
decoded.push(' ');
} else {
decoded.push(((c - a... | random_line_split | |
issue-5688.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 ... | { vec: &'static [isize] }
static V: &'static [X] = &[X { vec: &[1, 2, 3] }];
pub fn main() {
for &v in V {
println!("{:?}", v.vec);
}
}
| X | identifier_name |
issue-5688.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 ... | } | } | random_line_split |
issue-5688.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 ... | {
for &v in V {
println!("{:?}", v.vec);
}
} | identifier_body | |
main.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[cfg(test)] mod tests;
use rocket::Request;
use rocket::response::content;
#[derive(Debug, Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
}
// In a `GET` re... |
_ => format!("<p>Sorry, '{}' is an invalid path! Try \
/hello/<name>/<age> instead.</p>",
request.uri())
};
content::HTML(html)
}
fn main() {
rocket::ignite()
.mount("/hello", routes![get_hello, post_hello])
.catch(errors![not_found])
... | {
format!("<p>'{}' requests are not supported.</p>", mt)
} | conditional_block |
main.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[cfg(test)] mod tests;
use rocket::Request;
use rocket::response::content;
#[derive(Debug, Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
}
// In a `GET` re... |
// In a `POST` request and all other payload supporting request types, the
// content type is matched against the `format` in the route attribute.
#[post("/<age>", format = "text/plain", data = "<name>")]
fn post_hello(age: u8, name: String) -> content::JSON<String> {
let person = Person { name: name, age: age, }... | {
// In a real application, we'd use the JSON contrib type.
let person = Person { name: name, age: age, };
content::JSON(serde_json::to_string(&person).unwrap())
} | identifier_body |
main.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[cfg(test)] mod tests;
use rocket::Request;
use rocket::response::content;
#[derive(Debug, Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
}
// In a `GET` re... | fn post_hello(age: u8, name: String) -> content::JSON<String> {
let person = Person { name: name, age: age, };
content::JSON(serde_json::to_string(&person).unwrap())
}
#[error(404)]
fn not_found(request: &Request) -> content::HTML<String> {
let html = match request.format() {
Some(ref mt) if!mt.is_... | #[post("/<age>", format = "text/plain", data = "<name>")] | random_line_split |
main.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[cfg(test)] mod tests;
use rocket::Request;
use rocket::response::content;
#[derive(Debug, Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
}
// In a `GET` re... | () {
rocket::ignite()
.mount("/hello", routes![get_hello, post_hello])
.catch(errors![not_found])
.launch();
}
| main | identifier_name |
machine_config.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use serde::{de, Deserialize, Serialize};
use std::fmt;
/// The default memory size of the VM, in MiB.
pub const DEFAULT_MEM_SIZE_MIB: usize = 128;
/// Firecracker aims to support small scale workloads onl... | &"CPU templates are not supported on aarch64",
));
#[cfg(target_arch = "x86_64")]
T::deserialize(_d)
}
/// Template types available for configuring the CPU features that map
/// to EC2 instances.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub enum CpuFeaturesTemplate {
//... | return Err(de::Error::invalid_value(
de::Unexpected::Enum, | random_line_split |
machine_config.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use serde::{de, Deserialize, Serialize};
use std::fmt;
/// The default memory size of the VM, in MiB.
pub const DEFAULT_MEM_SIZE_MIB: usize = 128;
/// Firecracker aims to support small scale workloads onl... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CpuFeaturesTemplate::C3 => write!(f, "C3"),
CpuFeaturesTemplate::T2 => write!(f, "T2"),
CpuFeaturesTemplate::None => write!(f, "None"),
}
}
}
impl Default for CpuFeaturesTemplate {
fn default() -> ... | fmt | identifier_name |
allocator.rs | use rustc_span::symbol::{sym, Symbol};
#[derive(Clone, Debug, Copy, HashStable_Generic)]
pub enum AllocatorKind {
Global,
Default,
}
impl AllocatorKind { | }
}
}
pub enum AllocatorTy {
Layout,
Ptr,
ResultPtr,
Unit,
Usize,
}
pub struct AllocatorMethod {
pub name: Symbol,
pub inputs: &'static [AllocatorTy],
pub output: AllocatorTy,
}
pub static ALLOCATOR_METHODS: &[AllocatorMethod] = &[
AllocatorMethod {
name: sym::... | pub fn fn_name(&self, base: Symbol) -> String {
match *self {
AllocatorKind::Global => format!("__rg_{}", base),
AllocatorKind::Default => format!("__rdl_{}", base), | random_line_split |
allocator.rs | use rustc_span::symbol::{sym, Symbol};
#[derive(Clone, Debug, Copy, HashStable_Generic)]
pub enum AllocatorKind {
Global,
Default,
}
impl AllocatorKind {
pub fn fn_name(&self, base: Symbol) -> String {
match *self {
AllocatorKind::Global => format!("__rg_{}", base),
Allocat... | {
pub name: Symbol,
pub inputs: &'static [AllocatorTy],
pub output: AllocatorTy,
}
pub static ALLOCATOR_METHODS: &[AllocatorMethod] = &[
AllocatorMethod {
name: sym::alloc,
inputs: &[AllocatorTy::Layout],
output: AllocatorTy::ResultPtr,
},
AllocatorMethod {
name... | AllocatorMethod | identifier_name |
testbindingiterable.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
// check-tidy: no specs after this line
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::co... | } | random_line_split | |
testbindingiterable.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
// check-tidy: no specs after this line
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::co... |
fn GetItem(&self, n: u32) -> DOMString {
self.IndexedGetter(n).unwrap_or_default()
}
fn IndexedGetter(&self, n: u32) -> Option<DOMString> {
self.vals.borrow().get(n as usize).cloned()
}
}
| {
self.vals.borrow().len() as u32
} | identifier_body |
testbindingiterable.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
// check-tidy: no specs after this line
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::co... | (&self, n: u32) -> DOMString {
self.IndexedGetter(n).unwrap_or_default()
}
fn IndexedGetter(&self, n: u32) -> Option<DOMString> {
self.vals.borrow().get(n as usize).cloned()
}
}
| GetItem | identifier_name |
caps.rs | // Copyright (c) 2017-2019 Linaro LTD
// Copyright (c) 2019 JUUL Labs
// Copyright (c) 2019 Arm Limited
//
// SPDX-License-Identifier: Apache-2.0
// Query the bootloader's capabilities.
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[allow(unused)]
pub enum Caps {
RSA2048 = (1 << 0),
... |
/// Query for the number of images that have been configured into this
/// MCUboot build.
pub fn get_num_images() -> usize {
(unsafe { bootutil_get_num_images() }) as usize
}
}
extern "C" {
fn bootutil_get_caps() -> Caps;
fn bootutil_get_num_images() -> u32;
}
| {
let caps = unsafe { bootutil_get_caps() };
(caps as u32) & (self as u32) != 0
} | identifier_body |
caps.rs | // Copyright (c) 2017-2019 Linaro LTD
// Copyright (c) 2019 JUUL Labs
// Copyright (c) 2019 Arm Limited
//
// SPDX-License-Identifier: Apache-2.0
// Query the bootloader's capabilities.
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[allow(unused)]
pub enum | {
RSA2048 = (1 << 0),
EcdsaP224 = (1 << 1),
EcdsaP256 = (1 << 2),
SwapUsingScratch = (1 << 3),
OverwriteUpgrade = (1 << 4),
EncRsa = (1 << 5),
EncKw = (1 << 6),
ValidatePrimarySlot = (1 << 7),
RSA3072 ... | Caps | identifier_name |
caps.rs | // Copyright (c) 2017-2019 Linaro LTD
// Copyright (c) 2019 JUUL Labs
// Copyright (c) 2019 Arm Limited
//
// SPDX-License-Identifier: Apache-2.0
// Query the bootloader's capabilities.
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[allow(unused)]
pub enum Caps {
RSA2048 = (1 << 0),
... | pub fn present(self) -> bool {
let caps = unsafe { bootutil_get_caps() };
(caps as u32) & (self as u32)!= 0
}
/// Query for the number of images that have been configured into this
/// MCUboot build.
pub fn get_num_images() -> usize {
(unsafe { bootutil_get_num_images() }) a... |
impl Caps { | random_line_split |
task_queue.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/. */
//! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue).
use crate::dom::bindings::ce... |
/// Hold back tasks for currently not fully-active documents.
/// https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active
fn store_task_for_inactive_pipeline(&self, msg: T, pipeline_id: &PipelineId) {
let mut inactive = self.inactive.borrow_mut();
let inactive_queu... | {
self.inactive
.borrow_mut()
.iter_mut()
.filter(|(pipeline_id, _)| fully_active.contains(pipeline_id))
.flat_map(|(_, inactive_queue)| {
inactive_queue
.drain(0..)
.map(|queued_task| T::from_queued_task(que... | identifier_body |
task_queue.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/. */
//! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue).
use crate::dom::bindings::ce... | use crate::script_thread::ScriptThread;
use crate::task::TaskBox;
use crate::task_source::TaskSourceName;
use crossbeam_channel::{self, Receiver, Sender};
use msg::constellation_msg::PipelineId;
use std::cell::Cell;
use std::collections::{HashMap, HashSet, VecDeque};
use std::default::Default;
pub type QueuedTask = (
... | random_line_split | |
task_queue.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/. */
//! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue).
use crate::dom::bindings::ce... | (
&self,
fully_active: &HashSet<PipelineId>,
) -> Vec<T> {
self.inactive
.borrow_mut()
.iter_mut()
.filter(|(pipeline_id, _)| fully_active.contains(pipeline_id))
.flat_map(|(_, inactive_queue)| {
inactive_queue
.d... | release_tasks_for_fully_active_documents | identifier_name |
task_queue.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/. */
//! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue).
use crate::dom::bindings::ce... |
}
// Immediately send non-throttled tasks for processing.
let _ = self.msg_queue.borrow_mut().push_back(msg);
}
for msg in to_be_throttled {
// Categorize tasks per task queue.
let (worker, category, boxed, pipeline_id, task_source) = match m... | {
self.store_task_for_inactive_pipeline(msg, &pipeline_id);
continue;
} | conditional_block |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Fallible, Error};
use dom::bindings::glob... | let obj = RootedObject::new(cx, self.callback());
unsafe {
let c_name = CString::new(name).unwrap();
if JS_GetProperty(cx, obj.handle(), c_name.as_ptr(),
callable.handle_mut()) == 0 {
return Err(Error::JSFailed);
}
... | /// or an error otherwise.
pub fn get_callable_property(&self, cx: *mut JSContext, name: &str)
-> Fallible<JSVal> {
let mut callable = RootedValue::new(cx, UndefinedValue()); | random_line_split |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Fallible, Error};
use dom::bindings::glob... |
if!callable.ptr.is_object() ||
IsCallable(callable.ptr.to_object()) == 0 {
return Err(Error::Type(
format!("The value of the {} property is not callable", name)));
}
}
Ok(callable.ptr)
}
}
/// Wraps the reflector for `p` i... | {
return Err(Error::JSFailed);
} | conditional_block |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Fallible, Error};
use dom::bindings::glob... | {
object: CallbackObject
}
impl CallbackFunction {
/// Create a new `CallbackFunction` for this object.
pub fn new() -> CallbackFunction {
CallbackFunction {
object: CallbackObject {
callback: Heap::default()
}
}
}
/// Initialize the callbac... | CallbackFunction | identifier_name |
sleep.rs | #![crate_name = "uu_sleep"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uucore;
us... | (args: Vec<String>) {
let sleep_dur = args.iter().fold(Duration::new(0, 0), |result, arg|
match uucore::parse_time::from_str(&arg[..]) {
Ok(m) => m + result,
Err(f) => crash!(1, "{}", f),
});
thread::sleep(sleep_dur);
}
| sleep | identifier_name |
sleep.rs | #![crate_name = "uu_sleep"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uucore;
us... | Pause for NUMBER seconds. SUFFIX may be's' for seconds (the default),
'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations
that require NUMBER be an integer, here NUMBER may be an arbitrary floating
point number. Given two or more arguments, pause for the amount of time
specified by the sum of... | {
let mut opts = getopts::Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => {
show_error!("{}", f);
retur... | identifier_body |
sleep.rs | #![crate_name = "uu_sleep"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uucore;
us... | 'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations
that require NUMBER be an integer, here NUMBER may be an arbitrary floating
point number. Given two or more arguments, pause for the amount of time
specified by the sum of their values.", NAME, VERSION);
print!("{}", opts.usage(&msg))... | {0} NUMBER[SUFFIX]
or
{0} OPTION
Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), | random_line_split |
flatten.rs | use {Future, IntoFuture, Task, Poll};
use chain::Chain;
/// Future for the `flatten` combinator, flattening a future-of-a-future to get just
/// the result of the final future.
///
/// This is created by this `Future::flatten` method.
pub struct Flatten<A> where A: Future, A::Item: IntoFuture {
state: Chain<A, <A:... | (&mut self)
-> Option<Box<Future<Item=Self::Item, Error=Self::Error>>> {
self.state.tailcall()
}
}
| tailcall | identifier_name |
flatten.rs | use {Future, IntoFuture, Task, Poll};
use chain::Chain;
/// Future for the `flatten` combinator, flattening a future-of-a-future to get just
/// the result of the final future.
///
/// This is created by this `Future::flatten` method.
pub struct Flatten<A> where A: Future, A::Item: IntoFuture {
state: Chain<A, <A:... | })
}
fn schedule(&mut self, task: &mut Task) {
self.state.schedule(task)
}
fn tailcall(&mut self)
-> Option<Box<Future<Item=Self::Item, Error=Self::Error>>> {
self.state.tailcall()
}
} |
fn poll(&mut self, task: &mut Task) -> Poll<Self::Item, Self::Error> {
self.state.poll(task, |a, ()| {
let future = try!(a).into_future();
Ok(Err(future)) | random_line_split |
flatten.rs | use {Future, IntoFuture, Task, Poll};
use chain::Chain;
/// Future for the `flatten` combinator, flattening a future-of-a-future to get just
/// the result of the final future.
///
/// This is created by this `Future::flatten` method.
pub struct Flatten<A> where A: Future, A::Item: IntoFuture {
state: Chain<A, <A:... |
impl<A> Future for Flatten<A>
where A: Future,
A::Item: IntoFuture,
<<A as Future>::Item as IntoFuture>::Error: From<<A as Future>::Error>
{
type Item = <<A as Future>::Item as IntoFuture>::Item;
type Error = <<A as Future>::Item as IntoFuture>::Error;
fn poll(&mut self, task: &mu... | {
Flatten {
state: Chain::new(future, ()),
}
} | identifier_body |
coherence-orphan.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 |
coherence-orphan.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 ... | { } | identifier_body | |
coherence-orphan.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!Send for Vec<isize> { }
//~^ ERROR E0117
//~| ERROR E0119
fn main() { } | random_line_split | |
lib.rs | running Workunit as being in a blocked state.
///
/// When the `in_workunit!` macro exits, the Workunit on the stack is completed by storing any
/// local mutated values as the final value of the Workunit.
///
#[derive(Clone, Debug)]
pub struct Workunit {
pub name: String,
pub span_id: SpanId,
pub parent_id: Opt... | (&self) -> bool {
match self {
WorkunitState::Completed {.. } => true,
WorkunitState::Started {.. } => false,
}
}
fn blocked(&self) -> bool {
match self {
WorkunitState::Started { blocked,.. } => blocked.load(atomic::Ordering::Relaxed),
WorkunitState::Completed {.. } => false,
... | completed | identifier_name |
lib.rs | running Workunit as being in a blocked state.
///
/// When the `in_workunit!` macro exits, the Workunit on the stack is completed by storing any
/// local mutated values as the final value of the Workunit.
///
#[derive(Clone, Debug)]
pub struct Workunit {
pub name: String,
pub span_id: SpanId,
pub parent_id: Opt... |
};
if let Some(metadata) = new_metadata {
workunit.metadata = metadata;
}
}
}
}
fn refresh_store(&self) {
let mut inner = self.inner.lock();
let receiver = self.msg_rx.lock();
while let Ok(msg) = receiver.try_recv() {
match msg {
StoreMsg::Star... | {
let time_span = TimeSpan::from_start_and_end_systemtime(&start_time, &end_time);
workunit.state = WorkunitState::Completed { time_span };
} | conditional_block |
lib.rs | running Workunit as being in a blocked state.
///
/// When the `in_workunit!` macro exits, the Workunit on the stack is completed by storing any
/// local mutated values as the final value of the Workunit.
///
#[derive(Clone, Debug)]
pub struct Workunit {
pub name: String,
pub span_id: SpanId,
pub parent_id: Opt... |
fn blocked(&self) -> bool {
match self {
WorkunitState::Started { blocked,.. } => blocked.load(atomic::Ordering::Relaxed),
WorkunitState::Completed {.. } => false,
}
}
}
// NB: Only implemented for `fs::DirectoryDigest`, but is boxed to avoid a cycle between this crate
// and the `fs` crate.
... | {
match self {
WorkunitState::Completed { .. } => true,
WorkunitState::Started { .. } => false,
}
} | identifier_body |
lib.rs | the running Workunit as being in a blocked state.
///
/// When the `in_workunit!` macro exits, the Workunit on the stack is completed by storing any
/// local mutated values as the final value of the Workunit.
///
#[derive(Clone, Debug)]
pub struct Workunit {
pub name: String,
pub span_id: SpanId,
pub parent_id:... | completed_messages.push((span, metadata, time))
}
StoreMsg::Canceled(..) => (),
}
}
}
let mut workunit_records = self.workunit_records.lock();
let mut started_workunits: Vec<Workunit> = vec![];
for mut started in started_messages.into_iter() {
let spa... | match msg {
StoreMsg::Started(started) => started_messages.push(started),
StoreMsg::Completed(span, metadata, time) => { | random_line_split |
builder.rs | use super::{op::*, Script};
use crate::{constants::MAX_SCRIPT_BYTE_SIZE, serializer::*};
type FnRef = (u8, u32); // ID, pointer
#[derive(Clone, Debug, Default)]
pub struct Builder {
lookup_table: Vec<FnRef>,
body: Vec<u8>,
}
impl Builder {
pub fn new() -> Self {
Self {
lookup_table: V... | );
debug_assert_eq!(
script.capacity(),
total_len,
"additional allocation was performed, total length is incorrect"
);
Ok(Script::new(script))
}
pub fn push(mut self, function: FnBuilder) -> Self {
if self.lookup_table.len() + 1 > usi... | {
// 1 byte for fn len, 5 bytes for 1 byte id + 4 bytes pointer per fn
let header_len = 1 + (self.lookup_table.len() * 5);
let total_len = header_len + self.body.len();
if total_len > MAX_SCRIPT_BYTE_SIZE {
return Err(total_len);
}
let mut script = Vec::<u8>::... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.