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
network.rs
10; #[derive(Debug)] struct ErrorAction { retry_timeout: Duration, max_retries: usize, description: String, } impl ErrorAction { fn new(config: &NetworkConfiguration, description: String) -> Self { Self { retry_timeout: Duration::from_millis(config.tcp_connect_retry_timeout), ...
/// Drops the connection to a peer. The request can be optionally filtered by the connection ID /// in order to avoid issuing obsolete requests. /// /// # Return value /// /// Returns `true` if the connection with the peer was dropped. If the connection with the /// peer was not dropped (e...
{ self.peers.get(address).is_some() }
identifier_body
shortlex_strings_using_chars.rs
use itertools::Itertools; use malachite_base::chars::exhaustive::exhaustive_ascii_chars; use malachite_base::strings::exhaustive::shortlex_strings_using_chars;
let ss = shortlex_strings_using_chars(cs).take(20).collect_vec(); assert_eq!(ss.iter().map(String::as_str).collect_vec().as_slice(), out); } #[test] fn test_shortlex_strings_using_chars() { shortlex_strings_using_chars_helper(empty(), &[""]); shortlex_strings_using_chars_helper( once('a'), ...
use std::iter::{empty, once}; fn shortlex_strings_using_chars_helper<I: Clone + Iterator<Item = char>>(cs: I, out: &[&str]) {
random_line_split
shortlex_strings_using_chars.rs
use itertools::Itertools; use malachite_base::chars::exhaustive::exhaustive_ascii_chars; use malachite_base::strings::exhaustive::shortlex_strings_using_chars; use std::iter::{empty, once}; fn shortlex_strings_using_chars_helper<I: Clone + Iterator<Item = char>>(cs: I, out: &[&str])
#[test] fn test_shortlex_strings_using_chars() { shortlex_strings_using_chars_helper(empty(), &[""]); shortlex_strings_using_chars_helper( once('a'), &[ "", "a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", ...
{ let ss = shortlex_strings_using_chars(cs).take(20).collect_vec(); assert_eq!(ss.iter().map(String::as_str).collect_vec().as_slice(), out); }
identifier_body
shortlex_strings_using_chars.rs
use itertools::Itertools; use malachite_base::chars::exhaustive::exhaustive_ascii_chars; use malachite_base::strings::exhaustive::shortlex_strings_using_chars; use std::iter::{empty, once}; fn
<I: Clone + Iterator<Item = char>>(cs: I, out: &[&str]) { let ss = shortlex_strings_using_chars(cs).take(20).collect_vec(); assert_eq!(ss.iter().map(String::as_str).collect_vec().as_slice(), out); } #[test] fn test_shortlex_strings_using_chars() { shortlex_strings_using_chars_helper(empty(), &[""]); sh...
shortlex_strings_using_chars_helper
identifier_name
render.rs
use glfw_ffi::*; use nanovg; use std::os::raw::c_int; use std::ptr; #[repr(usize)] #[derive(PartialEq, Eq)] pub enum Fonts { Inter = 0, Vga8, Moderno, NumFonts, } pub struct RenderContext<'a> { window: *mut GLFWwindow, nvg: &'a nanovg::Context, fonts: [nanovg::Font<'a>; Fonts::NumFonts as...
pub fn size(&self) -> (f32, f32) { let (mut w, mut h) = (0i32, 0i32); unsafe { glfwGetWindowSize(self.window, &mut w as *mut _, &mut h as *mut _); } (w as f32, h as f32) } pub fn pixel_ratio(&self) -> f32 { unsafe { let mut fb_width: c_int =...
{ Self { window, nvg, fonts } }
identifier_body
render.rs
use glfw_ffi::*; use nanovg; use std::os::raw::c_int; use std::ptr; #[repr(usize)] #[derive(PartialEq, Eq)] pub enum Fonts { Inter = 0, Vga8, Moderno, NumFonts, } pub struct RenderContext<'a> { window: *mut GLFWwindow, nvg: &'a nanovg::Context, fonts: [nanovg::Font<'a>; Fonts::NumFonts as...
<F: FnOnce(nanovg::Frame)>(&self, f: F) { self.nvg.frame(self.size(), self.pixel_ratio(), f); } pub fn font(&self, id: Fonts) -> nanovg::Font<'a> { if id == Fonts::NumFonts { panic!("Tried to access font `Fonts::NumFonts`"); } self.fonts[id as usize] } }
frame
identifier_name
render.rs
use glfw_ffi::*; use nanovg; use std::os::raw::c_int; use std::ptr; #[repr(usize)] #[derive(PartialEq, Eq)] pub enum Fonts { Inter = 0,
NumFonts, } pub struct RenderContext<'a> { window: *mut GLFWwindow, nvg: &'a nanovg::Context, fonts: [nanovg::Font<'a>; Fonts::NumFonts as usize], } impl<'a> RenderContext<'a> { pub fn new( window: *mut GLFWwindow, nvg: &'a nanovg::Context, fonts: [nanovg::Font<'a>; Fonts::...
Vga8, Moderno,
random_line_split
render.rs
use glfw_ffi::*; use nanovg; use std::os::raw::c_int; use std::ptr; #[repr(usize)] #[derive(PartialEq, Eq)] pub enum Fonts { Inter = 0, Vga8, Moderno, NumFonts, } pub struct RenderContext<'a> { window: *mut GLFWwindow, nvg: &'a nanovg::Context, fonts: [nanovg::Font<'a>; Fonts::NumFonts as...
self.fonts[id as usize] } }
{ panic!("Tried to access font `Fonts::NumFonts`"); }
conditional_block
lib.rs
#![crate_name = "librespot"] #![cfg_attr(feature = "cargo-clippy", allow(unused_io_amount))] #[macro_use] extern crate error_chain; #[macro_use] extern crate futures; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate serde_json; #[macro_use] extern crate serde_derive; ex...
extern crate tremor as vorbis; #[cfg(feature = "alsa-backend")] extern crate alsa; #[cfg(feature = "portaudio")] extern crate portaudio; #[cfg(feature = "libpulse-sys")] extern crate libpulse_sys; #[macro_use] mod component; pub mod album_cover; pub mod apresolve; pub mod audio_backend; pub mod audio_decrypt; pub ...
random_line_split
autoref-intermediate-types-issue-3585.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = @3u; assert_eq!(x.foo(), ~"@3"); }
identifier_body
autoref-intermediate-types-issue-3585.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) -> ~str { fmt!("@%s", (**self).foo()) } } impl Foo for uint { fn foo(&self) -> ~str { fmt!("%u", *self) } } pub fn main() { let x = @3u; assert_eq!(x.foo(), ~"@3"); }
foo
identifier_name
autoref-intermediate-types-issue-3585.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn main() { let x = @3u; assert_eq!(x.foo(), ~"@3"); }
random_line_split
mod.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
/// Build a vector of requested size with key ID prefix pre-filled. fn create_output_prefix(size: usize, start_byte: u8, key_id: crate::KeyId) -> Vec<u8> { let mut prefix = Vec::with_capacity(size); prefix.push(start_byte); prefix.extend_from_slice(&key_id.to_be_bytes()); prefix }
{ match OutputPrefixType::from_i32(key.output_prefix_type) { Some(OutputPrefixType::Legacy) | Some(OutputPrefixType::Crunchy) => Ok( create_output_prefix(LEGACY_PREFIX_SIZE, LEGACY_START_BYTE, key.key_id), ), Some(OutputPrefixType::Tink) => Ok(create_output_prefix( TI...
identifier_body
mod.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
(size: usize, start_byte: u8, key_id: crate::KeyId) -> Vec<u8> { let mut prefix = Vec::with_capacity(size); prefix.push(start_byte); prefix.extend_from_slice(&key_id.to_be_bytes()); prefix }
create_output_prefix
identifier_name
mod.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
pub const LEGACY_START_BYTE: u8 = 0; /// Prefix size of Tink key types. /// The prefix starts with \x01 and followed by a 4-byte key id. pub const TINK_PREFIX_SIZE: usize = NON_RAW_PREFIX_SIZE; /// First byte of the prefix of Tink key types. pub const TINK_START_BYTE: u8 = 1; /// Prefix size of Raw key types. /// Raw...
/// First byte of the prefix of legacy key types.
random_line_split
frequency_status.rs
use rosrust::Duration; use rosrust_diagnostics::{FrequencyStatus, Level, Status, Task}; mod util; #[test] fn
() { let _roscore = util::run_roscore_for(util::Feature::FrequencyStatusTest); rosrust::init("frequency_status_test"); let fs = FrequencyStatus::builder() .window_size(2) .min_frequency(10.0) .max_frequency(20.0) .tolerance(0.5) .build(); fs.tick(); rosrust::slee...
frequency_status_test
identifier_name
frequency_status.rs
use rosrust::Duration; use rosrust_diagnostics::{FrequencyStatus, Level, Status, Task}; mod util; #[test] fn frequency_status_test() { let _roscore = util::run_roscore_for(util::Feature::FrequencyStatusTest); rosrust::init("frequency_status_test"); let fs = FrequencyStatus::builder() .window_size(...
); assert_eq!( fs.name(), "Frequency Status", "Name should be \"Frequency Status\"" ); }
assert_eq!(status4.level, Level::Error, "Freshly cleared should fail"); assert_eq!( status0.name, "", "Name should not be set by FrequencyStatus"
random_line_split
frequency_status.rs
use rosrust::Duration; use rosrust_diagnostics::{FrequencyStatus, Level, Status, Task}; mod util; #[test] fn frequency_status_test()
fs.tick(); let mut status2 = Status::default(); fs.run(&mut status2); rosrust::sleep(Duration::from_nanos(150_000_000)); fs.tick(); let mut status3 = Status::default(); fs.run(&mut status3); fs.clear(); let mut status4 = Status::default(); fs.run(&mut status4); assert_eq!( ...
{ let _roscore = util::run_roscore_for(util::Feature::FrequencyStatusTest); rosrust::init("frequency_status_test"); let fs = FrequencyStatus::builder() .window_size(2) .min_frequency(10.0) .max_frequency(20.0) .tolerance(0.5) .build(); fs.tick(); rosrust::sl...
identifier_body
mod.rs
extern crate android_glue; use libc; use std::ffi::{CString}; use std::sync::mpsc::{Receiver, channel}; use {CreationError, Event, MouseCursor}; use CreationError::OsError; use events::ElementState::{Pressed, Released}; use events::Event::{MouseInput, MouseMoved}; use events::MouseButton; use std::collections::VecDeq...
(&self) -> bool { unsafe { ffi::egl::GetCurrentContext() == self.context } } pub fn get_proc_address(&self, addr: &str) -> *const () { let addr = CString::from_slice(addr.as_bytes()); let addr = addr.as_ptr(); unsafe { ffi::egl::GetProcAddress(addr) as *const () ...
is_current
identifier_name
mod.rs
extern crate android_glue; use libc; use std::ffi::{CString}; use std::sync::mpsc::{Receiver, channel}; use {CreationError, Event, MouseCursor}; use CreationError::OsError; use events::ElementState::{Pressed, Released}; use events::Event::{MouseInput, MouseMoved}; use events::MouseButton; use std::collections::VecDeq...
} else { Some(( unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32, unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32 )) } } pub fn get_outer_size(&self) -> Option<(u32, u32)> { self.get_inner_size() } ...
pub fn get_inner_size(&self) -> Option<(u32, u32)> { let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null() { None
random_line_split
deriving-meta-multiple.rs
// xfail-fast // 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 // <...
() { use core::hash::{Hash, HashUtil}; // necessary for IterBytes check let a = Foo {bar: 4, baz: -3}; a == a; // check for Eq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness a.hash(); // check for IterBytes impl w/o testing its correctness }
main
identifier_name
deriving-meta-multiple.rs
// xfail-fast // 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. //
// <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. #[deriving(Eq)] #[deriving(Clone)] #[deriving(IterBytes)] struct Foo { bar: uint, baz: int } pub fn main() { use core::hash::{Hash, HashUtil}...
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
deriving-meta-multiple.rs
// xfail-fast // 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 // <...
{ use core::hash::{Hash, HashUtil}; // necessary for IterBytes check let a = Foo {bar: 4, baz: -3}; a == a; // check for Eq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness a.hash(); // check for IterBytes impl w/o testing its correctness }
identifier_body
derive_input_object.rs
#![allow(clippy::match_wild_err_arm)] use crate::{ result::{GraphQLScope, UnsupportedAttribute}, util::{self, span_container::SpanContainer, RenameRule}, }; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields}; pub fn impl_input_object(ast: ...
if let Some(duplicates) = crate::util::duplicate::Duplicate::find_by_key(&fields, |field| &field.name) { error.duplicate(duplicates.iter()) } if!attrs.interfaces.is_empty() { attrs.interfaces.iter().for_each(|elm| { error.unsupported_attribute(elm.span(), Unsupport...
{ error.not_empty(ast_span); }
conditional_block
derive_input_object.rs
#![allow(clippy::match_wild_err_arm)] use crate::{ result::{GraphQLScope, UnsupportedAttribute}, util::{self, span_container::SpanContainer, RenameRule}, }; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields}; pub fn
(ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> { let ast_span = ast.span(); let fields = match ast.data { Data::Struct(data) => match data.fields { Fields::Named(named) => named.named, _ => { return Err( error.custom_e...
impl_input_object
identifier_name
derive_input_object.rs
#![allow(clippy::match_wild_err_arm)] use crate::{ result::{GraphQLScope, UnsupportedAttribute}, util::{self, span_container::SpanContainer, RenameRule}, }; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields}; pub fn impl_input_object(ast: ...
.name .clone() .map(SpanContainer::into_inner) .unwrap_or_else(|| ident.to_string()); let fields = fields .into_iter() .filter_map(|field| { let span = field.span(); let field_attrs = match util::FieldAttributes::from_attrs( &field.a...
{ let ast_span = ast.span(); let fields = match ast.data { Data::Struct(data) => match data.fields { Fields::Named(named) => named.named, _ => { return Err( error.custom_error(ast_span, "all fields must be named, e.g., `test: String`") ...
identifier_body
derive_input_object.rs
#![allow(clippy::match_wild_err_arm)] use crate::{ result::{GraphQLScope, UnsupportedAttribute}, util::{self, span_container::SpanContainer, RenameRule}, }; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields}; pub fn impl_input_object(ast: ...
description: field_attrs.description.map(SpanContainer::into_inner), deprecation: None, resolver_code, is_type_inferred: true, is_async: false, default, span, }) }) .collect::<Vec<_...
args: Vec::new(),
random_line_split
get.rs
extern crate tftp; use std::io::BufWriter; use std::fs::OpenOptions; use std::path::Path; use std::net::{SocketAddr, IpAddr, Ipv4Addr}; use std::process::exit; use std::env; use tftp::client::get; use tftp::packet::Mode; fn
() { let args: Vec<_> = env::args().collect(); if args.len()!= 2 { println!("Usage: {} PATH", args.get(0).unwrap()); return } let file_path = args[1].clone(); let mut file_options = OpenOptions::new(); file_options.truncate(true).create(true).write(true); let file = match fil...
main
identifier_name
get.rs
extern crate tftp; use std::io::BufWriter; use std::fs::OpenOptions; use std::path::Path; use std::net::{SocketAddr, IpAddr, Ipv4Addr}; use std::process::exit; use std::env; use tftp::client::get; use tftp::packet::Mode; fn main() { let args: Vec<_> = env::args().collect(); if args.len()!= 2 { printl...
get(&Path::new(&file_path), Mode::Octet, &mut writer); }
random_line_split
get.rs
extern crate tftp; use std::io::BufWriter; use std::fs::OpenOptions; use std::path::Path; use std::net::{SocketAddr, IpAddr, Ipv4Addr}; use std::process::exit; use std::env; use tftp::client::get; use tftp::packet::Mode; fn main()
{ let args: Vec<_> = env::args().collect(); if args.len() != 2 { println!("Usage: {} PATH", args.get(0).unwrap()); return } let file_path = args[1].clone(); let mut file_options = OpenOptions::new(); file_options.truncate(true).create(true).write(true); let file = match file_...
identifier_body
lifetimes_as_part_of_type.rs
#![allow(warnings)] // **Exercise 1.** For the method `get`, identify at least 4 lifetimes // that must be inferred. // // **Exercise 2.** Modify the signature of `get` such that the method // `get` fails to compile with a lifetime inference error. // // **Exercise 3.** Modify the signature of `get` such that the // `...
} #[test] // START SOLUTION #[should_panic] // END SOLUTION fn do_not_compile() { let map: Map<char, String> = Map::new(); let r; let key = &'c'; r = map.get(key); panic!("If this test is running, your program compiled, and that's bad!"); }
{ let matching_pair: Option<&(K, V)> = <[_]>::iter(&self.elements) .rev() .find(|pair| pair.0 == *key); matching_pair.map(|pair| &pair.1) }
identifier_body
lifetimes_as_part_of_type.rs
#![allow(warnings)] // **Exercise 1.** For the method `get`, identify at least 4 lifetimes // that must be inferred. // // **Exercise 2.** Modify the signature of `get` such that the method // `get` fails to compile with a lifetime inference error. // // **Exercise 3.** Modify the signature of `get` such that the // `...
() { let map: Map<char, String> = Map::new(); let r; let key = &'c'; r = map.get(key); panic!("If this test is running, your program compiled, and that's bad!"); }
do_not_compile
identifier_name
lifetimes_as_part_of_type.rs
#![allow(warnings)] // **Exercise 1.** For the method `get`, identify at least 4 lifetimes
// // **Exercise 2.** Modify the signature of `get` such that the method // `get` fails to compile with a lifetime inference error. // // **Exercise 3.** Modify the signature of `get` such that the // `do_not_compile` test fails to compile with a lifetime error // (but `get` does not have any errors). // // **Exercise ...
// that must be inferred.
random_line_split
issue-14589.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 send(&self, _: T) {} } trait Foo { fn dummy(&self) { }} struct Output(int); impl Foo for Output {}
{}
identifier_body
issue-14589.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>(_: T) {} struct Test<T> { marker: std::marker::PhantomData<T> } impl<T> Test<T> { fn new() -> Test<T> { Test { marker: ::std::marker::PhantomData } } fn foo(_: T) {} fn send(&self, _: T) {} } trait Foo { fn dummy(&self) { }} struct Output(int); impl Foo for Output {}
send
identifier_name
issue-14589.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 Output(int); impl Foo for Output {}
random_line_split
builder.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
nonterm.builder_into(), ))); self } pub fn add_named_nonterm( &mut self, name: impl BuilderInto<Name>, nonterm: impl BuilderInto<E::NonTerm>, ) -> &mut Self { self.elems.push(ProdElement::new_with_name( name.builder_into(), Elem::NonTerm(nonterm.builder_into()), ...
nonterm: impl BuilderInto<E::NonTerm>, ) -> &mut Self { self .elems .push(ProdElement::new_empty(Elem::NonTerm(
random_line_split
builder.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} // ---------------- pub struct GrammarBuilder<E: ElemTypes> { start: E::NonTerm, rules: Vec<RuleInner<E>>, action_map: BTreeMap<E::ActionKey, E::ActionValue>, } impl<E: ElemTypes> GrammarBuilder<E> { fn new(start: E::NonTerm) -> Self { GrammarBuilder { start, rules: Vec::new(), actio...
{ let action_key = action_key.builder_into(); self .action_map .insert(action_key.clone(), action_value.builder_into()); self.prods.push(ProdInner { action_key, elements: elems.builder_into(), }); self }
identifier_body
builder.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
( &mut self, action_key: impl BuilderInto<E::ActionKey>, action_value: impl BuilderInto<E::ActionValue>, elems: impl BuilderInto<Vec<ProdElement<E>>>, ) -> &mut Self { let action_key = action_key.builder_into(); self .action_map .insert(action_key.clone(), action_value.builder_into()...
add_prod_with_elems
identifier_name
utils.rs
use snafu::{ResultExt, Snafu}; use std::path::{Path, PathBuf}; use tokio::fs; use tokio::io::AsyncWriteExt; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { #[snafu(display("Invalid Download URL: {} ({})", source, details))] InvalidUrl { details: String, source: url::Pa...
let mut resp = reqwest::get(url) .await .context(DownloadSnafu { details: format!("could not download url {}", url), })? .error_for_status() .context(DownloadSnafu { details: format!("download response error for {}", url), })?; while let Some...
.context(InvalidIOSnafu { details: format!("could no create file for download {}", path.display()), })? });
random_line_split
utils.rs
use snafu::{ResultExt, Snafu}; use std::path::{Path, PathBuf}; use tokio::fs; use tokio::io::AsyncWriteExt; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { #[snafu(display("Invalid Download URL: {} ({})", source, details))] InvalidUrl { details: String, source: url::Pa...
Ok(()) } pub async fn create_dir_if_not_exists_rec(path: &Path) -> Result<(), Error> { let mut head = PathBuf::new(); for fragment in path { head.push(fragment); create_dir_if_not_exists(&head).await?; } Ok(()) } /// Downloads the file identified by the url and saves it to the ...
{ fs::create_dir(path).await.context(InvalidIOSnafu { details: format!("could no create directory {}", path.display()), })?; }
conditional_block
utils.rs
use snafu::{ResultExt, Snafu}; use std::path::{Path, PathBuf}; use tokio::fs; use tokio::io::AsyncWriteExt; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { #[snafu(display("Invalid Download URL: {} ({})", source, details))] InvalidUrl { details: String, source: url::Pa...
(path: &Path, url: &str) -> Result<(), Error> { let mut file = tokio::io::BufWriter::new({ fs::OpenOptions::new() .append(true) .create(true) .open(&path) .await .context(InvalidIOSnafu { details: format!("could no create file for downlo...
download_to_file
identifier_name
capture-clauses-boxed-closures.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 mut sum = 0u; let elems = [ 1u, 2, 3, 4, 5 ]; each(elems, |val| sum += *val); assert_eq!(sum, 15); }
main
identifier_name
capture-clauses-boxed-closures.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 mut sum = 0u; let elems = [ 1u, 2, 3, 4, 5 ]; each(elems, |val| sum += *val); assert_eq!(sum, 15); }
{ for val in x.iter() { f(val) } }
identifier_body
capture-clauses-boxed-closures.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 mut sum = 0u; let elems = [ 1u, 2, 3, 4, 5 ]; each(elems, |val| sum += *val); assert_eq!(sum, 15); }
random_line_split
no-capture-arc.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// <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. // error-pattern: use of moved value extern mod extra; use extra::arc; use std::task; fn main() { let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let...
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
no-capture-arc.rs
// Copyright 2012-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-MI...
{ let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let arc_v = arc::Arc::new(v); do task::spawn() { let v = arc_v.get(); assert_eq!(v[3], 4); }; assert_eq!((arc_v.get())[2], 3); info2!("{:?}", arc_v); }
identifier_body
no-capture-arc.rs
// Copyright 2012-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-MI...
() { let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let arc_v = arc::Arc::new(v); do task::spawn() { let v = arc_v.get(); assert_eq!(v[3], 4); }; assert_eq!((arc_v.get())[2], 3); info2!("{:?}", arc_v); }
main
identifier_name
main.rs
// Copyright 2015 The Athena 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...
} } // ### Misc Command Handlers ### fn display_usage() -> Result<(), Box<Error>> { println!("{}", USAGE); return Ok(()); } fn display_not_found() -> Result<(), Box<Error>> { unimplemented!(); }
{ println!("{}", err); std::process::exit(1) }
conditional_block
main.rs
// Copyright 2015 The Athena 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...
// Run the actual command let result = match &flags.arg_command[..] { "list" => commands::list::execute(), "new" => commands::new::execute(), "setup" => commands::setup::execute(), "" => display_usage(), _ => display_not_found() }; // Set the exit code depending ...
random_line_split
main.rs
// Copyright 2015 The Athena 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...
{ arg_command: String, arg_args: Vec<String> } fn main() { // Parse in the command line flags let flags: Flags = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); // Run the actual command let result = match &flags.arg_command[..] { "list" => co...
Flags
identifier_name
main.rs
// Copyright 2015 The Athena 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...
std::process::exit(1) } } } // ### Misc Command Handlers ### fn display_usage() -> Result<(), Box<Error>> { println!("{}", USAGE); return Ok(()); } fn display_not_found() -> Result<(), Box<Error>> { unimplemented!(); }
{ // Parse in the command line flags let flags: Flags = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); // Run the actual command let result = match &flags.arg_command[..] { "list" => commands::list::execute(), "new" => commands::new::execute(...
identifier_body
subst.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, tcx: ty::ctxt, substs: &ty::substs) -> ~[T] { self.map(|t| t.subst(tcx, substs)) } } impl<T:Subst> Subst for OptVec<T> { fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> OptVec<T> { self.map(|t| t.subst(tcx, substs)) } } impl<T:Subst +'static> Subst for @T { fn subst(&sel...
subst
identifier_name
subst.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 ...
/////////////////////////////////////////////////////////////////////////// // Other types impl<T:Subst> Subst for ~[T] { fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ~[T] { self.map(|t| t.subst(tcx, substs)) } } impl<T:Subst> Subst for OptVec<T> { fn subst(&self, tcx: ty::ctxt, substs:...
} } } }
random_line_split
subst.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 ...
ty::NonerasedRegions(ref regions) => { ty::NonerasedRegions(regions.subst(tcx, substs)) } } } } impl Subst for ty::BareFnTy { fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::BareFnTy { ty::fold_bare_fn_ty(self, |t| t.subst(tcx, substs)) } ...
{ ty::ErasedRegions }
conditional_block
subst.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 Subst for ty::Region { fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::Region { // Note: This routine only handles the self region, because it // is only concerned with substitutions of regions that appear // in types. Region substitution of the bound regions that ...
{ ty::Generics { type_param_defs: self.type_param_defs.subst(tcx, substs), region_param: self.region_param } }
identifier_body
remove_lines_from_a_file.rs
// http://rosettacode.org/wiki/Remove_lines_from_a_file extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; use std::io::{BufReader,BufRead}; use std::fs::File; const USAGE: &'static str = " Usage: remove_lines_from_a_file <start> <count> <file> "; #[derive(Debug, RustcDecodable)] struct
{ arg_start: usize, arg_count: usize, arg_file: String, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); let file = BufReader::new(File::open(args.arg_file).unwrap()); for (i, line) in file.lines().enumerate() { ...
Args
identifier_name
remove_lines_from_a_file.rs
// http://rosettacode.org/wiki/Remove_lines_from_a_file extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; use std::io::{BufReader,BufRead}; use std::fs::File; const USAGE: &'static str = " Usage: remove_lines_from_a_file <start> <count> <file> "; #[derive(Debug, RustcDecodable)] struct Args { ...
{ let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); let file = BufReader::new(File::open(args.arg_file).unwrap()); for (i, line) in file.lines().enumerate() { let cur = i + 1; if cur < args.arg_start || cur >= (args.arg_start + ar...
identifier_body
remove_lines_from_a_file.rs
// http://rosettacode.org/wiki/Remove_lines_from_a_file extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; use std::io::{BufReader,BufRead}; use std::fs::File; const USAGE: &'static str = " Usage: remove_lines_from_a_file <start> <count> <file> "; #[derive(Debug, RustcDecodable)] struct Args { ...
arg_count: usize, arg_file: String, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); let file = BufReader::new(File::open(args.arg_file).unwrap()); for (i, line) in file.lines().enumerate() { let cur = i + 1; ...
random_line_split
remove_lines_from_a_file.rs
// http://rosettacode.org/wiki/Remove_lines_from_a_file extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; use std::io::{BufReader,BufRead}; use std::fs::File; const USAGE: &'static str = " Usage: remove_lines_from_a_file <start> <count> <file> "; #[derive(Debug, RustcDecodable)] struct Args { ...
} }
{ println!("{}", line.unwrap()); }
conditional_block
lib.rs
//! This crate provides generic implementations of clustering //! algorithms, allowing them to work with any back-end "point //! database" that implements the required operations, e.g. one might //! be happy with using the naive collection `BruteScan` from this //! crate, or go all out and implement a specialised R*-tr...
//! Clustering algorithms. //! //! ![A cluster](http://upload.wikimedia.org/wikipedia/commons/e/e1/Cassetteandfreehub.jpg) //!
random_line_split
location.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::{convert::TryInto, path::PathBuf}; use common::{Location, SourceLocationKey}; use lsp_types::Url; use crate::lsp_runtime...
} fn read_file_and_get_range( path_to_fragment: &PathBuf, index: usize, ) -> LSPRuntimeResult<(String, lsp_types::Range)> { let file = std::fs::read(path_to_fragment) .map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?; let file_contents = std::str::from_utf8(&file).map_err(|e...
)), }
random_line_split
location.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::{convert::TryInto, path::PathBuf}; use common::{Location, SourceLocationKey}; use lsp_types::Url; use crate::lsp_runtime...
( location: Location, root_dir: &PathBuf, ) -> LSPRuntimeResult<(String, lsp_types::Location)> { match location.source_location() { SourceLocationKey::Embedded { path, index } => { let path_to_fragment = root_dir.join(PathBuf::from(path.lookup())); let uri = get_uri(&path_to_...
to_contents_and_lsp_location_of_graphql_literal
identifier_name
location.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::{convert::TryInto, path::PathBuf}; use common::{Location, SourceLocationKey}; use lsp_types::Url; use crate::lsp_runtime...
SourceLocationKey::Standalone { path } => { let path_to_fragment = root_dir.join(PathBuf::from(path.lookup())); let uri = get_uri(&path_to_fragment)?; let (file_contents, range) = read_file_and_get_range(&path_to_fragment, 0)?; Ok((file_contents, lsp_types::Loca...
{ let path_to_fragment = root_dir.join(PathBuf::from(path.lookup())); let uri = get_uri(&path_to_fragment)?; let (file_contents, range) = read_file_and_get_range(&path_to_fragment, index.try_into().unwrap())?; Ok((file_contents, lsp_types::Location { uri,...
conditional_block
location.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::{convert::TryInto, path::PathBuf}; use common::{Location, SourceLocationKey}; use lsp_types::Url; use crate::lsp_runtime...
path_to_fragment, index )) })?; Ok(( source.text.to_string(), lsp_types::Range { start: lsp_types::Position { line: source.line_index as u64, character: source.column_index as u64, }, end: lsp_types::Positio...
{ let file = std::fs::read(path_to_fragment) .map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?; let file_contents = std::str::from_utf8(&file).map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?; let response = extract_graphql::parse_chunks(file_contents); let sou...
identifier_body
historystore.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::Deref; use std::path::PathBuf; use anyhow::Result; use edenapi_types::HistoryEntry; use types::Key; use types::NodeInfo; us...
(&self) -> Result<()> { T::refresh(self) } } impl<T: HgIdMutableHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync> HgIdMutableHistoryStore for U { fn add(&self, key: &Key, info: &NodeInfo) -> Result<()> { T::add(self, key, info) } fn flush(&self) -> Result<Option<Vec<PathBuf...
refresh
identifier_name
historystore.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::Deref; use std::path::PathBuf; use anyhow::Result; use edenapi_types::HistoryEntry; use types::Key; use types::NodeInfo; us...
} impl<T: HgIdMutableHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync> HgIdMutableHistoryStore for U { fn add(&self, key: &Key, info: &NodeInfo) -> Result<()> { T::add(self, key, info) } fn flush(&self) -> Result<Option<Vec<PathBuf>>> { T::flush(self) } } impl<T: RemoteHi...
{ T::refresh(self) }
identifier_body
historystore.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::Deref; use std::path::PathBuf; use anyhow::Result; use edenapi_types::HistoryEntry; use types::Key; use types::NodeInfo; us...
} impl<T: RemoteHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync> RemoteHistoryStore for U { fn prefetch(&self, keys: &[StoreKey]) -> Result<()> { T::prefetch(self, keys) } }
fn flush(&self) -> Result<Option<Vec<PathBuf>>> { T::flush(self) }
random_line_split
option.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 ...
else { Some(x) } }).collect(); assert!(v == None); // test that it does not take more elements than it needs let mut functions = [|| Some(()), || None, || panic!()]; let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect(); assert!(v == None); }
{ None }
conditional_block
option.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 i = Rc::new(RefCell::new(0i)); { let x = r(i.clone()); let opt = Some(x); let _y = opt.unwrap(); } assert_eq!(*i.borrow(), 1); } #[test] fn test_option_dance() { let x = Some(()); let mut y = Some(5i); let mut y2 = 0; for _x in x.iter() { y2 = y.take...
random_line_split
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or_else(|| 2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or_else(|| 2), 2); } #[test] fn test_iter() { let val = 5i; let x = Some(val); let mut it = x.iter(); assert_eq!(it.size_hint(), (1, Some(1))); assert_eq!(it.n...
test_unwrap_or_else
identifier_name
option.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 ...
#[test] fn test_unwrap_or_else() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or_else(|| 2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or_else(|| 2), 2); } #[test] fn test_iter() { let val = 5i; let x = Some(val); let mut it = x.iter(); assert_eq!(it.size_hint(), (1...
{ let x: Option<int> = Some(1); assert_eq!(x.unwrap_or(2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or(2), 2); }
identifier_body
font_icon.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle}, }; /// The `FontIconRenderObject` holds the font icons inside
impl RenderObject for FontIconRenderObject { fn render_self(&self, ctx: &mut Context, global_position: &Point) { let (bounds, icon, icon_brush, icon_font, icon_size) = { let widget = ctx.widget(); ( *widget.get::<Rectangle>("bounds"), widget.clone::<St...
/// a render object. #[derive(Debug, IntoRenderObject)] pub struct FontIconRenderObject;
random_line_split
font_icon.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle}, }; /// The `FontIconRenderObject` holds the font icons inside /// a render object. #[derive(Debug, IntoRenderObject)] pub struct FontIconRenderObject; impl RenderObject for FontIconRenderObject { fn render_...
if!icon.is_empty() { ctx.render_context_2_d().begin_path(); ctx.render_context_2_d().set_font_family(icon_font); ctx.render_context_2_d().set_font_size(icon_size); ctx.render_context_2_d().set_fill_style(icon_brush); ctx.render_context_2_d().fill_tex...
{ let (bounds, icon, icon_brush, icon_font, icon_size) = { let widget = ctx.widget(); ( *widget.get::<Rectangle>("bounds"), widget.clone::<String>("icon"), widget.get::<Brush>("icon_brush").clone(), widget.get::<String>("ico...
identifier_body
font_icon.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle}, }; /// The `FontIconRenderObject` holds the font icons inside /// a render object. #[derive(Debug, IntoRenderObject)] pub struct FontIconRenderObject; impl RenderObject for FontIconRenderObject { fn render_...
if!icon.is_empty() { ctx.render_context_2_d().begin_path(); ctx.render_context_2_d().set_font_family(icon_font); ctx.render_context_2_d().set_font_size(icon_size); ctx.render_context_2_d().set_fill_style(icon_brush); ctx.render_context_2_d().fill_te...
{ return; }
conditional_block
font_icon.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle}, }; /// The `FontIconRenderObject` holds the font icons inside /// a render object. #[derive(Debug, IntoRenderObject)] pub struct
; impl RenderObject for FontIconRenderObject { fn render_self(&self, ctx: &mut Context, global_position: &Point) { let (bounds, icon, icon_brush, icon_font, icon_size) = { let widget = ctx.widget(); ( *widget.get::<Rectangle>("bounds"), widget.clone::...
FontIconRenderObject
identifier_name
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::order::ne; use core::cmp::PartialEq; struct A<T: PartialEq> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&m...
// } type T = i32; Iterator_impl!(T); type L = A<T>; type R = A<T>; #[test] fn ne_test1() { let a: L = L { begin: 0, end: 10 }; let b: R = R { begin: 0, end: 10 }; let result: bool = ne::<L, R>(a, b); assert_eq!(result, false); } #[test] fn ne_test2() { let a: L = L...
// } // }
random_line_split
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::order::ne; use core::cmp::PartialEq; struct A<T: PartialEq> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&m...
#[test] fn ne_test5() { let a: L = L { begin: 10, end: 20 }; let b: R = R { begin: 0, end: 10 }; let result: bool = ne::<L, R>(a, b); assert_eq!(result, true); } }
{ let a: L = L { begin: 0, end: 10 }; let b: R = R { begin: 10, end: 20 }; let result: bool = ne::<L, R>(a, b); assert_eq!(result, true); }
identifier_body
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::order::ne; use core::cmp::PartialEq; struct
<T: PartialEq> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) ...
A
identifier_name
unboxed-closures-counter-not-moved.rs
// run-pass // Test that we mutate a counter on the stack only when we expect to. fn call<F>(f: F) where F : FnOnce() { f(); } fn
() { let y = vec![format!("Hello"), format!("World")]; let mut counter = 22_u32; call(|| { // Move `y`, but do not move `counter`, even though it is read // by value (note that it is also mutated). for item in y { //~ WARN unused variable: `item` let v = counter; ...
main
identifier_name
unboxed-closures-counter-not-moved.rs
// run-pass // Test that we mutate a counter on the stack only when we expect to. fn call<F>(f: F) where F : FnOnce() { f(); } fn main() { let y = vec![format!("Hello"), format!("World")]; let mut counter = 22_u32; call(|| {
// Move `y`, but do not move `counter`, even though it is read // by value (note that it is also mutated). for item in y { //~ WARN unused variable: `item` let v = counter; counter += v; } }); assert_eq!(counter, 88); call(move || { // this mu...
random_line_split
unboxed-closures-counter-not-moved.rs
// run-pass // Test that we mutate a counter on the stack only when we expect to. fn call<F>(f: F) where F : FnOnce()
fn main() { let y = vec![format!("Hello"), format!("World")]; let mut counter = 22_u32; call(|| { // Move `y`, but do not move `counter`, even though it is read // by value (note that it is also mutated). for item in y { //~ WARN unused variable: `item` let v = counter...
{ f(); }
identifier_body
mod.rs
//! Encoder-based structs and traits. mod encoder; mod impl_tuples; mod impls; use self::write::Writer; use crate::{config::Config, error::EncodeError, utils::Sealed}; pub mod write; pub use self::encoder::EncoderImpl; /// Any source that can be encoded. This trait should be implemented for all types that you want...
{ (len as u64).encode(encoder) }
identifier_body
mod.rs
//! Encoder-based structs and traits. mod encoder; mod impl_tuples; mod impls; use self::write::Writer; use crate::{config::Config, error::EncodeError, utils::Sealed}; pub mod write; pub use self::encoder::EncoderImpl;
/// This trait will be automatically implemented if you enable the `derive` feature and add `#[derive(bincode::Encode)]` to your trait. /// /// # Implementing this trait manually /// /// If you want to implement this trait for your type, the easiest way is to add a `#[derive(bincode::Encode)]`, build and check your `ta...
/// Any source that can be encoded. This trait should be implemented for all types that you want to be able to use with any of the `encode_with` methods. ///
random_line_split
mod.rs
//! Encoder-based structs and traits. mod encoder; mod impl_tuples; mod impls; use self::write::Writer; use crate::{config::Config, error::EncodeError, utils::Sealed}; pub mod write; pub use self::encoder::EncoderImpl; /// Any source that can be encoded. This trait should be implemented for all types that you want...
<E: Encoder>(encoder: &mut E, len: usize) -> Result<(), EncodeError> { (len as u64).encode(encoder) }
encode_slice_len
identifier_name
get_profile_information.rs
//! `GET /_matrix/federation/*/query/profile` //! //! Endpoint to query profile information with a user id and optional field. pub mod v1 { //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1queryprofile use ruma_common::{api::ruma_api, MxcUri, Us...
Default::default() } } /// Profile fields to specify in query. /// /// This type can hold an arbitrary string. To check for formats that are not available as a /// documented variant here, use its string representation, obtained through `.as_str()`. #[derive(Clone, Debug, Pa...
impl Response { /// Creates an empty `Response`. pub fn new() -> Self {
random_line_split
get_profile_information.rs
//! `GET /_matrix/federation/*/query/profile` //! //! Endpoint to query profile information with a user id and optional field. pub mod v1 { //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1queryprofile use ruma_common::{api::ruma_api, MxcUri, Us...
{ /// Display name of the user. #[ruma_enum(rename = "displayname")] DisplayName, /// Avatar URL for the user's avatar. #[ruma_enum(rename = "avatar_url")] AvatarUrl, #[doc(hidden)] _Custom(PrivOwnedStr), } impl ProfileField { /// Creat...
ProfileField
identifier_name
block_metadata.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{config::global::Config as GlobalConfig, errors::*}; use diem_crypto::HashValue; use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata}; use std::str::FromStr; #[derive(Debug)] pub enum
{ Account(String), Address(AccountAddress), } #[derive(Debug)] pub enum Entry { Proposer(Proposer), Timestamp(u64), } impl FromStr for Entry { type Err = Error; fn from_str(s: &str) -> Result<Self> { let s = s.split_whitespace().collect::<String>(); let s = &s .str...
Proposer
identifier_name
block_metadata.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{config::global::Config as GlobalConfig, errors::*}; use diem_crypto::HashValue; use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata}; use std::str::FromStr; #[derive(Debug)] pub enum Proposer { ...
} pub fn build_block_metadata(config: &GlobalConfig, entries: &[Entry]) -> Result<BlockMetadata> { let mut timestamp = None; let mut proposer = None; for entry in entries { match entry { Entry::Proposer(s) => { proposer = match s { Proposer::Account(...
{ if s.starts_with("//!") { Ok(Some(s.parse::<Entry>()?)) } else { Ok(None) } }
identifier_body
block_metadata.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{config::global::Config as GlobalConfig, errors::*}; use diem_crypto::HashValue; use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata}; use std::str::FromStr; #[derive(Debug)] pub enum Proposer { ...
}
{ Err(ErrorKind::Other("Cannot generate block metadata".to_string()).into()) }
conditional_block
block_metadata.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{config::global::Config as GlobalConfig, errors::*}; use diem_crypto::HashValue; use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata}; use std::str::FromStr; #[derive(Debug)] pub enum Proposer { ...
return Ok(Entry::Proposer(Proposer::Address( AccountAddress::from_hex_literal(s)?, ))); } if let Some(s) = s.strip_prefix("block-time:") { return Ok(Entry::Timestamp(s.parse::<u64>()?)); } Err(ErrorKind::Other(format!( "fai...
random_line_split
position.rs
* 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/. */ //! Generic types for CSS handling of specified and computed values of //! [`position`](https://drafts.csswg.org/css-backgrounds-3/#position) #[derive(Clone, Copy, Debug, HasViewportPe...
/* This Source Code Form is subject to the terms of the Mozilla Public
random_line_split
position.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/. */ //! Generic types for CSS handling of specified and computed values of //! [`position`](https://drafts.csswg.org/c...
<H, V> { /// The horizontal component of position. pub horizontal: H, /// The vertical component of position. pub vertical: V, } impl<H, V> Position<H, V> { /// Returns a new position. pub fn new(horizontal: H, vertical: V) -> Self { Self { horizontal: horizontal, ...
Position
identifier_name
applayerframetype.rs
/* Copyright (C) 2021 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 WARR...
(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident; let mut fields = Vec::new(); let mut vals = Vec::new(); let mut cstrings = Vec::new(); let mut names = Vec::new(); match input.data { syn::Data::Enum(ref data) => { ...
derive_app_layer_frame_type
identifier_name
applayerframetype.rs
/* Copyright (C) 2021 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 WARR...
xname.push_str(&chars[i].to_lowercase().to_string()); } xname } #[cfg(test)] mod test { use super::*; #[test] fn test_transform_name() { assert_eq!(transform_name("One"), "one"); assert_eq!(transform_name("OneTwo"), "one.two"); assert_eq!(transform_name("OneTwoThre...
{ xname.push('.'); }
conditional_block
applayerframetype.rs
/* Copyright (C) 2021 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 WARR...
}
{ assert_eq!(transform_name("One"), "one"); assert_eq!(transform_name("OneTwo"), "one.two"); assert_eq!(transform_name("OneTwoThree"), "one.two.three"); assert_eq!(transform_name("NBSS"), "nbss"); assert_eq!(transform_name("NBSSHdr"), "nbss.hdr"); assert_eq!(transform_nam...
identifier_body
applayerframetype.rs
/* Copyright (C) 2021 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. *
* You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use syn::{self, ...
* This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. *
random_line_split
fetch.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::RequestBinding::RequestInfo; use dom::bindings::codegen::Bindings::RequestBi...
(&mut self, fetch_metadata: Result<FetchMetadata, NetworkError>) { let promise = self.fetch_promise.take().expect("fetch promise is missing").root(); // JSAutoCompartment needs to be manually made. // Otherwise, Servo will crash. let promise_cx = promise.global().get_cx(); let _...
process_response
identifier_name
fetch.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::RequestBinding::RequestInfo; use dom::bindings::codegen::Bindings::RequestBi...
self.response_object.root().set_type(DOMResponseType::Default); }, FetchMetadata::Filtered { filtered,.. } => match filtered { FilteredMetadata::Basic(m) => { fill_headers_with_metadata(self.response_obje...
{ let promise = self.fetch_promise.take().expect("fetch promise is missing").root(); // JSAutoCompartment needs to be manually made. // Otherwise, Servo will crash. let promise_cx = promise.global().get_cx(); let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_j...
identifier_body
fetch.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::RequestBinding::RequestInfo; use dom::bindings::codegen::Bindings::RequestBi...
mode: request.mode.clone(), use_cors_preflight: request.use_cors_preflight, credentials_mode: request.credentials_mode, use_url_credentials: request.use_url_credentials, origin: GlobalScope::current().expect("No current global object").origin().immutable().clone(), referr...
headers: request.headers.clone(), unsafe_request: request.unsafe_request, body: request.body.clone(), destination: request.destination, synchronous: request.synchronous,
random_line_split