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 |
|---|---|---|---|---|
levenshtein.rs | // Copyright (c) 2016. See AUTHORS file.
//
// 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 agr... |
#[test]
fn unicode() {
assert_eq!(2, levenshtein("SpΓ€Γe", "SpaΓ"));
assert_eq!(5, levenshtein("γγγγͺγ", "γγγ«γ‘γ―"));
assert_eq!(1, levenshtein("γγγγͺγ", "γγγγͺγ"));
assert_eq!(4, levenshtein("γγγ«γ‘γ―", "γγγ«γ‘γ― abc"));
assert_eq!(1, levenshtein("ΰΌΰΌΚ", "ΰΌΛ₯Κ"));
}
} | {
assert_eq!(4, levenshtein("book", ""));
assert_eq!(4, levenshtein("", "book"));
assert_eq!(0, levenshtein("", ""));
} | identifier_body |
levenshtein.rs | // Copyright (c) 2016. See AUTHORS file.
//
// 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 agr... | else {1};
mat[i+1][j+1] = utils::min3(
mat[i][j+1] + 1, // deletion
mat[i+1][j] + 1, // insertion
mat[i][j] + substitution // substitution
);
}
}
return mat[len_s][len_t];
}
#[cfg(test)]
mod tests {
... | {0} | conditional_block |
levenshtein.rs | // Copyright (c) 2016. See AUTHORS file.
//
// 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 agr... | () {
assert_eq!(0, levenshtein("kitten", "kitten"));
assert_eq!(0, levenshtein("a", "a"));
}
#[test]
fn cases() {
assert_eq!(1, levenshtein("Hello", "hello"));
assert_eq!(1, levenshtein("World", "world"));
}
#[test]
fn empty() {
assert_eq!(4, levenshtein... | equal | identifier_name |
mod.rs | // Copyright (c) 2016-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
//
// Unl... | pub fn with_keys<F>(&self, mut with_closure: F)
where
F: FnMut((&String, &HashMap<String, T>)),
{
let list = self.list.read().expect("Rumor store lock poisoned");
for x in list.iter() {
with_closure(x);
}
}
pub fn with_rumors<F>(&self, key: &str, mut with... | let mut list = self.list.write().expect("Rumor store lock poisoned");
list.get_mut(key).and_then(|r| r.remove(id));
}
| random_line_split |
mod.rs | // Copyright (c) 2016-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
//
// Unl... | <F>(&self, key: &str, member_id: &str, mut with_closure: F)
where
F: FnMut(Option<&T>),
{
let list = self.list.read().expect("Rumor store lock poisoned");
with_closure(list.get(key).and_then(|r| r.get(member_id)));
}
pub fn write_to_bytes(&self, key: &str, member_id: &str) -> Re... | with_rumor | identifier_name |
mod.rs | // Copyright (c) 2016-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
//
// Unl... |
fn key(&self) -> &str {
&self.key
}
fn id(&self) -> &str {
&self.id
}
fn merge(&mut self, mut _other: FakeRumor) -> bool {
false
}
fn write_to_bytes(&self) -> Result<Vec<u8>> {
Ok(Vec::from(format!("{}-{}", self... | {
Rumor_Type::Fake
} | identifier_body |
print_iter.rs | use cw::{BLOCK, Crosswords, Dir, Point};
/// An element representing a part of a crosswords grid: an element of the cell's borders, a cell
/// and its contents or a line break. It should be converted to a textual or graphical
/// representation.
///
/// The variants specifying borders contain a boolean value specifyin... | <'a> {
point: Point,
between_lines: bool,
between_chars: bool,
cw: &'a Crosswords,
hint_count: u32,
}
impl<'a> PrintIter<'a> {
pub fn new(cw: &'a Crosswords) -> Self {
PrintIter {
point: Point::new(-1, -1),
between_lines: true,
between_chars: true,
... | PrintIter | identifier_name |
print_iter.rs | use cw::{BLOCK, Crosswords, Dir, Point};
/// An element representing a part of a crosswords grid: an element of the cell's borders, a cell
/// and its contents or a line break. It should be converted to a textual or graphical
/// representation.
///
/// The variants specifying borders contain a boolean value specifyin... | pub fn new(cw: &'a Crosswords) -> Self {
PrintIter {
point: Point::new(-1, -1),
between_lines: true,
between_chars: true,
cw: cw,
hint_count: 0,
}
}
}
impl<'a> Iterator for PrintIter<'a> {
type Item = PrintItem;
fn next(&mut se... | }
impl<'a> PrintIter<'a> { | random_line_split |
print_iter.rs | use cw::{BLOCK, Crosswords, Dir, Point};
/// An element representing a part of a crosswords grid: an element of the cell's borders, a cell
/// and its contents or a line break. It should be converted to a textual or graphical
/// representation.
///
/// The variants specifying borders contain a boolean value specifyin... |
Some(result)
}
}
| {
if self.between_lines {
result = PrintItem::HorizBorder(self.cw.get_border(self.point, Dir::Down));
} else {
result = match self.cw.get_char(self.point).unwrap() {
BLOCK => PrintItem::Block,
c => {
... | conditional_block |
issue-35609.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
match (A, ()) { //~ ERROR non-exhaustive
(A, _) => {}
}
match (A, A) { //~ ERROR non-exhaustive
(_, A) => {}
}
match ((A, ()), ()) { //~ ERROR non-exhaustive
((A, ()), _) => {}
}
match ((A, ()), A) { //~ ERROR non-exhaustive
((A, ()), _) => {}
... | struct Sd { x: Enum, y: () } | random_line_split |
issue-35609.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 ... | {
A, B, C, D, E, F
}
use Enum::*;
struct S(Enum, ());
struct Sd { x: Enum, y: () }
fn main() {
match (A, ()) { //~ ERROR non-exhaustive
(A, _) => {}
}
match (A, A) { //~ ERROR non-exhaustive
(_, A) => {}
}
match ((A, ()), ()) { //~ ERROR non-exhaustive
((A, ()), _) =... | Enum | identifier_name |
coherence_inherent_cc.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... | () {}
| main | identifier_name |
coherence_inherent_cc.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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file... | random_line_split | |
coherence_inherent_cc.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... | {} | identifier_body | |
main.rs | #![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn main() | print!(".");
}
}
println!("\nTotal elapsed time: {:?}", start.elapsed());
}
| {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zmq::PULL).unwrap();
assert!(receiver.bind("tcp://*:5558").is_ok());
// Wait for start of batch
let mut msg = zmq::Message::new().unwrap();
receiver.recv(&mut msg, 0).unwrap();... | identifier_body |
main.rs | #![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn main() {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zm... | receiver.recv(&mut msg, 0).unwrap();
// Start our clock now
let start = Instant::now();
for i in 1..101 {
receiver.recv(&mut msg, 0).unwrap();
if i % 10 == 0 {
print!(":");
} else {
print!(".");
}
}
println!("\nTotal elapsed time: ... | let mut msg = zmq::Message::new().unwrap();
| random_line_split |
main.rs | #![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn main() {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zm... |
}
println!("\nTotal elapsed time: {:?}", start.elapsed());
}
| {
print!(".");
} | conditional_block |
main.rs | #![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn | () {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zmq::PULL).unwrap();
assert!(receiver.bind("tcp://*:5558").is_ok());
// Wait for start of batch
let mut msg = zmq::Message::new().unwrap();
receiver.recv(&mut msg, 0).unwrap... | main | identifier_name |
display.rs | //! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display f... |
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: false }
}
}
| {
DisplayCausesAndBacktrace { err: self, include_backtrace: true }
} | identifier_body |
display.rs | //! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display f... |
}
if self.include_backtrace {
write!(f, "{}", self.err.backtrace())?;
}
Ok(())
}
}
/// Extensions to standard `failure::Error` trait.
pub trait DisplayCausesAndBacktraceExt {
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with... | {
writeln!(f, " caused by: {}", cause)?;
} | conditional_block |
display.rs | //! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display f... | (&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: true }
}
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: false }
}
}
| display_causes_and_backtrace | identifier_name |
display.rs | //! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display f... | pub trait DisplayCausesAndBacktraceExt {
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes, plus an optional
/// backtrace.
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace;
/// Wrap the error in `DisplayCau... | }
/// Extensions to standard `failure::Error` trait. | random_line_split |
util.rs | use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn get_hash<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [0... |
impl FaI {
fn from_data<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
let mut hash_arr: [u8; FINGERPRINT_SIZE] = [0; FINGERPRINT_SIZE];
let hash = get_hash::<_, H>(data);
let mut n = 0;
let fp;
loop {
for i in 0..FINGERPRINT_SIZE {
hash_arr[i] = hash[i] + n;
}
... | {
let hash = get_hash::<_, H>(&fp.data);
let alt_i = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
(i ^ alt_i) as usize
} | identifier_body |
util.rs | use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn get_hash<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [0... |
n += 1;
}
let i1 = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
let i2 = get_alt_index::<H>(fp, i1);
FaI {
fp: fp, i1: i1, i2: i2
}
}
pub fn random_index<R: ::rand::Rng>(&self, r: &mut R) -> usize {
if r.gen() {
self.i1
} else {
self.i2
}
}
}
... | {
fp = val;
break;
} | conditional_block |
util.rs | use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn get_hash<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [0... | FaI {
fp: fp, i1: i1, i2: i2
}
}
pub fn random_index<R: ::rand::Rng>(&self, r: &mut R) -> usize {
if r.gen() {
self.i1
} else {
self.i2
}
}
}
pub fn get_fai<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
FaI::from_data::<_, H>(data)
}
#[test]
fn test_fp_and... | let i1 = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
let i2 = get_alt_index::<H>(fp, i1); | random_line_split |
util.rs | use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn | <T:?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [0; 4];
{
let mut hasher = <H as Default>::default();
data.hash(&mut hasher);
let _ = (&mut result[..]).write_u32::<BigEndian>(hasher.finish() as u32);
}
result
}
pub fn get_alt_index<H: Hasher + Default>(fp: Fingerprint... | get_hash | identifier_name |
svgsvgelement.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::SVGSVGElementBinding;
use dom::bindings::inheritance::C... |
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> Root<SVGSVGElement> {
Node::reflect_node(box SVGSVGElement::new_inherited(local_name, prefix, document),
document,
... | {
SVGSVGElement {
svggraphicselement:
SVGGraphicsElement::new_inherited(local_name, prefix, document)
}
} | identifier_body |
svgsvgelement.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::SVGSVGElementBinding;
use dom::bindings::inheritance::C... | {
svggraphicselement: SVGGraphicsElement
}
impl SVGSVGElement {
fn new_inherited(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> SVGSVGElement {
SVGSVGElement {
svggraphicselement:
SVGGraphicsElement::new_inhe... | SVGSVGElement | identifier_name |
svgsvgelement.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::SVGSVGElementBinding;
use dom::bindings::inheritance::C... | }
pub trait LayoutSVGSVGElementHelpers {
fn data(&self) -> SVGSVGData;
}
impl LayoutSVGSVGElementHelpers for LayoutJS<SVGSVGElement> {
#[allow(unsafe_code)]
fn data(&self) -> SVGSVGData {
unsafe {
let SVG = &*self.unsafe_get();
let width_attr = SVG.upcast::<Element>().get_... | random_line_split | |
multiple_files.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 args = os::args();
let rustc = args.get(1).as_slice();
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
let main_file_str = main_file.as_str().unwrap();
{
let _ = File::create(&main_file).unwrap()
.w... | main | identifier_name |
multiple_files.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 main() {
let args = os::args();
let rustc = args.get(1).as_slice();
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
let main_file_str = main_file.as_str().unwrap();
{
let _ = File::create(&main_file).unwrap()
... | {
let mut rng = task_rng();
// a subset of the XID_start unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1, 4 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
... | identifier_body |
multiple_files.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 ... | // compiler changes.
assert!(err.as_slice().contains("expected item but found"))
}
} | // can't exec it directly
let result = Process::output("sh", ["-c".to_owned(), rustc + " " + main_file_str]).unwrap();
let err = str::from_utf8_lossy(result.error.as_slice());
// positive test so that this test will be updated when the | random_line_split |
aes_ecb_decrypter.rs | /* AES-128 ECB mode decrypter
*
* Dmitry Vasiliev <dima@hlabs.org>
*/
extern crate serialize;
extern crate aes_lib;
use std::path::Path;
use std::io::fs::File;
use serialize::base64::FromBase64;
use aes_lib::decrypt_aes_ecb;
fn | (mut file: File, key: &[u8]) -> Vec<u8> {
let data = file.read_to_end().unwrap();
let text = String::from_utf8(data).unwrap();
let encrypted = text.from_base64().unwrap();
decrypt_aes_ecb(encrypted.as_slice(), key)
}
/*
* Main entry point
*/
fn main() {
let key = b"YELLOW SUBMARINE";
let path... | decrypt_aes_ecb_file | identifier_name |
aes_ecb_decrypter.rs | /* AES-128 ECB mode decrypter
*
* Dmitry Vasiliev <dima@hlabs.org>
*/
extern crate serialize;
extern crate aes_lib;
use std::path::Path;
use std::io::fs::File;
use serialize::base64::FromBase64;
use aes_lib::decrypt_aes_ecb;
fn decrypt_aes_ecb_file(mut file: File, key: &[u8]) -> Vec<u8> |
/*
* Main entry point
*/
fn main() {
let key = b"YELLOW SUBMARINE";
let path = Path::new("aes_ecb_encrypted.txt");
let decrypted = match File::open(&path) {
Ok(file) => decrypt_aes_ecb_file(file, key),
Err(err) => panic!("Unable to open aes_ecb_encrypted.txt: {}", err)
};
println... | {
let data = file.read_to_end().unwrap();
let text = String::from_utf8(data).unwrap();
let encrypted = text.from_base64().unwrap();
decrypt_aes_ecb(encrypted.as_slice(), key)
} | identifier_body |
aes_ecb_decrypter.rs | /* AES-128 ECB mode decrypter
*
* Dmitry Vasiliev <dima@hlabs.org>
*/
|
use std::path::Path;
use std::io::fs::File;
use serialize::base64::FromBase64;
use aes_lib::decrypt_aes_ecb;
fn decrypt_aes_ecb_file(mut file: File, key: &[u8]) -> Vec<u8> {
let data = file.read_to_end().unwrap();
let text = String::from_utf8(data).unwrap();
let encrypted = text.from_base64().unwrap();
... | extern crate serialize;
extern crate aes_lib; | random_line_split |
issue-19358.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 ... | struct Bar<T> where T: Trait {
bar: T,
}
impl Trait for int {}
fn main() {
let a = Foo { foo: 12i };
let b = Bar { bar: 12i };
println!("{:?} {:?}", a, b);
} | random_line_split | |
issue-19358.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let a = Foo { foo: 12i };
let b = Bar { bar: 12i };
println!("{:?} {:?}", a, b);
}
| main | identifier_name |
miner_service.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.... |
/// Set the lower gas limit we wish to target when sealing a new block.
fn set_gas_floor_target(&self, target: U256) {
self.gas_range_target.write().0 = target;
}
/// Set the upper gas limit we wish to target when sealing a new block.
fn set_gas_ceil_target(&self, target: U256) {
self.gas_range_target.write... | {
*self.extra_data.write() = extra_data;
} | identifier_body |
miner_service.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 all_transactions(&self) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_transactions(&self, _best_block: BlockNumber) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_receipt(&self, _best_block: Blo... | fn transaction(&self, _best_block: BlockNumber, hash: &H256) -> Option<SignedTransaction> {
self.pending_transactions.lock().get(hash).cloned()
} | random_line_split |
miner_service.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.... |
// lets assume that all txs are valid
self.imported_transactions.lock().push(transaction);
Ok(TransactionImportResult::Current)
}
/// Returns hashes of transactions currently in pending
fn pending_transactions_hashes(&self, _best_block: BlockNumber) -> Vec<H256> {
vec![]
}
/// Removes all transactions... | {
let nonce = self.last_nonce(sender).unwrap_or(chain.latest_nonce(sender));
self.last_nonces.write().insert(sender.clone(), nonce + U256::from(1));
} | conditional_block |
miner_service.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.... | (&self, extra_data: Bytes) {
*self.extra_data.write() = extra_data;
}
/// Set the lower gas limit we wish to target when sealing a new block.
fn set_gas_floor_target(&self, target: U256) {
self.gas_range_target.write().0 = target;
}
/// Set the upper gas limit we wish to target when sealing a new block.
fn ... | set_extra_data | identifier_name |
windows.rs | );
1
}
winapi::CTRL_BREAK_EVENT => {
write_fake_key(SIGQUIT_KEY);
1
}
winapi::CTRL_CLOSE_EVENT => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
0... | {
hndl: winapi::HANDLE,
size: winapi::COORD,
}
impl Resizer {
fn from_conout() -> Result<Resizer> {
let hndl = unsafe {
kernel32::CreateFileA(
"CONOUT$\x00".as_ptr() as *const _ as winapi::LPCSTR,
winapi::GENERIC_READ | winapi::GENERIC_WRITE,
... | Resizer | identifier_name |
windows.rs | _KEY);
1
}
winapi::CTRL_BREAK_EVENT => {
write_fake_key(SIGQUIT_KEY);
1
}
winapi::CTRL_CLOSE_EVENT => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
... | let presses = new_btns - self.btns;
let releases = self.btns - new_btns;
self.btns = new_btns;
if presses.contains(Btn::LEFT) {
let mevt = InputEvent::Mouse(Press, Left, mods, coords);
self.send(mevt)?;
... | 0 | 2 => {
let new_btns = Btn::from_bits(evt.dwButtonState & 0x7).unwrap(); | random_line_split |
windows.rs | );
1
}
winapi::CTRL_BREAK_EVENT => {
write_fake_key(SIGQUIT_KEY);
1
}
winapi::CTRL_CLOSE_EVENT => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
0... | if presses.contains(Btn::MIDDLE) {
let mevt = InputEvent::Mouse(Press, Middle, mods, coords);
self.send(mevt)?;
}
if presses.contains(Btn::RIGHT) {
let mevt = InputEvent::Mouse(Press, Right, mods, coords);
... | {
use input::ButtonMotion::*;
use input::MouseButton::*;
use input::WheelMotion::*;
let coords = (
(evt.dwMousePosition.X as u16),
(evt.dwMousePosition.Y as u16),
);
let mods = Mods::win32(evt.dwControlKeyState);
match evt.dwEventFlags {
... | identifier_body |
dj.rs | extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "... | () {
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(&env::var("DISCORD_TOKEN").expect("Expected token"))
.expect("login failed");
// establish websocket and voice connection
let (mut connection, ready) = discord.connect().expect("connect failed");
println!(
"... | main | identifier_name |
dj.rs | extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "... |
if let discord::Error::Closed(..) = err {
break;
}
continue;
}
};
state.update(&event);
match event {
Event::MessageCreate(message) => {
// safeguard: stop if the message is from us
if message.author.id == state.user().id {
continue;
}
// reply to a command if there ... | {
// Handle the websocket connection being dropped
let (new_connection, ready) = discord.connect().expect("connect failed");
connection = new_connection;
state = State::new(ready);
println!("[Ready] Reconnected successfully.");
} | conditional_block |
dj.rs | extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "... | println!("[Warning] Receive error: {:?}", err);
if let discord::Error::WebSocket(..) = err {
// Handle the websocket connection being dropped
let (new_connection, ready) = discord.connect().expect("connect failed");
connection = new_connection;
state = State::new(ready);
println!("[Read... | {
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(&env::var("DISCORD_TOKEN").expect("Expected token"))
.expect("login failed");
// establish websocket and voice connection
let (mut connection, ready) = discord.connect().expect("connect failed");
println!(
"[Re... | identifier_body |
dj.rs | extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "... | }
}
}
_ => {} // discard other events
}
}
}
fn warn<T, E: ::std::fmt::Debug>(result: Result<T, E>) {
match result {
Ok(_) => {}
Err(err) => println!("[Warning] {:?}", err),
}
} | connection.voice(server_id).disconnect();
}
}
} | random_line_split |
lib.rs | #[allow(unused_variables)]
// Because these are passed without & to some functions,
// it will probably be necessary for these two types to be Copy.
pub type CellID = ();
pub type CallbackID = ();
pub struct Reactor<T> {
// Just so that the compiler doesn't complain about an unused type parameter.
// You prob... | unimplemented!()
}
} | random_line_split | |
lib.rs | #[allow(unused_variables)]
// Because these are passed without & to some functions,
// it will probably be necessary for these two types to be Copy.
pub type CellID = ();
pub type CallbackID = ();
pub struct Reactor<T> {
// Just so that the compiler doesn't complain about an unused type parameter.
// You prob... | (&mut self, id: CellID, new_value: T) -> Result<(), ()> {
unimplemented!()
}
// Adds a callback to the specified compute cell.
//
// Return an Err (and you can change the error type) if the cell does not exist.
//
// Callbacks on input cells will not be tested.
//
// The semanti... | set_value | identifier_name |
lib.rs | #[allow(unused_variables)]
// Because these are passed without & to some functions,
// it will probably be necessary for these two types to be Copy.
pub type CellID = ();
pub type CallbackID = ();
pub struct Reactor<T> {
// Just so that the compiler doesn't complain about an unused type parameter.
// You prob... |
// Removes the specified callback, using an ID returned from add_callback.
//
// Return an Err (and you can change the error type) if either the cell or callback
// does not exist.
//
// A removed callback should no longer be called.
pub fn remove_callback(&mut self, cell: CellID, callback... | {
unimplemented!()
} | identifier_body |
direct_irq.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;... | /// Note: this feature is not part of VFIO, but provides
/// missing IRQ forwarding functionality.
///
/// # Arguments
///
/// * `irq_num` - host interrupt number (GSI).
///
pub fn irq_enable(&self, irq_num: u32) -> Result<(), DirectIrqError> {
if let Some(resample) = &self.resam... | /// | random_line_split |
direct_irq.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;... |
/// Enable hardware triggered interrupt handling.
///
/// Note: this feature is not part of VFIO, but provides
/// missing IRQ forwarding functionality.
///
/// # Arguments
///
/// * `irq_num` - host interrupt number (GSI).
///
pub fn irq_enable(&self, irq_num: u32) -> Result<(... | {
let dev = OpenOptions::new()
.read(true)
.write(true)
.open("/dev/plat-irq-forward")
.map_err(DirectIrqError::Open)?;
Ok(DirectIrq {
dev,
trigger,
resample,
})
} | identifier_body |
direct_irq.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;... | else {
Ok(())
}
}
}
impl AsRawDescriptor for DirectIrq {
fn as_raw_descriptor(&self) -> i32 {
self.dev.as_raw_descriptor()
}
}
| {
Err(DirectIrqError::Enable)
} | conditional_block |
direct_irq.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;... | (&self, irq_num: u32) -> Result<(), DirectIrqError> {
if let Some(resample) = &self.resample {
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_LEVEL_TRIGGER_EVENTFD,
self.trigger.as_raw_descriptor(),
)?;
self.plat_irq_ioctl(
... | irq_enable | identifier_name |
query_result.rs | use std::marker::PhantomData;
use serde::{de, Deserialize, Deserializer};
use uuid::Uuid;
/// A report about the outcome of a write.
#[derive(Debug)]
pub struct WriteStatus<T> {
/// The number of new documents inserted. This counter is zero in case of an update or delete
/// operation. In case of a replace ope... | <V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error>
where V: de::MapVisitor
{
let mut inserted = None;
let mut replaced = None;
let mut unchanged = None;
let mut skipped = None;
let mut deleted = None... | visit_map | identifier_name |
query_result.rs | use std::marker::PhantomData;
use serde::{de, Deserialize, Deserializer};
use uuid::Uuid;
/// A report about the outcome of a write.
#[derive(Debug)]
pub struct WriteStatus<T> {
/// The number of new documents inserted. This counter is zero in case of an update or delete
/// operation. In case of a replace ope... | Field::FirstError => first_error = Some(try!(visitor.visit_value())),
Field::GeneratedKeys => generated_keys = Some(try!(visitor.visit_value())),
Field::Warnings => warnings = Some(try!(visitor.visit_value())),
Field::Change... | {
let mut inserted = None;
let mut replaced = None;
let mut unchanged = None;
let mut skipped = None;
let mut deleted = None;
let mut errors = None;
let mut first_error = None;
let mut generat... | identifier_body |
query_result.rs | use std::marker::PhantomData;
use serde::{de, Deserialize, Deserializer};
use uuid::Uuid;
/// A report about the outcome of a write.
#[derive(Debug)]
pub struct WriteStatus<T> {
/// The number of new documents inserted. This counter is zero in case of an update or delete
/// operation. In case of a replace ope... |
/// The number of documents that would have been modified except the new value was the same as
/// the old value. This counter is zero in case of a delete operation or an insert operation
/// where `confict` is set to "error".
pub unchanged: u32,
/// The number of documents that were skipped becau... |
/// The number of documents that were updated or replaced. This counter is zero in case of a
/// delete operation or an insert operation where `conflict` isn't set to "replace" or "update".
pub replaced: u32, | random_line_split |
mq_handler.rs | // Copyright Cryptape Technologies LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... | {
responses: RpcMap,
}
impl MqHandler {
pub fn new(responses: RpcMap) -> Self {
MqHandler { responses }
}
pub fn handle(&mut self, key: &str, body: &[u8]) -> Result<(), ()> {
trace!("get msg from routing_key {}", key);
let mut msg = Message::try_from(body).map_err(|e| {
... | MqHandler | identifier_name |
mq_handler.rs | // Copyright Cryptape Technologies LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::helper::{RpcMap, TransferType};
use jsonrpc_proto::response::OutputExt;
use jsonrpc_types::rpc_response::Output;
use libproto::... | //
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
reader.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 ... |
}
impl<R: Reader> Rng for ReaderRng<R> {
fn next_u32(&mut self) -> u32 {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
if cfg!(target_endian="lit... | {
ReaderRng {
reader: r
}
} | identifier_body |
reader.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 ... | (&mut self) -> u32 {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
if cfg!(target_endian="little") {
self.reader.read_le_u32_()
} e... | next_u32 | identifier_name |
reader.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 ... | mod test {
use super::*;
use rt::io::mem::MemReader;
use cast;
#[test]
fn test_reader_rng_u64() {
// transmute from the target to avoid endianness concerns.
let v = ~[1u64, 2u64, 3u64];
let bytes: ~[u8] = unsafe {cast::transmute(v)};
let mut rng = ReaderRng::new(MemR... | #[cfg(test)] | random_line_split |
segment_stats.rs | use search::segment::Segment;
| pub struct SegmentStatistics {
total_docs: i64,
deleted_docs: i64,
}
impl SegmentStatistics {
fn read<S: Segment>(segment: &S) -> Result<SegmentStatistics, String> {
let total_docs = try!(segment.load_statistic(b"total_docs")).unwrap_or(0);
let deleted_docs = try!(segment.load_statistic(b"d... | use super::RocksDBStore;
#[derive(Debug)] | random_line_split |
segment_stats.rs | use search::segment::Segment;
use super::RocksDBStore;
#[derive(Debug)]
pub struct SegmentStatistics {
total_docs: i64,
deleted_docs: i64,
}
impl SegmentStatistics {
fn read<S: Segment>(segment: &S) -> Result<SegmentStatistics, String> {
let total_docs = try!(segment.load_statistic(b"total_docs")... |
}
impl RocksDBStore {
pub fn get_segment_statistics(&self) -> Result<Vec<(u32, SegmentStatistics)>, String> {
let mut segment_stats = Vec::new();
let reader = self.reader();
for segment in self.segments.iter_active(&reader) {
let stats = try!(SegmentStatistics::read(&segment))... | {
self.deleted_docs
} | identifier_body |
segment_stats.rs | use search::segment::Segment;
use super::RocksDBStore;
#[derive(Debug)]
pub struct SegmentStatistics {
total_docs: i64,
deleted_docs: i64,
}
impl SegmentStatistics {
fn read<S: Segment>(segment: &S) -> Result<SegmentStatistics, String> {
let total_docs = try!(segment.load_statistic(b"total_docs")... | (&self) -> i64 {
self.total_docs
}
#[inline]
pub fn deleted_docs(&self) -> i64 {
self.deleted_docs
}
}
impl RocksDBStore {
pub fn get_segment_statistics(&self) -> Result<Vec<(u32, SegmentStatistics)>, String> {
let mut segment_stats = Vec::new();
let reader = self.r... | total_docs | identifier_name |
ip2_convolve3x3.rs | /*
* Copyright (C) 2012 The Android Open Source Project
* | *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the Licen... | * 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 | random_line_split |
client.rs | use std;
import core::result::*;
import socket::*;
fn from_bytes_n(bytes: [const u8], count: uint) -> str |
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet_addr(host);
let sockaddr = new_sockaddr_in(af_inet, addr, port);
let r = connect(sock, sockaddr);
if failure(r) {
fail #fmt("cannot connect to %s:%u", host, port as uint);
}
... | {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
} | identifier_body |
client.rs | use std;
import core::result::*;
import socket::*;
fn | (bytes: [const u8], count: uint) -> str {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
}
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet_addr(host);
let sockaddr = new_sockaddr_in(af_inet, addr, port)... | from_bytes_n | identifier_name |
client.rs | import socket::*;
fn from_bytes_n(bytes: [const u8], count: uint) -> str {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
}
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet_addr(host);
let sockaddr = ne... | use std;
import core::result::*; | random_line_split | |
client.rs | use std;
import core::result::*;
import socket::*;
fn from_bytes_n(bytes: [const u8], count: uint) -> str {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
}
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet... |
send_str(sock, "HELLO", 0u);
let buf = vec::init_elt_mut(1024u, 0u8);
let size = recv(sock, buf, 0u);
let s = from_bytes_n(buf, size as uint);
std::io::println(s);
}
| {
fail #fmt("cannot connect to %s:%u", host, port as uint);
} | conditional_block |
position.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Position", inherited=False) %>
%... | (_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
specified::parse_integer(input)
}
</%helpers:longhand>
${helpers.predefined_type("flex-basis",
"LengthOrPercentageOrAutoOrContent",
"computed::LengthOrPercentageOrAutoOrContent... | parse | identifier_name |
position.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Position", inherited=False) %>
%... | ${helpers.predefined_type("flex-grow", "Number", "0.0", "parse_non_negative", experimental=True)}
${helpers.predefined_type("flex-shrink", "Number", "1.0", "parse_non_negative", experimental=True)}
${helpers.single_keyword("align-self", "auto stretch flex-start flex-end center baseline",
expe... | // Flex item properties | random_line_split |
method-ambig-one-trait-unknown-int-type.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 ... | // distinct functions, in this order, causes us to print out both
// errors I'd like to see.
fn m1() {
// we couldn't infer the type of the vector just based on calling foo()...
let mut x = Vec::new(); //~ ERROR type annotations required
x.foo();
}
fn m2() {
let mut x = Vec::new();
//...but we st... | }
// This is very hokey: we have heuristics to suppress messages about
// type annotations required. But placing these two bits of code into | random_line_split |
method-ambig-one-trait-unknown-int-type.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 ... | () { }
| main | identifier_name |
method-ambig-one-trait-unknown-int-type.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 ... |
}
impl foo for Vec<isize> {
fn foo(&self) -> isize {2}
}
// This is very hokey: we have heuristics to suppress messages about
// type annotations required. But placing these two bits of code into
// distinct functions, in this order, causes us to print out both
// errors I'd like to see.
fn m1() {
// we cou... | {1} | identifier_body |
union-derive-rpass.rs | // run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![allow(dead_code)]
#![allow(unused_variables)]
// Some traits can be derived for unions. | )]
union U {
a: u8,
b: u16,
}
impl PartialEq for U { fn eq(&self, rhs: &Self) -> bool { true } }
#[derive(
Clone,
Copy,
Eq
)]
union W<T: Copy> {
a: T,
}
impl<T: Copy> PartialEq for W<T> { fn eq(&self, rhs: &Self) -> bool { true } }
fn main() {
let u = U { b: 0 };
let u1 = u;
let ... |
#[derive(
Copy,
Clone,
Eq, | random_line_split |
union-derive-rpass.rs | // run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![allow(dead_code)]
#![allow(unused_variables)]
// Some traits can be derived for unions.
#[derive(
Copy,
Clone,
Eq,
)]
union U {
a: u8,
b: u16,
}
impl PartialEq for U { fn eq(&self, rhs: &Self) ... | {
let u = U { b: 0 };
let u1 = u;
let u2 = u.clone();
assert!(u1 == u2);
let w = W { a: 0 };
let w1 = w.clone();
assert!(w == w1);
} | identifier_body | |
union-derive-rpass.rs | // run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![allow(dead_code)]
#![allow(unused_variables)]
// Some traits can be derived for unions.
#[derive(
Copy,
Clone,
Eq,
)]
union U {
a: u8,
b: u16,
}
impl PartialEq for U { fn | (&self, rhs: &Self) -> bool { true } }
#[derive(
Clone,
Copy,
Eq
)]
union W<T: Copy> {
a: T,
}
impl<T: Copy> PartialEq for W<T> { fn eq(&self, rhs: &Self) -> bool { true } }
fn main() {
let u = U { b: 0 };
let u1 = u;
let u2 = u.clone();
assert!(u1 == u2);
let w = W { a: 0 };
... | eq | identifier_name |
mod.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
annotatable: Annotatable)
-> Annotatable {
annotatable.map_item_or(|item| {
item.map(|mut item| {
if mitem.value_str().is_some() {
cx.span_err(mitem.span, "unexpec... | expand_derive | identifier_name |
mod.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
if!(is_builtin_trait(tname) || cx.ecfg.enable_custom_derive()) {
feature_gate::emit_feature_err(&cx.parse_sess.span_diagnostic,
"custom_derive",
titem.span,
... | {
annotatable.map_item_or(|item| {
item.map(|mut item| {
if mitem.value_str().is_some() {
cx.span_err(mitem.span, "unexpected value in `derive`");
}
let traits = mitem.meta_item_list().unwrap_or(&[]);
if traits.is_empty() {
cx.... | identifier_body |
mod.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
for titem in traits.iter().rev() {
let tname = match titem.node {
MetaWord(ref tname) => tname,
_ => {
cx.span_err(titem.span, "malformed `derive` entry");
continue;
}
... | {
cx.span_warn(mitem.span, "empty trait list in `derive`");
} | conditional_block |
mod.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
//! The compiler code necessary to implement the `#[derive]` extensions.
//!
//! FIXME (#2810): hygiene. Search for "__" strings (in other files too). We also assume "extra" is
//! the standard library, and "std" is the core library.
use ast::{MetaItem, MetaWord};
use attr::AttrMetaMethods;
use ext::base::{ExtCtxt, S... | // except according to those terms. | random_line_split |
lib.rs | // Copyright 2016 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// 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/.
//! Fast and lightweight Slab Allocator.
extern cra... | unsafe {
let elem_ptr = self.mem.offset(x as isize);
ptr::drop_in_place(elem_ptr);
}
}
unsafe { libc::free(self.mem as *mut _ as *mut libc::c_void) };
}
}
impl<T> Index<usize> for Slab<T> {
type Output = T;
fn index(&self, index: usiz... | for x in 0..self.len() { | random_line_split |
lib.rs | // Copyright 2016 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// 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/.
//! Fast and lightweight Slab Allocator.
extern cra... |
/// Removes the element at `offset`.
///
/// # Panics
///
/// * If `offset` is out of bounds.
#[inline]
pub fn remove(&mut self, offset: usize) -> T {
assert!(offset < self.len, "Offset out of bounds");
let elem: T;
let last_elem: T;
let elem_ptr: *mut T;
... | {
if self.len == self.capacity {
self.reallocate();
}
unsafe {
let ptr = self.mem.offset(self.len as isize);
ptr::write(ptr, elem);
}
self.len += 1;
} | identifier_body |
lib.rs | // Copyright 2016 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// 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/.
//! Fast and lightweight Slab Allocator.
extern cra... | (&self, index: usize) -> &Self::Output {
assert!(index < self.len, "Index out of bounds");
unsafe { &(*(self.mem.offset(index as isize))) }
}
}
impl<'a, T> Iterator for SlabIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
while self.current_offset < self.slab.l... | index | identifier_name |
lib.rs | // Copyright 2016 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// 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/.
//! Fast and lightweight Slab Allocator.
extern cra... |
unsafe {
let ptr = self.mem.offset(self.len as isize);
ptr::write(ptr, elem);
}
self.len += 1;
}
/// Removes the element at `offset`.
///
/// # Panics
///
/// * If `offset` is out of bounds.
#[inline]
pub fn remove(&mut self, offset: us... | {
self.reallocate();
} | conditional_block |
trait-inheritance-auto.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
fn f<T:Quux>(a: &T) {
assert!(a.f() == 10);
assert!(a.g() == 20);
assert!(a.h() == 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
| { 30 } | identifier_body |
trait-inheritance-auto.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert!(a.f() == 10);
assert!(a.g() == 20);
assert!(a.h() == 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
} | impl Bar for A { fn g(&self) -> int { 20 } }
impl Baz for A { fn h(&self) -> int { 30 } }
fn f<T:Quux>(a: &T) { | random_line_split |
trait-inheritance-auto.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> int { 30 } }
fn f<T:Quux>(a: &T) {
assert!(a.f() == 10);
assert!(a.g() == 20);
assert!(a.h() == 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
| h | identifier_name |
app_blink_stm32f4.rs | #![feature(phase)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[no_mangle]
#[no_split_stack]
#[allow(unused_variable)]
#[allow(dead_code)] | zinc::hal::mem_init::init_data();
let led1 = pin::PinConf{
port: pin::PortG,
pin: 13u8,
function: pin::GPIOOut
};
let led2 = pin::PinConf{
port: pin::PortG,
pin: 14u8,
function: pin::GPIOOut
};
led1.setup();
led2.setup();
let timer = timer::Timer::new(timer::Timer2, 25u32);
... | pub unsafe fn main() {
use zinc::hal::timer::Timer;
use zinc::hal::stm32f4::{pin, timer};
zinc::hal::mem_init::init_stack(); | random_line_split |
app_blink_stm32f4.rs | #![feature(phase)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[no_mangle]
#[no_split_stack]
#[allow(unused_variable)]
#[allow(dead_code)]
pub unsafe fn | () {
use zinc::hal::timer::Timer;
use zinc::hal::stm32f4::{pin, timer};
zinc::hal::mem_init::init_stack();
zinc::hal::mem_init::init_data();
let led1 = pin::PinConf{
port: pin::PortG,
pin: 13u8,
function: pin::GPIOOut
};
let led2 = pin::PinConf{
port: pin::PortG,
pin: 14u8,
functi... | main | identifier_name |
app_blink_stm32f4.rs | #![feature(phase)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[no_mangle]
#[no_split_stack]
#[allow(unused_variable)]
#[allow(dead_code)]
pub unsafe fn main() |
loop {
led1.set_high();
led2.set_low();
timer.wait_ms(300);
led1.set_low();
led2.set_high();
timer.wait_ms(300);
}
}
| {
use zinc::hal::timer::Timer;
use zinc::hal::stm32f4::{pin, timer};
zinc::hal::mem_init::init_stack();
zinc::hal::mem_init::init_data();
let led1 = pin::PinConf{
port: pin::PortG,
pin: 13u8,
function: pin::GPIOOut
};
let led2 = pin::PinConf{
port: pin::PortG,
pin: 14u8,
function:... | identifier_body |
adsr.rs | // Copyright 2017 Google Inc. All rights reserved.
//
// 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... | Adsr {
value: -24.0,
state: Quiet,
}
}
}
impl Module for Adsr {
fn n_ctrl_out(&self) -> usize { 1 }
fn handle_note(&mut self, _midi_num: f32, _velocity: f32, on: bool) {
if on {
self.state = Attack;
} else {
self.state = Relea... | pub fn new() -> Adsr { | random_line_split |
adsr.rs | // Copyright 2017 Google Inc. All rights reserved.
//
// 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... | () -> Adsr {
Adsr {
value: -24.0,
state: Quiet,
}
}
}
impl Module for Adsr {
fn n_ctrl_out(&self) -> usize { 1 }
fn handle_note(&mut self, _midi_num: f32, _velocity: f32, on: bool) {
if on {
self.state = Attack;
} else {
self.... | new | identifier_name |
console.rs | use super::super::backend::Backend;
use super::super::buckets::Buckets;
use time;
#[derive(Debug)]
pub struct Console;
impl Console {
/// Create a Console formatter that prints to stdout
///
/// # Examples
///
/// ```
/// let cons = Console::new();
/// ```
pub fn new() -> Console {
... | }
println!(" timer_data:");
for (key, values) in buckets.timer_data().iter() {
println!(" {}: {:?}", key, values);
}
}
}
| {
let now = time::get_time();
println!("Flushing metrics: {}", time::at(now).rfc822().to_string());
println!(" bad_messages: {}", buckets.bad_messages());
println!(" total_messages: {}", buckets.total_messages());
println!(" counters:");
for (key, value) in buckets.c... | identifier_body |
console.rs | use super::super::backend::Backend;
use super::super::buckets::Buckets;
use time;
#[derive(Debug)]
pub struct Console; | impl Console {
/// Create a Console formatter that prints to stdout
///
/// # Examples
///
/// ```
/// let cons = Console::new();
/// ```
pub fn new() -> Console {
Console
}
}
/// Print a single stats line.
fn fmt_line(key: &str, value: &f64) {
println!(" {}: {}", key... | random_line_split | |
console.rs | use super::super::backend::Backend;
use super::super::buckets::Buckets;
use time;
#[derive(Debug)]
pub struct Console;
impl Console {
/// Create a Console formatter that prints to stdout
///
/// # Examples
///
/// ```
/// let cons = Console::new();
/// ```
pub fn | () -> Console {
Console
}
}
/// Print a single stats line.
fn fmt_line(key: &str, value: &f64) {
println!(" {}: {}", key, value)
}
impl Backend for Console {
fn flush_buckets(&mut self, buckets: &Buckets) {
let now = time::get_time();
println!("Flushing metrics: {}", time::at(n... | new | identifier_name |
messageevent.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::MessageEve... | (&self, _cx: *mut JSContext) -> JSVal {
self.data.get()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DO... | Data | identifier_name |
messageevent.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::MessageEve... |
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DOMString {
self.lastEventId.clone()
}
} | } | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.