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 |
|---|---|---|---|---|
import.rs | // Copyright (c) 2016 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... | {
ui.begin("Importing ring key from standard input")?;
let (pair, pair_type) = SymKey::write_file_from_str(content, cache)?;
ui.end(format!(
"Imported {} ring key {}.",
&pair_type,
&pair.name_with_rev()
))?;
Ok(())
} | identifier_body | |
import.rs | // Copyright (c) 2016 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... | ))?;
Ok(())
} | &pair_type,
&pair.name_with_rev() | random_line_split |
import.rs | // Copyright (c) 2016 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... | (ui: &mut UI, content: &str, cache: &Path) -> Result<()> {
ui.begin("Importing ring key from standard input")?;
let (pair, pair_type) = SymKey::write_file_from_str(content, cache)?;
ui.end(format!(
"Imported {} ring key {}.",
&pair_type,
&pair.name_with_rev()
))?;
Ok(())
}
| start | identifier_name |
editor.rs | use std::env;
use std::os;
use std::process::{Command,Stdio};
use rand::Rng;
use rand;
use std::io::{Read,Write,BufReader,BufRead};
use std::fs;
use std::path::{Path,PathBuf};
use std::fs::File;
use super::Note;
use super::util;
use std::io::Result;
pub fn edit_note(note: &Note) -> Result<Note> {
let editor = get_... | {
let mut reader = BufReader::new(fp);
let mut lines = reader.lines();
let name = lines.nth(0_usize).unwrap().unwrap();
let mut content = String::new();
for line in lines.skip(1_usize) {
content.push_str(&line.unwrap());
content.push_str("\n");
}
Ok(Note::new(None, &name, &... | identifier_body | |
editor.rs | use std::env;
use std::os;
use std::process::{Command,Stdio};
use rand::Rng;
use rand;
use std::io::{Read,Write,BufReader,BufRead};
use std::fs;
use std::path::{Path,PathBuf};
use std::fs::File;
use super::Note;
use super::util;
use std::io::Result;
pub fn | (note: &Note) -> Result<Note> {
let editor = get_editor(); // is "vi"
println!("Have the editor as {}", editor);
let path = tmp_file_path();
println!("Have the path as {:?}", path);
{
let mut fp = try!(File::create(&path));
try!(fp.write_all(note.as_markdown().as_bytes()));
}
... | edit_note | identifier_name |
editor.rs | use std::env;
use std::os;
use std::process::{Command,Stdio};
use rand::Rng;
use rand;
use std::io::{Read,Write,BufReader,BufRead};
use std::fs;
use std::path::{Path,PathBuf};
use std::fs::File;
use super::Note;
use super::util;
use std::io::Result;
pub fn edit_note(note: &Note) -> Result<Note> {
let editor = get_... | ,
Err(_) => { },
}
}
match env::var("EDITOR") {
Ok(name) => { return name; },
Err(_) => { },
}
let mut default_editor = String::new();
default_editor.push_str("vi");
default_editor
}
fn tmp_file_path() -> PathBuf {
let mut rng = rand::thread_rng();
l... | { return name; } | conditional_block |
editor.rs | use std::env;
use std::os;
use std::process::{Command,Stdio};
use rand::Rng;
use rand;
use std::io::{Read,Write,BufReader,BufRead};
use std::fs;
use std::path::{Path,PathBuf};
use std::fs::File;
use super::Note;
use super::util;
use std::io::Result;
pub fn edit_note(note: &Note) -> Result<Note> {
let editor = get_... |
let name = lines.nth(0_usize).unwrap().unwrap();
let mut content = String::new();
for line in lines.skip(1_usize) {
content.push_str(&line.unwrap());
content.push_str("\n");
}
Ok(Note::new(None, &name, &content))
} |
fn parse_note(fp: &mut File) -> Result<Note> {
let mut reader = BufReader::new(fp);
let mut lines = reader.lines(); | random_line_split |
lib.rs | #[macro_use]
extern crate error_chain;
#[macro_use]
extern crate serde_derive;
extern crate xdg;
extern crate serde;
extern crate sodiumoxide;
extern crate rmp_serde;
use std::fs::File;
use std::collections::HashMap;
use serde::Deserialize;
use sodiumoxide::crypto::secretbox;
pub mod errors {
extern crate rmp... | (&mut self) -> Result<()> {
match self.key {
Some(_) => Err("Mine instance already has a key".to_owned())?,
None => {
let key = secretbox::gen_key();
self.key = Some(key);
Ok(())
}
}
}
pub fn save(&self) -> Resu... | generate_key | identifier_name |
lib.rs | #[macro_use]
extern crate error_chain;
#[macro_use]
extern crate serde_derive;
extern crate xdg;
extern crate serde;
extern crate sodiumoxide;
extern crate rmp_serde;
use std::fs::File;
use std::collections::HashMap;
use serde::Deserialize;
use sodiumoxide::crypto::secretbox;
pub mod errors {
extern crate rmp... |
}
| {
let key = self.key.as_ref().ok_or("no secret key available")?;
match secretbox::open(&ciphertext.ciphertext, &ciphertext.nonce, &key) {
Ok(plaintext) => Ok(plaintext),
Err(()) => Err("failed to decrypt".to_owned())?,
}
} | identifier_body |
lib.rs | #[macro_use]
extern crate error_chain;
#[macro_use]
extern crate serde_derive;
extern crate xdg;
extern crate serde;
extern crate sodiumoxide;
extern crate rmp_serde;
use std::fs::File;
use std::collections::HashMap;
use serde::Deserialize;
use sodiumoxide::crypto::secretbox;
pub mod errors {
extern crate rmp... | Some(_) => Err("Mine instance already has a key".to_owned())?,
None => {
let key = secretbox::gen_key();
self.key = Some(key);
Ok(())
}
}
}
pub fn save(&self) -> Result<()> {
let key_path = self.dirs
... |
pub fn generate_key(&mut self) -> Result<()> {
match self.key { | random_line_split |
displayarea.rs | use event::ChatEvent;
use std::collections::VecDeque;
use std::cell::{Cell, RefCell};
use termion::{self, cursor, clear};
pub struct DisplayArea {
messages: Messages,
to_be_displayed: Cell<usize>,
}
impl DisplayArea {
pub fn new() -> DisplayArea {
DisplayArea {
messages: Messages::wi... | }
pub fn update_display(&self) {
let messages = self.messages.storage.borrow();
let to_be_displayed = self.to_be_displayed.get();
for i in messages.len().saturating_sub(to_be_displayed).. messages.len() {
let message = &messages[i];
let (_, max_y) = termion::term... | }
pub fn self_message(&self, message: &str) {
self.add_message(format!("<> {}", message)); | random_line_split |
displayarea.rs | use event::ChatEvent;
use std::collections::VecDeque;
use std::cell::{Cell, RefCell};
use termion::{self, cursor, clear};
pub struct DisplayArea {
messages: Messages,
to_be_displayed: Cell<usize>,
}
impl DisplayArea {
pub fn new() -> DisplayArea {
DisplayArea {
messages: Messages::wi... | (max_len: usize) -> Messages {
Messages {
max_len: max_len,
storage: RefCell::new(VecDeque::with_capacity(100)),
}
}
fn add_message(&self, message: String) {
let mut storage = self.storage.borrow_mut();
while storage.len() >= self.max_len {
st... | with_max | identifier_name |
displayarea.rs | use event::ChatEvent;
use std::collections::VecDeque;
use std::cell::{Cell, RefCell};
use termion::{self, cursor, clear};
pub struct DisplayArea {
messages: Messages,
to_be_displayed: Cell<usize>,
}
impl DisplayArea {
pub fn new() -> DisplayArea {
DisplayArea {
messages: Messages::wi... |
pub fn update_display(&self) {
let messages = self.messages.storage.borrow();
let to_be_displayed = self.to_be_displayed.get();
for i in messages.len().saturating_sub(to_be_displayed).. messages.len() {
let message = &messages[i];
let (_, max_y) = termion::terminal_... | {
self.add_message(format!("<> {}", message));
} | identifier_body |
clock_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <lionel@svkt.org>
//
// 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/LICENS... | (_: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
node.materializer.set(Some(build_clock as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
}
fn build_clock(builder: &mut Builder,
cx: &mut ExtCtxt,
node: Rc<node::Node>) {
if!node.expect_attributes(cx, &[("source", n... | attach | identifier_name |
clock_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <lionel@svkt.org>
//
// 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/LICENS... |
fn build_clock(builder: &mut Builder,
cx: &mut ExtCtxt,
node: Rc<node::Node>) {
if!node.expect_attributes(cx, &[("source", node::StrAttribute)]) {
return;
}
let source = TokenString(node.get_string_attr("source").unwrap());
let use_pll = node.get_bool_attr("pll").un... | {
node.materializer.set(Some(build_clock as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
} | identifier_body |
clock_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <lionel@svkt.org>
//
// Licensed under the Apache License, Version 2.0 (the "License"); | //
// 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... | // 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 |
clock_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <lionel@svkt.org>
//
// 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/LICENS... |
let source = TokenString(node.get_string_attr("source").unwrap());
let use_pll = node.get_bool_attr("pll").unwrap_or(false);
let div = node.get_int_attr("div").unwrap_or(1);
let xtal = TokenString(node.get_string_attr("xtal")
.unwrap_or("X16_0MHz".to_string()));
let ex = ... | {
return;
} | conditional_block |
lib.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... | args: vec!(Literal(path_local!(i64))),
ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
None,
vec!(Box::new(Self_)),
true)),
... | generics: LifetimeBounds::empty(),
explicit_self: None, | random_line_split |
lib.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... | (reg: &mut Registry) {
reg.register_syntax_extension(
token::intern("derive_NumFromPrimitive"),
MultiDecorator(Box::new(expand_deriving_from_primitive)));
}
| plugin_registrar | identifier_name |
lib.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... | {
reg.register_syntax_extension(
token::intern("derive_NumFromPrimitive"),
MultiDecorator(Box::new(expand_deriving_from_primitive)));
} | identifier_body | |
lib.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... |
let span = variant.span;
// expr for `$n == $variant as $name`
let path = cx.path(span, vec![substr.type_ident, variant.node.name]);
let variant = cx.expr_path(path);
let ty = cx.ty_ident(span, cx.i... | {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
Inter... | conditional_block |
mdct.rs | extern crate num_complex;
use kiss_fft;
use mode;
use std;
fn pre_rotate(fft: &kiss_fft::KissFft, x: &[f32], y: &mut [f32]) |
fn post_rotate(y: &mut [f32]) {
let n = y.len();
for i in 0..(n / 2 + 1) / 2 {
let i0 = 2 * i;
let i1 = 2 * i + 1;
let i2 = n - 2 * i - 1;
let i3 = n - 2 * i - 2;
let theta = -std::f32::consts::PI * (i as f32 + 1.0 / 8.0) / n as f32;
let phi = std::f32::consts:... | {
let stride = 1 << fft.shift;
let n = y.len();
for i in 0..n / 2 {
y[2 * fft.bitrev[i]] = x[stride * 2 * i] * fft.trig[i] -
x[stride * (n - 1 - 2 * i)] * fft.trig[n / 2 + i];
y[2 * fft.bitrev[i] + 1] = x[stride * (n - 1 - 2 * i)] * fft.trig[i] +
... | identifier_body |
mdct.rs | extern crate num_complex;
use kiss_fft;
use mode;
use std;
fn pre_rotate(fft: &kiss_fft::KissFft, x: &[f32], y: &mut [f32]) {
let stride = 1 << fft.shift;
let n = y.len();
for i in 0..n / 2 {
y[2 * fft.bitrev[i]] = x[stride * 2 * i] * fft.trig[i] -
x[stride * (n - 1 ... | let complex = std::slice::from_raw_parts_mut((&mut y[120 / 2..]).as_mut_ptr() as
(*mut num_complex::Complex<f32>),
480 >> shift);
let fft = if shift == 0 { &mode.fft0 } else { &mode.fft3 };
pre_rotate(fft, x, &... | pub unsafe fn mdct_backward(mode: &mode::CeltMode, x: &[f32], y: &mut [f32], shift: usize) { | random_line_split |
mdct.rs | extern crate num_complex;
use kiss_fft;
use mode;
use std;
fn pre_rotate(fft: &kiss_fft::KissFft, x: &[f32], y: &mut [f32]) {
let stride = 1 << fft.shift;
let n = y.len();
for i in 0..n / 2 {
y[2 * fft.bitrev[i]] = x[stride * 2 * i] * fft.trig[i] -
x[stride * (n - 1 ... | ;
pre_rotate(fft, x, &mut y[120 / 2..120 / 2 + (960 >> shift)]);
kiss_fft::opus_fft(fft, complex, &mode.twiddles);
post_rotate(&mut y[120 / 2..120 / 2 + (960 >> shift)]);
mirror(&mut y[..120], &mode.window);
}
| { &mode.fft3 } | conditional_block |
mdct.rs | extern crate num_complex;
use kiss_fft;
use mode;
use std;
fn pre_rotate(fft: &kiss_fft::KissFft, x: &[f32], y: &mut [f32]) {
let stride = 1 << fft.shift;
let n = y.len();
for i in 0..n / 2 {
y[2 * fft.bitrev[i]] = x[stride * 2 * i] * fft.trig[i] -
x[stride * (n - 1 ... | (mode: &mode::CeltMode, x: &[f32], y: &mut [f32], shift: usize) {
let complex = std::slice::from_raw_parts_mut((&mut y[120 / 2..]).as_mut_ptr() as
(*mut num_complex::Complex<f32>),
480 >> shift);
let fft = if shift... | mdct_backward | identifier_name |
main.rs | //! this is the unoptimized version that performs all 100
//! passes, as per the original description of the problem
fn main() {
// states for the 100 doors
// uses a vector of booleans,
// where state==false means the door is closed
let mut doors = [false; 100];
solve(&mut doors);
for (idx, d... | () {
let mut doors = [false; 100];
solve(&mut doors);
// test that the doors with index corresponding to
// a perfect square are now open
for i in 1..11 {
assert!(doors[i * i - 1]);
}
}
| solution | identifier_name |
main.rs | //! this is the unoptimized version that performs all 100
//! passes, as per the original description of the problem
fn main() |
/// unoptimized solution for the 100 Doors problem,
/// performs all 100 passes and mutates the vector with
/// the states in place
fn solve(doors: &mut [bool]) {
for pass in 1..101 {
let mut p = pass;
while p <= 100 {
// flip the state of the door
doors[p - 1] =!doors[p - ... | {
// states for the 100 doors
// uses a vector of booleans,
// where state==false means the door is closed
let mut doors = [false; 100];
solve(&mut doors);
for (idx, door) in doors.iter().enumerate() {
println!("door {} open: {}", idx + 1, door);
}
} | identifier_body |
main.rs | //! this is the unoptimized version that performs all 100
//! passes, as per the original description of the problem
fn main() {
// states for the 100 doors
// uses a vector of booleans,
// where state==false means the door is closed
let mut doors = [false; 100]; | }
}
/// unoptimized solution for the 100 Doors problem,
/// performs all 100 passes and mutates the vector with
/// the states in place
fn solve(doors: &mut [bool]) {
for pass in 1..101 {
let mut p = pass;
while p <= 100 {
// flip the state of the door
doors[p - 1] =!do... | solve(&mut doors);
for (idx, door) in doors.iter().enumerate() {
println!("door {} open: {}", idx + 1, door); | random_line_split |
borrowed-struct.rs | // Copyright 2013-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... |
// gdb-command:print *unique_val_interior_ref_2
// gdb-check:$7 = 26.5
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print *stack_val_ref
// lldb-check:[...]$0 = SomeStruct { x: 10, y: 23.5 }
// lldb-command:print *stack_va... | // gdb-check:$6 = 13 | random_line_split |
borrowed-struct.rs | // Copyright 2013-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 | |
borrowed-struct.rs | // Copyright 2013-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... | {
x: int,
y: f64
}
fn main() {
let stack_val: SomeStruct = SomeStruct { x: 10, y: 23.5 };
let stack_val_ref: &SomeStruct = &stack_val;
let stack_val_interior_ref_1: &int = &stack_val.x;
let stack_val_interior_ref_2: &f64 = &stack_val.y;
let ref_to_unnamed: &SomeStruct = &SomeStruct { x: 11... | SomeStruct | identifier_name |
lib.rs | #[derive(PartialEq, Eq, Debug)]
struct Age(u8);
struct Person<'a> {
name: &'static str,
parent: Option<&'a Person<'a>>,
}
impl<'a> Person<'a> {
fn new(name: &'static str, parent: Option<&'a Person<'a>>) -> Person<'a> {
Person{name: name, parent: parent}
}
fn parents_name(&self) -> Option<... | &value[..5]
}
// This cannot be elided because Rust doesn't know to use lifetime of "a" or "b".
fn double_first_five<'a>(a: &'a String, b: &'a String) -> (&'a str, &'a str) {
(&a[..5], &b[..5])
}
// Output borrows generally must have an input value from which it can borrow. The exception is
// the static life... |
// This one can be elided.
fn first_five<'a>(value: &'a String) -> &'a str { | random_line_split |
lib.rs | #[derive(PartialEq, Eq, Debug)]
struct Age(u8);
struct Person<'a> {
name: &'static str,
parent: Option<&'a Person<'a>>,
}
impl<'a> Person<'a> {
fn new(name: &'static str, parent: Option<&'a Person<'a>>) -> Person<'a> {
Person{name: name, parent: parent}
}
fn parents_name(&self) -> Option<... |
}
// This one can be elided.
fn first_five<'a>(value: &'a String) -> &'a str {
&value[..5]
}
// This cannot be elided because Rust doesn't know to use lifetime of "a" or "b".
fn double_first_five<'a>(a: &'a String, b: &'a String) -> (&'a str, &'a str) {
(&a[..5], &b[..5])
}
// Output borrows generally must ... | {
self.parent.and_then(|p| Some(p.name))
} | identifier_body |
lib.rs | #[derive(PartialEq, Eq, Debug)]
struct Age(u8);
struct Person<'a> {
name: &'static str,
parent: Option<&'a Person<'a>>,
}
impl<'a> Person<'a> {
fn new(name: &'static str, parent: Option<&'a Person<'a>>) -> Person<'a> {
Person{name: name, parent: parent}
}
fn parents_name(&self) -> Option<... | () -> bool {
let a = &9;
{
let b = &9;
multi_lifetimes(a, b)
}
}
#[test]
fn it_works() {
let jane = Person::new("Jane", None);
let tom = Person::new("Tom", Some(&jane));
let name = "Andrew".to_owned();
let another = "Timothy".to_owned();
let a = 43;
let vec_ages = ... | multiple_lifetimes | identifier_name |
hex.rs | // Copyright 2013-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... | () {
assert_eq!("666f6f626172".from_hex().unwrap(),
b"foobar");
assert_eq!("666F6F626172".from_hex().unwrap(),
b"foobar");
}
#[test]
pub fn test_from_hex_odd_len() {
assert!("666".from_hex().is_err());
assert!("66 6".from_hex().is_err())... | test_from_hex_okay | identifier_name |
hex.rs | // Copyright 2013-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... |
#[test]
pub fn test_from_hex_ignores_whitespace() {
assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(),
b"foobar");
}
#[test]
pub fn test_to_hex_all_bytes() {
for i in range(0u, 256) {
assert_eq!([i as u8].to_hex(), format!("{:02x}", i as uint));
... | {
assert!("66y6".from_hex().is_err());
} | identifier_body |
hex.rs | // Copyright 2013-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 result_str = String::from_utf8(bytes).unwrap();
/// println!("{}", result_str);
/// }
/// ```
fn from_hex(&self) -> Result<Vec<u8>, FromHexError> {
// This may be an overestimate if there is any whitespace
let mut b = Vec::with_capacity(self.len() / 2);
let mu... | /// let bytes = hello_str.as_slice().from_hex().unwrap();
/// println!("{:?}", bytes); | random_line_split |
main.rs | // Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
}
}
let submit = start.elapsed();
// Swap buffers
self.window.swap_buffers().unwrap();
let swap = start.elapsed();
println!("total time:\t\t{0:4.2}ms", duration_to_ms(swap));
println!("\tsubmit:\t\t{0:4.2}ms", duration_to_ms(submit));
print... | {
let start = Instant::now();
// Clear the screen to black
unsafe {
self.gl.ClearColor(CLEAR_COLOR.0, CLEAR_COLOR.1, CLEAR_COLOR.2, CLEAR_COLOR.3);
self.gl.Clear(gl::COLOR_BUFFER_BIT);
}
for x in (-self.dimension) ..self.dimension {
f... | identifier_body |
main.rs | // Copyright 2014 The Gfx-rs Developers.
// | // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WA... | // Licensed under the Apache License, Version 2.0 (the "License"); | random_line_split |
main.rs | // Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
shader
}
};
let window = builder.build().unwrap();
unsafe { window.make_current().unwrap() };
let gl = Gl::load_with(|s| window.get_proc_address(s) as *const _);
// Create GLSL shaders
let vs = compile_shader(&gl, VERTEX_SRC, gl::VER... | {
let mut len: GLint = 0;
gl.GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);
// allocate a buffer of size (len - 1) to skip the trailing null character
let mut buf: Vec<u8> = repeat(0u8).take((len as usize).saturating_sub(1)).collect()... | conditional_block |
main.rs | // Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (builder: glutin::WindowBuilder, dimension: i16) -> Self {
use gfx::traits::FactoryExt;
let (window, device, mut factory, main_color, _) =
gfx_window_glutin::init::<ColorFormat, DepthStencil>(builder);
let encoder: gfx::Encoder<_,_> = factory.create_command_buffer().into();
... | new | identifier_name |
primary_test.rs | extern crate expector;
use expector::prelude::*;
#[test]
fn equality_matcher_matches_things_that_are_equal() {
#[derive(PartialEq)]
struct Foo(i32);
expect(1).to(eq(1));
expect(2).to(eq(2));
expect(true).to(eq(true));
expect(Some(1)).to(eq(Some(1)));
expect(None::<i32>).to(eq(None));
e... | } | random_line_split | |
primary_test.rs | extern crate expector;
use expector::prelude::*;
#[test]
fn equality_matcher_matches_things_that_are_equal() {
#[derive(PartialEq)]
struct Foo(i32);
expect(1).to(eq(1));
expect(2).to(eq(2));
expect(true).to(eq(true));
expect(Some(1)).to(eq(Some(1)));
expect(None::<i32>).to(eq(None));
e... |
#[test]
#[should_panic]
fn be_an_empty_vec_fails_when_vecs_are_not_empty() {
expect(vec![1]).to(be_an_empty_vector())
}
| {
expect(Vec::<i32>::new()).to(be_an_empty_vector());
expect(Vec::<String>::new()).to(be_an_empty_vector());
} | identifier_body |
primary_test.rs | extern crate expector;
use expector::prelude::*;
#[test]
fn equality_matcher_matches_things_that_are_equal() {
#[derive(PartialEq)]
struct | (i32);
expect(1).to(eq(1));
expect(2).to(eq(2));
expect(true).to(eq(true));
expect(Some(1)).to(eq(Some(1)));
expect(None::<i32>).to(eq(None));
expect(Foo(2)).to(eq(Foo(2)));
}
#[test]
#[should_panic]
fn eq_matcher_fails_when_things_are_not_equal() {
expect(1).to(eq(2));
}
#[test]
fn be_an... | Foo | identifier_name |
strong.rs | use std::fmt;
use std::mem;
use std::ops::Deref;
use crate::runtime::{Object, self};
use super::WeakPtr;
/// A pointer that strongly references an object, ensuring it won't be deallocated.
pub struct StrongPtr(*mut Object);
impl StrongPtr {
/// Constructs a `StrongPtr` to a newly created object that already has ... | unsafe {
runtime::objc_autorelease(ptr);
}
ptr
}
/// Returns a `WeakPtr` to self.
pub fn weak(&self) -> WeakPtr {
unsafe { WeakPtr::new(self.0) }
}
}
impl Drop for StrongPtr {
fn drop(&mut self) {
unsafe {
runtime::objc_release(self.0... | random_line_split | |
strong.rs | use std::fmt;
use std::mem;
use std::ops::Deref;
use crate::runtime::{Object, self};
use super::WeakPtr;
/// A pointer that strongly references an object, ensuring it won't be deallocated.
pub struct StrongPtr(*mut Object);
impl StrongPtr {
/// Constructs a `StrongPtr` to a newly created object that already has ... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&self.0, f)
}
}
| fmt | identifier_name |
strong.rs | use std::fmt;
use std::mem;
use std::ops::Deref;
use crate::runtime::{Object, self};
use super::WeakPtr;
/// A pointer that strongly references an object, ensuring it won't be deallocated.
pub struct StrongPtr(*mut Object);
impl StrongPtr {
/// Constructs a `StrongPtr` to a newly created object that already has ... |
}
impl Deref for StrongPtr {
type Target = *mut Object;
fn deref(&self) -> &*mut Object {
&self.0
}
}
impl fmt::Pointer for StrongPtr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&self.0, f)
}
}
| {
unsafe {
StrongPtr::retain(self.0)
}
} | identifier_body |
crypto.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CryptoBinding;
use dom::bindings::codeg... |
Ok(NonNull::new_unchecked(input))
}
}
fn is_integer_buffer(array_type: Type) -> bool {
match array_type {
Type::Uint8 |
Type::Uint8Clamped |
Type::Int8 |
Type::Uint16 |
Type::Int16 |
Type::Uint32 |
Type::Int32 => true,
_ => false,
}
... | {
assert!(!input.is_null());
typedarray!(in(_cx) let mut array_buffer_view: ArrayBufferView = input);
let (array_type, mut data) = match array_buffer_view.as_mut() {
Ok(x) => (x.get_array_type(), x.as_mut_slice()),
Err(_) => {
return Err(Error::Type("Argum... | identifier_body |
crypto.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CryptoBinding;
use dom::bindings::codeg... | let (array_type, mut data) = match array_buffer_view.as_mut() {
Ok(x) => (x.get_array_type(), x.as_mut_slice()),
Err(_) => {
return Err(Error::Type("Argument to Crypto.getRandomValues is not an ArrayBufferView"
.to_owned()));
... | typedarray!(in(_cx) let mut array_buffer_view: ArrayBufferView = input); | random_line_split |
crypto.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CryptoBinding;
use dom::bindings::codeg... |
if data.len() > 65536 {
return Err(Error::QuotaExceeded);
}
self.rng.borrow_mut().fill_bytes(&mut data);
Ok(NonNull::new_unchecked(input))
}
}
fn is_integer_buffer(array_type: Type) -> bool {
match array_type {
Type::Uint8 |
Type::Uint8Clamped |
... | {
return Err(Error::TypeMismatch);
} | conditional_block |
crypto.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CryptoBinding;
use dom::bindings::codeg... | (global: &GlobalScope) -> DomRoot<Crypto> {
reflect_dom_object(Box::new(Crypto::new_inherited()), global, CryptoBinding::Wrap)
}
}
impl CryptoMethods for Crypto {
#[allow(unsafe_code)]
// https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues
unsafe f... | new | identifier_name |
headless.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 compositing::*;
use geom::size::Size2D;
use servo_msg::constellation_msg::{ConstellationChan, ExitMsg, Resize... | }
fn handle_message(&self, constellation_chan: ConstellationChan) {
loop {
match self.port.recv() {
Exit(chan) => {
debug!("shutting down the constellation");
let ConstellationChan(ref con_chan) = constellation_chan;
... | {
let compositor = NullCompositor::new(port);
// Tell the constellation about the initial fake size.
{
let ConstellationChan(ref chan) = constellation_chan;
chan.send(ResizedWindowMsg(Size2D(640u, 480u)));
}
compositor.handle_message(constellation_chan);
... | identifier_body |
headless.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 compositing::*;
use geom::size::Size2D;
use servo_msg::constellation_msg::{ConstellationChan, ExitMsg, Resize... | (port: Port<Msg>,
constellation_chan: ConstellationChan,
profiler_chan: ProfilerChan) {
let compositor = NullCompositor::new(port);
// Tell the constellation about the initial fake size.
{
let ConstellationChan(ref chan) = constellation_chan;
... | create | identifier_name |
headless.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 compositing::*;
use geom::size::Size2D;
use servo_msg::constellation_msg::{ConstellationChan, ExitMsg, Resize... |
SetIds(_, response_chan, _) => {
response_chan.send(());
}
// Explicitly list ignored messages so that when we add a new one,
// we'll notice and think about whether it needs a response, like
// SetIds.
... | }
GetGraphicsMetadata(chan) => {
chan.send(None);
} | random_line_split |
font_context.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 freetype::freetype::FT_Add_Default_Modules;
use freetype::freetype::FT_Done_Library;
use freetype::freetype::F... |
FT_Add_Default_Modules(ctx);
FontContextHandle {
ctx: Rc::new(FreeTypeLibraryHandle { ctx: ctx, mem: mem, user: user }),
}
}
}
}
| { panic!("Unable to initialize FreeType library"); } | conditional_block |
font_context.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 freetype::freetype::FT_Add_Default_Modules;
use freetype::freetype::FT_Done_Library;
use freetype::freetype::F... | {
// WARNING: FreeTypeLibraryHandle contains raw pointers, is clonable, and also implements
// `Drop`. This field needs to be Rc<> to make sure that the `drop` function is only called
// once, otherwise we'll get crashes. Yuk.
pub ctx: Rc<FreeTypeLibraryHandle>,
}
impl MallocSizeOf for FontContextHand... | FontContextHandle | identifier_name |
font_context.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 freetype::freetype::FT_Add_Default_Modules;
use freetype::freetype::FT_Done_Library;
use freetype::freetype::F... | use servo_allocator::libc_compat::{malloc, realloc, free};
use servo_allocator::usable_size;
use std::os::raw::{c_long, c_void};
use std::ptr;
use std::rc::Rc;
// We pass a |User| struct -- via an opaque |void*| -- to FreeType each time a new instance is
// created. FreeType passes it back to the ft_alloc/ft_realloc/f... | use freetype::freetype::FT_New_Library;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; | random_line_split |
font_context.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 freetype::freetype::FT_Add_Default_Modules;
use freetype::freetype::FT_Done_Library;
use freetype::freetype::F... |
}
#[derive(Clone, Debug)]
pub struct FontContextHandle {
// WARNING: FreeTypeLibraryHandle contains raw pointers, is clonable, and also implements
// `Drop`. This field needs to be Rc<> to make sure that the `drop` function is only called
// once, otherwise we'll get crashes. Yuk.
pub ctx: Rc<FreeType... | {
unsafe {
(*self.user).size +
ops.malloc_size_of(self.ctx as *const _) +
ops.malloc_size_of(self.mem as *const _) +
ops.malloc_size_of(self.user as *const _)
}
} | identifier_body |
applayer.rs | /* Copyright (C) 2017-2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY... |
pub fn set(&mut self, bits: u32) {
self.flags = bits;
}
}
/// Export a function to get the DetectEngineState on a struct.
#[macro_export]
macro_rules!export_tx_get_detect_state {
($name:ident, $type:ty) => (
#[no_mangle]
pub extern "C" fn $name(tx: *mut std::os::raw::c_void)
... | {
self.flags
} | identifier_body |
applayer.rs | /* Copyright (C) 2017-2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY... | else {
Self::ok()
}
}
}
impl From<i32> for AppLayerResult {
fn from(v: i32) -> Self {
if v < 0 {
Self::err()
} else {
Self::ok()
}
}
}
/// Rust parser declaration
#[repr(C)]
pub struct RustParser {
/// Parser name.
pub name: ... | {
Self::err()
} | conditional_block |
applayer.rs | /* Copyright (C) 2017-2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY... | (v: bool) -> Self {
if v == false {
Self::err()
} else {
Self::ok()
}
}
}
impl From<i32> for AppLayerResult {
fn from(v: i32) -> Self {
if v < 0 {
Self::err()
} else {
Self::ok()
}
}
}
/// Rust parser declarati... | from | identifier_name |
applayer.rs | /* Copyright (C) 2017-2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY... | pub type LocalStorageNewFn = extern "C" fn () -> *mut c_void;
pub type LocalStorageFreeFn = extern "C" fn (*mut c_void);
pub type GetFilesFn = extern "C" fn (*mut c_void, u8) -> *mut FileContainer;
pub type GetTxIteratorFn = extern "C" fn (ipproto: u8, alproto: AppProto,
... | pub type GetEventInfoFn = extern "C" fn (*const c_char, *mut c_int, *mut AppLayerEventType) -> c_int;
pub type GetEventInfoByIdFn = extern "C" fn (c_int, *mut *const c_char, *mut AppLayerEventType) -> i8;
pub type GetEventsFn = extern "C" fn (*mut c_void) -> *mut AppLayerDecoderEvents; | random_line_split |
tile.rs | use std::default::Default;
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
//the indexes inside the enums are for flexibility. You can create an extra array for different
//types of particular tile type and index it with the index. For example you could have an array of
//different wall texture variations and have y... | }
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum Faction {
Faction(usize),
Neutral,
Void,
}
impl Default for Faction {
fn default() -> Faction {
Faction::Void
}
} | Tile::Void(0)
}
| random_line_split |
tile.rs | use std::default::Default;
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
//the indexes inside the enums are for flexibility. You can create an extra array for different
//types of particular tile type and index it with the index. For example you could have an array of
//different wall texture variations and have y... | () -> Tile {
Tile::Void(0)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum Faction {
Faction(usize),
Neutral,
Void,
}
impl Default for Faction {
fn default() -> Faction {
Faction::Void
}
}
| default | identifier_name |
mod.rs | pub use self::encode::{EncodableResolve, EncodableDependency, EncodablePackageId};
pub use self::encode::Metadata;
mod encode;
/// Represents a fully resolved package dependency graph. Each node in the graph
/// is a package and edges represent dependencies between packages.
///
/// Each instance of `Resolve` also un... | <'a>(cx: Box<Context>,
registry: &mut Registry,
parent: &Summary,
platform: Option<&'a str>,
mut deps: slice::Iter<'a, DepInfo>,
cur: usize,
finished: &mut FnMut(Box<Context>, &mut Registry) -> ... | activate_deps | identifier_name |
mod.rs | pub use self::encode::{EncodableResolve, EncodableDependency, EncodablePackageId};
pub use self::encode::Metadata;
mod encode;
/// Represents a fully resolved package dependency graph. Each node in the graph
/// is a package and edges represent dependencies between packages.
///
/// Each instance of `Resolve` also un... |
}
match method {
Method::Everything |
Method::Required { uses_default_features: true,.. } => {
if s.features().get("default").is_some() {
try!(add_feature(s, "default", &mut deps, &mut used,
&mut visited));
}
}
... | {
for feat in requested_features.iter() {
try!(add_feature(s, feat, &mut deps, &mut used, &mut visited));
}
} | conditional_block |
mod.rs | msg.push_str(&format!("\n {}",
PackageIdSpec::from_package_id(*id)));
}
}
}
}
pub fn features(&self, pkg: &PackageId) -> Option<&HashSet<String>> {
self.features.get(pkg)
}
}
impl fmt::Debug for Resolve {
fn ... | Method::Everything => true,
Method::Required { dev_deps, .. } => dev_deps,
};
// First, filter by dev-dependencies | random_line_split | |
mod.rs | pub use self::encode::{EncodableResolve, EncodableDependency, EncodablePackageId};
pub use self::encode::Metadata;
mod encode;
/// Represents a fully resolved package dependency graph. Each node in the graph
/// is a package and edges represent dependencies between packages.
///
/// Each instance of `Resolve` also un... |
}
impl fmt::Debug for Resolve {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "graph: {:?}\n", self.graph));
try!(write!(fmt, "\nfeatures: {{\n"));
for (pkg, features) in &self.features {
try!(write!(fmt, " {}: {:?}\n", pkg, features));
}
... | {
self.features.get(pkg)
} | identifier_body |
link-assoc-const.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// |
#![crate_name = "foo"]
// @has foo/index.html '//a[@href="../foo/foo/constant.FIRSTCONST.html"]' 'foo::FIRSTCONST'
// @has foo/index.html '//a[@href="../foo/struct.Bar.html#associatedconstant.CONST"]' 'Bar::CONST'
//! We have here [`foo::FIRSTCONST`] and [`Bar::CONST`].
pub mod foo {
pub const FIRSTCONST: u32 =... | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
link-assoc-const.rs | // Copyright 2018 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 Bar {
pub const CONST: u32 = 42;
}
| Bar | identifier_name |
symbolic_color.rs | // This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT
use StyleProperties;
use ffi;
use gdk;
use glib::translate::*;
use std::fmt;
glib_wrapper! {
pub struct SymbolicColor(Shared<ffi::GtkSymbolicColor>);
match fn {
ref => |ptr| ffi::gtk_symbolic_color_ref(ptr),
u... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_string())
}
}
| fmt | identifier_name |
symbolic_color.rs | // This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT
use StyleProperties;
use ffi;
use gdk;
use glib::translate::*;
use std::fmt;
glib_wrapper! {
pub struct SymbolicColor(Shared<ffi::GtkSymbolicColor>);
match fn {
ref => |ptr| ffi::gtk_symbolic_color_ref(ptr),
u... |
}
}
fn to_string(&self) -> String {
unsafe {
from_glib_full(ffi::gtk_symbolic_color_to_string(self.to_glib_none().0))
}
}
}
impl fmt::Display for SymbolicColor {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_st... | { None } | conditional_block |
symbolic_color.rs | // This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT
use StyleProperties;
use ffi;
use gdk;
use glib::translate::*;
use std::fmt;
glib_wrapper! {
pub struct SymbolicColor(Shared<ffi::GtkSymbolicColor>);
match fn {
ref => |ptr| ffi::gtk_symbolic_color_ref(ptr),
u... |
}
| {
write!(f, "{}", self.to_string())
} | identifier_body |
symbolic_color.rs | // This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT
use StyleProperties;
use ffi;
use gdk;
use glib::translate::*;
use std::fmt;
glib_wrapper! {
pub struct SymbolicColor(Shared<ffi::GtkSymbolicColor>);
match fn {
ref => |ptr| ffi::gtk_symbolic_color_ref(ptr),
u... | }
}
pub fn resolve(&self, props: Option<&StyleProperties>) -> Option<gdk::RGBA> {
unsafe {
let mut resolved_color = gdk::RGBA::uninitialized();
let ret = from_glib(ffi::gtk_symbolic_color_resolve(self.to_glib_none().0, props.to_glib_none().0, resolved_color.to_glib_none_... |
pub fn new_win32(theme_class: &str, id: i32) -> SymbolicColor {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gtk_symbolic_color_new_win32(theme_class.to_glib_none().0, id)) | random_line_split |
util.rs | // Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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/l... | {
format!("Error: {:?}", error)
} | identifier_body | |
util.rs | // Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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/l... | use serenity::Result as SerenityResult;
use serenity::model::Message;
use serenity::utils::Colour;
use std::collections::HashMap;
use std::error::Error;
use std::fmt::Debug;
use std::hash::Hash;
/// Takes a `Vec<T>` and splits it into a head and a tail.
#[inline]
pub fn split_list<T>(list: Vec<T>) -> (Option<T>, Vec<T... | random_line_split | |
util.rs | // Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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/l... | <T>(list: Vec<T>) -> (Option<T>, Vec<T>) {
let mut iter = list.into_iter();
let head = iter.next();
let tail = iter.collect();
(head, tail)
}
/// Checks that a message successfully sent; if not, then logs why.
#[inline]
pub fn check_msg(result: SerenityResult<Message>) {
if let Err(why) = result {... | split_list | identifier_name |
util.rs | // Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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/l... | ;
let minutes = if hours > 0 {
duration.num_minutes() % 60
} else {
duration.num_minutes()
};
let seconds = if minutes > 0 {
duration.num_seconds() % 60
} else {
duration.num_seconds()
};
format!(
"{}d {}h {}m {}s",
days,
hours,
... | {
duration.num_hours()
} | conditional_block |
lib.rs | extern crate libc;
#[allow(non_camel_case_types)]
mod minilzo; | pub const LZO1X_MEM_COMPRESS : usize = LZO1X_1_MEM_COMPRESS;
pub const LZO_E_OK : i32 = 0;
pub const LZO_E_ERROR : i32 = -1;
pub const LZO_E_OUT_OF_MEMORY : i32 = -2; /* [lzo_alloc_func_t failure] */
pub const LZO_E_NOT_COMPRESSIBLE : i32 = -3; /* [not used right now] */
pub c... |
/* Manually added */
pub const LZO1X_1_MEM_COMPRESS : usize = (16384 * 8); | random_line_split |
build.rs | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
use std::path::PathBuf;
const PROTOS: &'static [&'static str] = &[
"grr/grr/proto/grr_response_proto/semantic.proto",
"grr/grr/prot... | }
| {
prost_build::compile_protos(&PROTOS, &INCLUDES)
.expect("failed to compile proto files");
// There is a problem with one enum generated by PROST!: it's values use
// name mangling, but it's default value does not. This is likely a bug in
// PROST! itself, but for now we hack around it by repl... | identifier_body |
build.rs | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
use std::path::PathBuf;
const PROTOS: &'static [&'static str] = &[
"grr/grr/proto/grr_response_proto/semantic.proto",
"grr/grr/prot... | () {
prost_build::compile_protos(&PROTOS, &INCLUDES)
.expect("failed to compile proto files");
// There is a problem with one enum generated by PROST!: it's values use
// name mangling, but it's default value does not. This is likely a bug in
// PROST! itself, but for now we hack around it by re... | main | identifier_name |
build.rs | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
|
const PROTOS: &'static [&'static str] = &[
"grr/grr/proto/grr_response_proto/semantic.proto",
"grr/grr/proto/grr_response_proto/sysinfo.proto",
"grr/grr/proto/grr_response_proto/knowledge_base.proto",
"grr/grr/proto/grr_response_proto/jobs.proto",
"grr/grr/proto/grr_response_proto/timeline.proto",
... | use std::path::PathBuf; | random_line_split |
mod_is_reduced.rs | use malachite_base::num::arithmetic::traits::ModIsReduced;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::runner::Runner;
use malachite_nz_test_util::bench::bucketers::pair_1_natural_bit_bucketer;... |
fn benchmark_natural_mod_is_reduced(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) {
run_benchmark(
"Natural.mod_is_reduced(&Natural)",
BenchmarkType::Single,
natural_pair_gen_var_5().get(gm, &config),
gm.name(),
limit,
file_name,
&pair_1_nat... | {
for (n, m) in natural_pair_gen_var_5().get(gm, &config).take(limit) {
if n.mod_is_reduced(&m) {
println!("{} is reduced mod {}", n, m);
} else {
println!("{} is not reduced mod {}", n, m);
}
}
} | identifier_body |
mod_is_reduced.rs | use malachite_base::num::arithmetic::traits::ModIsReduced;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::runner::Runner;
use malachite_nz_test_util::bench::bucketers::pair_1_natural_bit_bucketer;... | (gm: GenMode, config: GenConfig, limit: usize) {
for (n, m) in natural_pair_gen_var_5().get(gm, &config).take(limit) {
if n.mod_is_reduced(&m) {
println!("{} is reduced mod {}", n, m);
} else {
println!("{} is not reduced mod {}", n, m);
}
}
}
fn benchmark_natura... | demo_natural_mod_is_reduced | identifier_name |
mod_is_reduced.rs | use malachite_base::num::arithmetic::traits::ModIsReduced; | use malachite_nz_test_util::bench::bucketers::pair_1_natural_bit_bucketer;
use malachite_nz_test_util::generators::natural_pair_gen_var_5;
pub(crate) fn register(runner: &mut Runner) {
register_demo!(runner, demo_natural_mod_is_reduced);
register_bench!(runner, benchmark_natural_mod_is_reduced);
}
fn demo_na... | use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::runner::Runner; | random_line_split |
mod_is_reduced.rs | use malachite_base::num::arithmetic::traits::ModIsReduced;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::runner::Runner;
use malachite_nz_test_util::bench::bucketers::pair_1_natural_bit_bucketer;... | else {
println!("{} is not reduced mod {}", n, m);
}
}
}
fn benchmark_natural_mod_is_reduced(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) {
run_benchmark(
"Natural.mod_is_reduced(&Natural)",
BenchmarkType::Single,
natural_pair_gen_var_5().get(gm, &... | {
println!("{} is reduced mod {}", n, m);
} | conditional_block |
repeat.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | let mark = context.next_mark_name();
continuation.map_success(|success, failure|
if self.cardinality_min > 0 {
let counter = context.next_counter_name();
let cardinality_min = self.cardinality_min;
parse_quote!(
{
let mut #mark = state.mark();
let ... | random_line_split | |
repeat.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | <'a>(&self, context: &mut Context<'a>,
continuation: Continuation) -> syn::Expr
{
let ty: syn::Type = parse_quote!(Vec<_>);
let (body, result_var) = context.value_constructor(
self.expr_idx,
ty,
RepeatCompiler::value_constructor
);
let repeat_expr = self.compile(context, continua... | compile_parser | identifier_name |
repeat.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... |
}
impl CompileExpr for RepeatCompiler
{
fn compile_expr<'a>(&self, context: &mut Context<'a>,
continuation: Continuation) -> syn::Expr
{
match self.compiler_kind {
CompilerKind::Recognizer => self.compile_recognizer(context, continuation),
CompilerKind::Parser => self.compile_parser(context, c... | {
let ty: syn::Type = parse_quote!(Vec<_>);
let (body, result_var) = context.value_constructor(
self.expr_idx,
ty,
RepeatCompiler::value_constructor
);
let repeat_expr = self.compile(context, continuation, body);
parse_quote!({
let mut #result_var = vec![];
#repeat_expr... | identifier_body |
synth.rs | use audiobuffer::*;
use processblock::ProcessBlock;
use port::Port;
use jack::prelude::RawMidi;
use synthconfig::SynthConfig;
#[derive(Debug, Clone, Copy)]
pub struct BlockId(usize);
#[derive(Debug, Clone)]
pub struct Connection{
buffer_id: usize,
block: BlockId,
port: Port,
}
impl Connection{
pub fn... | {
block: Box<ProcessBlock>,
inputs: Vec<Connection>, // connection to an output
outputs: Vec<usize>, // id of this output
}
#[derive(Debug)]
pub struct Synth{
blocks: Vec<ProcessBlockAtSynth>,
output: Connection,
buffer_size: usize,
output_port_count: usize,
// only between prework and... | ProcessBlockAtSynth | identifier_name |
synth.rs | use audiobuffer::*;
use processblock::ProcessBlock;
use port::Port;
use jack::prelude::RawMidi;
use synthconfig::SynthConfig;
#[derive(Debug, Clone, Copy)]
pub struct BlockId(usize);
#[derive(Debug, Clone)]
pub struct Connection{
buffer_id: usize,
block: BlockId,
port: Port,
}
impl Connection{
pub fn... | ,
Some(block) =>
match block.outputs.get(port_id.nr) {
None =>
{
println!("Invalid output id {:?} at {:?} ({:?})", port_id, block_id, block.block);
0
},
... | {
println!("Invalid block id {:?}", block_id);
0
} | conditional_block |
synth.rs | use audiobuffer::*;
use processblock::ProcessBlock;
use port::Port;
use jack::prelude::RawMidi;
use synthconfig::SynthConfig;
#[derive(Debug, Clone, Copy)]
pub struct BlockId(usize);
#[derive(Debug, Clone)]
pub struct Connection{
buffer_id: usize,
block: BlockId,
port: Port,
}
impl Connection{
pub fn... | //println!("{}", Colour::Green.paint(format!("## {:?} ({:?}) <({:?}) <({:?})", block, block_id, cblock.inputs, cblock.outputs)));
for port_in in 0..block.input_count() {
let ipn = self.get_input_port_number(BlockId(block_id), Port::new(port_in));
l... | let pb = *rpb;
// loan audio buffers from the main list of audiobuffers
{
let cblock = &self.blocks[pb];
let block = &cblock.block; | random_line_split |
dxgi1_5.rs | // Copyright © 2017 winapi-rs developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modi... | 0x7632e1f5, 0xee65, 0x4dca, 0x87, 0xfd, 0x84, 0xcd, 0x75, 0xf8, 0x83, 0x8d} | random_line_split | |
issue-17476.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
// @has issue_17476/struct.Foo.html \
// '//*[@href="http://example.com/issue_17476/trait.Foo.html#method.foo"]' \
// 'foo'
impl issue_17476::Foo for Foo {}
| Foo | identifier_name |
issue-17476.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:issue-17476.rs
// ignore-android
extern crate issue_17476;
pub struct Foo... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
redundant_clone.rs | // run-rustfix
// rustfix-only-machine-applicable
#![allow(clippy::implicit_clone)]
use std::ffi::OsString;
use std::path::Path;
fn main() {
let _s = ["lorem", "ipsum"].join(" ").to_string();
let s = String::from("foo");
let _s = s.clone();
let s = String::from("foo");
let _s = s.to_string();
... | () -> String {
let s = TypeWithDrop { x: String::new() };
s.x.clone() // removing this `clone()` summons E0509
}
fn borrower_propagation() {
let s = String::new();
let t = String::new();
{
fn b() -> bool {
unimplemented!()
}
let _u = if b() { &s } else { &t };
... | cannot_move_from_type_with_drop | identifier_name |
redundant_clone.rs | // run-rustfix
// rustfix-only-machine-applicable
#![allow(clippy::implicit_clone)]
use std::ffi::OsString;
use std::path::Path;
fn main() {
let _s = ["lorem", "ipsum"].join(" ").to_string();
let s = String::from("foo");
let _s = s.clone();
let s = String::from("foo");
let _s = s.to_string();
... | let _s = Path::new("/a/b/").join("c").to_path_buf();
let _s = OsString::new().to_owned();
let _s = OsString::new().to_os_string();
// Check that lint level works
#[allow(clippy::redundant_clone)]
let _s = String::new().to_string();
let tup = (String::from("foo"),);
let _t = tup.0.clo... | random_line_split | |
redundant_clone.rs | // run-rustfix
// rustfix-only-machine-applicable
#![allow(clippy::implicit_clone)]
use std::ffi::OsString;
use std::path::Path;
fn main() {
let _s = ["lorem", "ipsum"].join(" ").to_string();
let s = String::from("foo");
let _s = s.clone();
let s = String::from("foo");
let _s = s.to_string();
... | ;
// ok; `s` and `t` are possibly borrowed
let _s = s.clone();
let _t = t.clone();
}
{
let _u = || s.len();
let _v = [&t; 32];
let _s = s.clone(); // ok
let _t = t.clone(); // ok
}
{
let _u = {
let u = Some(&s);
l... | { &t } | conditional_block |
redundant_clone.rs | // run-rustfix
// rustfix-only-machine-applicable
#![allow(clippy::implicit_clone)]
use std::ffi::OsString;
use std::path::Path;
fn main() {
let _s = ["lorem", "ipsum"].join(" ").to_string();
let s = String::from("foo");
let _s = s.clone();
let s = String::from("foo");
let _s = s.to_string();
... | x.0.clone().chars().for_each(|_| x.m());
}
fn hashmap_neg() {
// issue 5707
use std::collections::HashMap;
use std::path::PathBuf;
let p = PathBuf::from("/");
let mut h: HashMap<&str, &str> = HashMap::new();
h.insert("orig-p", p.to_str().unwrap());
let mut q = p.clone();
q.push(... | {
// issue #5973
let x = Some(String::new());
// ok, x is moved while the clone is in use.
assert_eq!(x.clone(), None, "not equal {}", x.unwrap());
// issue #5595
fn foo<F: Fn()>(_: &Alpha, _: F) {}
let x = Alpha;
// ok, data is moved while the clone is in use.
foo(&x.clone(), move ... | identifier_body |
mod.rs | use std::net::SocketAddr;
use filter::FilterDecision;
use message::initiate::InitiateMessage;
use message::protocol::Protocol;
use message::extensions::Extensions;
use filter::filters::Filters;
use bip_util::bt::{PeerId, InfoHash};
use futures::stream::Stream;
use futures::sink::Sink;
use futures::future::{self, Into... | <S> {
Initiate(S, InitiateMessage),
Complete(S, SocketAddr)
}
enum LoopError<D> {
Terminate,
Recoverable(D)
}
/// Create loop for feeding the handler with the items coming from the stream, and forwarding the result to the sink.
///
/// If the stream is used up, or an error is propogated from any of th... | HandshakeType | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.