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
send_state_event.rs
//! `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{stateKey}` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3roomsroomidstateeventtypestatekey use ruma_common::{ api::ruma_api, events::{AnyStateEventContent, ...
} impl Response { /// Creates a new `Response` with the given event id. pub fn new(event_id: Box<EventId>) -> Self { Self { event_id } } } #[cfg(feature = "client")] impl<'a> ruma_common::api::OutgoingRequest for Request<'a> { type EndpointError = crate...
{ Self { room_id, event_type, state_key, body } }
identifier_body
send_state_event.rs
//! `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{stateKey}` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3roomsroomidstateeventtypestatekey use ruma_common::{ api::ruma_api, events::{AnyStateEventContent, ...
let http_request = http::Request::builder() .method(http::Method::PUT) .uri(url) .header(header::CONTENT_TYPE, "application/json") .header( header::AUTHORIZATION, HeaderValue::from_str(&format!( ...
{ url.push('/'); url.push_str(&Cow::from(utf8_percent_encode(self.state_key, NON_ALPHANUMERIC))); }
conditional_block
send_state_event.rs
//! `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{stateKey}` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3roomsroomidstateeventtypestatekey use ruma_common::{ api::ruma_api, events::{AnyStateEventContent, ...
Ok(Self { room_id, state_key, event_type: content.event_type(), body: Raw::from_json(to_raw_json_value(content)?), }) } /// Creates a new `Request` with the given room id, event type, state key and raw event ...
state_key: &'a str, content: &'a T, ) -> serde_json::Result<Self> {
random_line_split
shim.rs
bug!("creating shims from intrinsics ({:?}) is unsupported", instance) } }; debug!("make_shim({:?}) = untransformed {:?}", instance, result); run_passes( tcx, &mut result, MirPhase::Const, &[&[ &add_moves_for_packed_drops::AddMovesForPackedDrops, ...
<'tcx>( tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>, local_decls: IndexVec<Local, LocalDecl<'tcx>>, arg_count: usize, span: Span, ) -> Body<'tcx> { Body::new( tcx, source, basic_blocks, IndexVec::from_el...
new_body
identifier_name
shim.rs
bug!("creating shims from intrinsics ({:?}) is unsupported", instance) } }; debug!("make_shim({:?}) = untransformed {:?}", instance, result); run_passes( tcx, &mut result, MirPhase::Const, &[&[ &add_moves_for_packed_drops::AddMovesForPackedDrops, ...
} impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> { type Path = (); fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch } fn body(&self) -> &'a Body<'tcx> { self.body } fn tcx(&self) -> TyCtxt<'tcx> { self.tcx } fn param_env(&s...
{ Ok(()) }
identifier_body
shim.rs
build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect(ty)) } // We are generating a call back to our def-id, which the // codegen backend knows to turn to an actual call, be it // a virtual call, or a direct call to a function for which // indirect calls...
None => bug!("fn pointer {:?} is not an fn", ty), };
random_line_split
shim.rs
{ tcx.intern_substs(&[ty.into()]) } else { InternalSubsts::identity_for_item(tcx, def_id) }; let sig = tcx.fn_sig(def_id).subst(tcx, substs); let sig = tcx.erase_late_bound_regions(sig); let span = tcx.def_span(def_id); let source_info = SourceInfo::outermost(span); let re...
{ arg_range.start += 1; }
conditional_block
build.rs
fn main() { build::main(); } #[cfg(feature = "bundled")] mod build { extern crate cc; use std::{env, fs}; use std::path::Path; pub fn main() { if cfg!(feature = "sqlcipher") { panic!("Builds with bundled SQLCipher are not supported"); } let out_dir = env::var("...
impl ParseCallbacks for SqliteTypeChooser { fn int_macro(&self, _name: &str, value: i64) -> Option<IntKind> { if value >= i32::min_value() as i64 && value <= i32::max_value() as i64 { Some(IntKind::I32) } else { None ...
use std::path::Path; #[derive(Debug)] struct SqliteTypeChooser;
random_line_split
build.rs
fn main() { build::main(); } #[cfg(feature = "bundled")] mod build { extern crate cc; use std::{env, fs}; use std::path::Path; pub fn main() { if cfg!(feature = "sqlcipher") { panic!("Builds with bundled SQLCipher are not supported"); } let out_dir = env::var("...
(_header: HeaderLocation) { let out_dir = env::var("OUT_DIR").unwrap(); let out_path = Path::new(&out_dir).join("bindgen.rs"); let in_path = PREBUILT_BINDGEN_PATHS[PREBUILT_BINDGEN_PATHS.len() - 1]; fs::copy(in_path, out_path).expect("Could not copy bindings to output dir...
write_to_out_dir
identifier_name
build.rs
fn main() { build::main(); } #[cfg(feature = "bundled")] mod build { extern crate cc; use std::{env, fs}; use std::path::Path; pub fn main() { if cfg!(feature = "sqlcipher") { panic!("Builds with bundled SQLCipher are not supported"); } let out_dir = env::var("...
} #[cfg(not(feature = "buildtime_bindgen"))] mod bindings { use super::HeaderLocation; use std::{env, fs}; use std::path::Path; #[cfg_attr(rustfmt, rustfmt_skip)] static PREBUILT_BINDGEN_PATHS: &'static [&'static str] = &[ "bindgen-bindings/bindgen_3.7...
{ "sqlite3" }
conditional_block
size_medium.rs
//! The GC can work with objects that are a few hundred bytes big. extern crate cell_gc; #[macro_use] extern crate cell_gc_derive; #[derive(IntoHeap)] struct Chunk<'h> { field_0: (u64, u64, u64, u64), field_32: (u64, u64, u64, u64), field_64: (u64, u64, u64, u64), field_96: (u64, u64, u64, u64), f...
}); }
99 );
random_line_split
size_medium.rs
//! The GC can work with objects that are a few hundred bytes big. extern crate cell_gc; #[macro_use] extern crate cell_gc_derive; #[derive(IntoHeap)] struct Chunk<'h> { field_0: (u64, u64, u64, u64), field_32: (u64, u64, u64, u64), field_64: (u64, u64, u64, u64), field_96: (u64, u64, u64, u64), f...
field_128: (i, i, i, i), field_160: (i, i, i, i), field_192: (i, i, i, i), field_224: (i, i, i, i), next: root, })); } // Heap is full. assert_eq!( hs.try_alloc(Chunk { field_...
{ cell_gc::with_heap(|hs| { hs.set_page_limit::<Chunk>(Some(1)); let n = cell_gc::page_capacity::<Chunk>(); // Users don't care about the exact value here, but test it anyway // since it would be weird if it changed (or turned out to be different // on some platform). If th...
identifier_body
size_medium.rs
//! The GC can work with objects that are a few hundred bytes big. extern crate cell_gc; #[macro_use] extern crate cell_gc_derive; #[derive(IntoHeap)] struct
<'h> { field_0: (u64, u64, u64, u64), field_32: (u64, u64, u64, u64), field_64: (u64, u64, u64, u64), field_96: (u64, u64, u64, u64), field_128: (u64, u64, u64, u64), field_160: (u64, u64, u64, u64), field_192: (u64, u64, u64, u64), field_224: (u64, u64, u64, u64), next: Option<Chunk...
Chunk
identifier_name
benchmark.rs
use std::mem; use mio::net::{AddressFamily, Inet, Inet6, SockAddr, InetAddr, IPv4Addr, SocketType, Dgram, Stream}; use std::io::net::ip::IpAddr; use native::NativeTaskBuilder; use std::task::TaskBuilder; use mio::os::{from_sockaddr}; use time::Instant; use std::vec::*; use std::io::timer; mod nix { pub use nix::c_...
while i < 10000000 { let res = nix::read(clifd, buf.as_mut_slice()); assert_eq!(res.unwrap_err().kind, nix::EWOULDBLOCK); i = i + 1; } }); } #[test] fn epollctl_bench() { let (clifd, srvfd) = init("10.10.1.5:22222"); let epfd = nix::epoll_create().unwrap...
let mut buf = Vec::with_capacity(1600); unsafe { buf.set_len(1600); } timed("read", || { let mut i = 0u;
random_line_split
benchmark.rs
use std::mem; use mio::net::{AddressFamily, Inet, Inet6, SockAddr, InetAddr, IPv4Addr, SocketType, Dgram, Stream}; use std::io::net::ip::IpAddr; use native::NativeTaskBuilder; use std::task::TaskBuilder; use mio::os::{from_sockaddr}; use time::Instant; use std::vec::*; use std::io::timer; mod nix { pub use nix::c_...
(saddr: &str) -> (nix::Fd, nix::Fd) { let optval = 1i; let addr = SockAddr::parse(saddr.as_slice()).expect("could not parse InetAddr"); let srvfd = nix::socket(nix::AF_INET, nix::SOCK_STREAM, nix::SOCK_CLOEXEC).unwrap(); nix::setsockopt(srvfd, nix::SOL_SOCKET, nix::SO_REUSEADDR, &optval).unwrap(); n...
init
identifier_name
benchmark.rs
use std::mem; use mio::net::{AddressFamily, Inet, Inet6, SockAddr, InetAddr, IPv4Addr, SocketType, Dgram, Stream}; use std::io::net::ip::IpAddr; use native::NativeTaskBuilder; use std::task::TaskBuilder; use mio::os::{from_sockaddr}; use time::Instant; use std::vec::*; use std::io::timer; mod nix { pub use nix::c_...
fn init(saddr: &str) -> (nix::Fd, nix::Fd) { let optval = 1i; let addr = SockAddr::parse(saddr.as_slice()).expect("could not parse InetAddr"); let srvfd = nix::socket(nix::AF_INET, nix::SOCK_STREAM, nix::SOCK_CLOEXEC).unwrap(); nix::setsockopt(srvfd, nix::SOL_SOCKET, nix::SO_REUSEADDR, &optval).unwrap...
{ let start = Instant::now(); f(); let elapsed = start.elapsed(); println!(" {}: {}", label, elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 / 1_000_000_000.0); }
identifier_body
list_store.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::translate::*; use glib::{Type, ToValue, Value}; use libc::c_int; use std::...
(&self, position: Option<u32>, columns: &[u32], values: &[&ToValue]) -> TreeIter { unsafe { assert!(position.unwrap_or(0) <= i32::max_value() as u32); assert!(columns.len() == values.len()); let n_columns = ffi::gtk_tree_model_get_n_columns(self.to_glib_none().0) ...
insert_with_values
identifier_name
list_store.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::translate::*; use glib::{Type, ToValue, Value}; use libc::c_int; use std::...
} } pub fn set(&self, iter: &TreeIter, columns: &[u32], values: &[&ToValue]) { unsafe { assert!(columns.len() == values.len()); let n_columns = ffi::gtk_tree_model_get_n_columns(self.to_glib_none().0) as u32; assert!(columns.len() <= n_columns as usize); ...
{ ffi::gtk_list_store_reorder(self.to_glib_none().0, mut_override(new_order.as_ptr() as *const c_int)); }
conditional_block
list_store.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::translate::*; use glib::{Type, ToValue, Value}; use libc::c_int; use std::...
pub fn insert_with_values(&self, position: Option<u32>, columns: &[u32], values: &[&ToValue]) -> TreeIter { unsafe { assert!(position.unwrap_or(0) <= i32::max_value() as u32); assert!(columns.len() == values.len()); let n_columns = ffi::gtk_tree_model_get_n_...
{ assert_initialized_main_thread!(); unsafe { let mut column_types = column_types.iter().map(|t| t.to_glib()).collect::<Vec<_>>(); from_glib_full( ffi::gtk_list_store_newv(column_types.len() as c_int, column_types.as_mut_ptr())) } }
identifier_body
list_store.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::translate::*; use glib::{Type, ToValue, Value}; use libc::c_int; use std::...
let type_ = from_glib( ffi::gtk_tree_model_get_column_type(self.to_glib_none().0, column as c_int)); assert!(Value::type_transformable(value.to_value_type(), type_)); } let mut iter = TreeIter::uninitialized(); ffi::gtk_list_store_i...
assert!(columns.len() <= n_columns as usize); for (&column, value) in columns.iter().zip(values.iter()) { assert!(column < n_columns);
random_line_split
util.rs
use image::{ mod, ImageResult, RgbaImage, }; use std::collections::{HashSet, HashMap}; use std::fmt::{mod, Show, Formatter}; use std::thread::Thread; pub fn
<T, E>(result: Result<T, E>) where E: Show { if let Err(err) = result { println!("Encountered nonfatal error: {}", err); } } #[deriving(Copy)] pub struct FormatBytes(pub u64); impl FormatBytes { #[inline] fn to_kb(self) -> f64 { (self.0 as f64) / 1.0e3 } #[inline] ...
print_err
identifier_name
util.rs
use image::{ mod, ImageResult, RgbaImage, }; use std::collections::{HashSet, HashMap}; use std::fmt::{mod, Show, Formatter}; use std::thread::Thread; pub fn print_err<T, E>(result: Result<T, E>) where E: Show
#[deriving(Copy)] pub struct FormatBytes(pub u64); impl FormatBytes { #[inline] fn to_kb(self) -> f64 { (self.0 as f64) / 1.0e3 } #[inline] fn to_mb(self) -> f64 { (self.0 as f64) / 1.0e6 } #[inline] fn to_gb(self) -> f64 { (self.0 as f64) / 1.0e9 } }...
{ if let Err(err) = result { println!("Encountered nonfatal error: {}", err); } }
identifier_body
util.rs
use image::{ mod, ImageResult, RgbaImage, }; use std::collections::{HashSet, HashMap}; use std::fmt::{mod, Show, Formatter}; use std::thread::Thread; pub fn print_err<T, E>(result: Result<T, E>) where E: Show { if let Err(err) = result { println!("Encountered nonfatal error: {}", err); ...
} pub fn begin_load(&mut self, path: &Path) { self.waiting.insert(path.clone()); self.in_tx.send(path.clone()); } fn rollup_results(&mut self) { while let Ok((path, result)) = self.out_rx.try_recv() { self.waiting.remove(&path); self.read...
out_rx: out_rx, }
random_line_split
object-lifetime-default-from-ref-struct.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 ...
<'a>(t: Ref<'a,Test+'a>, mut ss: SomeStruct<'a>) { ss.u = t; } fn e<'a>(_: Ref<'a, Display+'static>) {} fn g<'a, 'b>(_: Ref2<'a, 'b, Display+'static>) {} fn main() { // Inside a function body, we can just infer all // lifetimes, to allow Ref<'tmp, Display+'static> // and Ref2<'tmp, 'tmp, Display+'sta...
d
identifier_name
object-lifetime-default-from-ref-struct.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 ...
#![allow(dead_code)] use std::fmt::Display; trait Test { fn foo(&self) { } } struct Ref<'a,T:'a+?Sized> { r: &'a T } struct Ref2<'a,'b,T:'a+'b+?Sized> { a: &'a T, b: &'b T } struct SomeStruct<'a> { t: Ref<'a,Test>, u: Ref<'a,Test+'a>, } fn a<'a>(t: Ref<'a,Test>, mut ss: SomeStruct<'a>) { ...
// run-pass // Test that the lifetime of the enclosing `&` is used for the object // lifetime bound. // pretty-expanded FIXME #23616
random_line_split
object-lifetime-default-from-ref-struct.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 ...
fn d<'a>(t: Ref<'a,Test+'a>, mut ss: SomeStruct<'a>) { ss.u = t; } fn e<'a>(_: Ref<'a, Display+'static>) {} fn g<'a, 'b>(_: Ref2<'a, 'b, Display+'static>) {} fn main() { // Inside a function body, we can just infer all // lifetimes, to allow Ref<'tmp, Display+'static> // and Ref2<'tmp, 'tmp, Displa...
{ ss.t = t; }
identifier_body
dir.rs
use errors::{Error, Result}; use failure::ResultExt; use mkdirp::mkdirp as _mkdirp; use std::env; use std::path::{Path, PathBuf}; pub fn resolve(path: PathBuf) -> Result<PathBuf> { let path = env::current_dir() .map(|mut p| { p.push(path.to_path_buf()); p }) .map_err(E...
#[test] fn mkdirp_non_existing() { let path = TempDir::new("existing-dir") .map(|dir| dir.into_path().join("non-existing")) .unwrap(); assert_eq!(path.exists(), false); assert!(mkdirp(&path).is_ok()); assert!(path.exists()); } }
assert!(mkdirp(&path).is_ok()); assert!(path.exists()); }
random_line_split
dir.rs
use errors::{Error, Result}; use failure::ResultExt; use mkdirp::mkdirp as _mkdirp; use std::env; use std::path::{Path, PathBuf}; pub fn resolve(path: PathBuf) -> Result<PathBuf> { let path = env::current_dir() .map(|mut p| { p.push(path.to_path_buf()); p }) .map_err(E...
}
{ let path = TempDir::new("existing-dir") .map(|dir| dir.into_path().join("non-existing")) .unwrap(); assert_eq!(path.exists(), false); assert!(mkdirp(&path).is_ok()); assert!(path.exists()); }
identifier_body
dir.rs
use errors::{Error, Result}; use failure::ResultExt; use mkdirp::mkdirp as _mkdirp; use std::env; use std::path::{Path, PathBuf}; pub fn resolve(path: PathBuf) -> Result<PathBuf> { let path = env::current_dir() .map(|mut p| { p.push(path.to_path_buf()); p }) .map_err(E...
() { let path = TempDir::new("existing-dir") .map(|dir| dir.into_path().join("non-existing")) .unwrap(); assert_eq!(path.exists(), false); assert!(mkdirp(&path).is_ok()); assert!(path.exists()); } }
mkdirp_non_existing
identifier_name
move-arg-2-unique.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 ...
(foo: Box<Vec<isize>> ) { assert!(((*foo)[0] == 10)); } pub fn main() { let x = box vec!(10); // Test forgetting a local by move-in test(x); // Test forgetting a temporary by move-in. test(box vec!(10)); }
test
identifier_name
move-arg-2-unique.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 = box vec!(10); // Test forgetting a local by move-in test(x); // Test forgetting a temporary by move-in. test(box vec!(10)); }
{ assert!(((*foo)[0] == 10)); }
identifier_body
move-arg-2-unique.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
random_line_split
send-resource.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 (tx, rx) = channel(); let _t = Thread::spawn(move|| { let (tx2, rx2) = channel(); tx.send(tx2).unwrap(); let _r = rx2.recv().unwrap(); }); rx.recv().unwrap().send(test(42)).unwrap(); }
identifier_body
send-resource.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 ...
(&mut self) {} } fn test(f: int) -> test { test { f: f } } pub fn main() { let (tx, rx) = channel(); let _t = Thread::spawn(move|| { let (tx2, rx2) = channel(); tx.send(tx2).unwrap(); let _r = rx2.recv().unwrap(); }); rx.recv().unwrap().send(test(42)).unwrap(...
drop
identifier_name
send-resource.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 ...
use std::thread::Thread; use std::sync::mpsc::channel; struct test { f: int, } impl Drop for test { fn drop(&mut self) {} } fn test(f: int) -> test { test { f: f } } pub fn main() { let (tx, rx) = channel(); let _t = Thread::spawn(move|| { let (tx2, rx2) = channel(); ...
// except according to those terms.
random_line_split
mod.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. //! This mod contains components to support rapid data import with the project //! `tidb-lightning`. //! //! It mainly exposes one service: //! //! The `ImportSSTService` is used to ingest the generated SST files into TiKV's //! RocksDB instance. The i...
<E: Debug>(err: E) -> RpcStatus { // FIXME: Just spewing debug error formatting here seems pretty unfriendly RpcStatus::with_message(RpcStatusCode::UNKNOWN, format!("{:?}", err)) } #[macro_export] macro_rules! send_rpc_response { ($res:ident, $sink:ident, $label:ident, $timer:ident) => {{ let res =...
make_rpc_error
identifier_name
mod.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. //! This mod contains components to support rapid data import with the project //! `tidb-lightning`. //! //! It mainly exposes one service: //! //! The `ImportSSTService` is used to ingest the generated SST files into TiKV's //! RocksDB instance. The i...
#[macro_export] macro_rules! send_rpc_response { ($res:ident, $sink:ident, $label:ident, $timer:ident) => {{ let res = match $res { Ok(resp) => { IMPORT_RPC_DURATION .with_label_values(&[$label, "ok"]) .observe($timer.saturating_elapsed_sec...
{ // FIXME: Just spewing debug error formatting here seems pretty unfriendly RpcStatus::with_message(RpcStatusCode::UNKNOWN, format!("{:?}", err)) }
identifier_body
mod.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. //! This mod contains components to support rapid data import with the project //! `tidb-lightning`. //! //! It mainly exposes one service: //! //! The `ImportSSTService` is used to ingest the generated SST files into TiKV's //! RocksDB instance. The i...
macro_rules! send_rpc_response { ($res:ident, $sink:ident, $label:ident, $timer:ident) => {{ let res = match $res { Ok(resp) => { IMPORT_RPC_DURATION .with_label_values(&[$label, "ok"]) .observe($timer.saturating_elapsed_secs()); ...
#[macro_export]
random_line_split
htmltablerowelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::{Attr, AttrHelpers}; use dom::bindings::codegen::Bindings::HTMLTableRowElementBinding; use dom::bin...
(self) -> Option<RGBA> { self.background_color.get() } } impl<'a> VirtualMethods for &'a HTMLTableRowElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) ...
get_background_color
identifier_name
htmltablerowelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::{Attr, AttrHelpers}; use dom::bindings::codegen::Bindings::HTMLTableRowElementBinding; use dom::bin...
} impl<'a> VirtualMethods for &'a HTMLTableRowElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: &Attr) { if let Some...
{ self.background_color.get() }
identifier_body
htmltablerowelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::{Attr, AttrHelpers}; use dom::bindings::codegen::Bindings::HTMLTableRowElementBinding; use dom::bin...
} } pub trait HTMLTableRowElementHelpers { fn get_background_color(self) -> Option<RGBA>; } impl<'a> HTMLTableRowElementHelpers for &'a HTMLTableRowElement { fn get_background_color(self) -> Option<RGBA> { self.background_color.get() } } impl<'a> VirtualMethods for &'a HTMLTableRowElement { ...
random_line_split
htmltablerowelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::{Attr, AttrHelpers}; use dom::bindings::codegen::Bindings::HTMLTableRowElementBinding; use dom::bin...
match attr.local_name() { &atom!("bgcolor") => { self.background_color.set(str::parse_legacy_color(&attr.value()).ok()); }, _ => () } } fn before_remove_attr(&self, attr: &Attr) { if let Some(ref s) = self.super_type() { ...
{ s.after_set_attr(attr); }
conditional_block
asm.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...
match s { Asm => Some(Outputs), Outputs => Some(Inputs), Inputs => Some(Clobbers), Clobbers => Some(Options), Options => None } } pub fn expand_asm(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) -> base::MacResult { let p = parse::new_parser...
Clobbers, Options } fn next_state(s: State) -> Option<State> {
random_line_split
asm.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...
(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) -> base::MacResult { let p = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_owned()); let mut asm = @""; let mut asm_str_style = None; let mut out...
expand_asm
identifier_name
htmlprogresselement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLProgressElementBinding::{ self, HTMLProgressElementMethods, ...
make_labels_getter!(Labels, labels_node_list); }
impl HTMLProgressElementMethods for HTMLProgressElement { // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
random_line_split
htmlprogresselement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLProgressElementBinding::{ self, HTMLProgressElementMethods, ...
} impl HTMLProgressElementMethods for HTMLProgressElement { // https://html.spec.whatwg.org/multipage/#dom-lfe-labels make_labels_getter!(Labels, labels_node_list); }
{ Node::reflect_node( Box::new(HTMLProgressElement::new_inherited( local_name, prefix, document, )), document, HTMLProgressElementBinding::Wrap, ) }
identifier_body
htmlprogresselement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLProgressElementBinding::{ self, HTMLProgressElementMethods, ...
( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLProgressElement { HTMLProgressElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), labels_node_list: MutNullableDom::new(None), } } #[al...
new_inherited
identifier_name
garbage.rs
//! Data structure for storing garbage use alloc::heap; use std::ptr; use std::mem; use std::sync::atomic::AtomicPtr; use std::sync::atomic::Ordering::{Relaxed, Release}; /// One item of garbage. /// /// Stores enough information to do a deallocation. struct Item { ptr: *mut u8, size: usize, align: usize...
<T>(&mut self, elem: *mut T) { self.new.insert(elem) } /// Collect one epoch of garbage, rotating the local garbage bags. pub unsafe fn collect(&mut self) { let ret = self.old.collect(); mem::swap(&mut self.old, &mut self.cur); mem::swap(&mut self.cur, &mut self.new); ...
reclaim
identifier_name
garbage.rs
//! Data structure for storing garbage use alloc::heap; use std::ptr; use std::mem; use std::sync::atomic::AtomicPtr; use std::sync::atomic::Ordering::{Relaxed, Release}; /// One item of garbage. /// /// Stores enough information to do a deallocation. struct Item { ptr: *mut u8, size: usize, align: usize...
if self.head.compare_and_swap(head, n, Release) == head { break } } } pub unsafe fn collect(&self) { let mut head = self.head.load(Relaxed); self.head.store(ptr::null_mut(), Relaxed); while head!= ptr::null_mut() { let mut n = Box::from_raw(head); ...
unsafe { (*n).next.store(head, Relaxed) };
random_line_split
garbage.rs
//! Data structure for storing garbage use alloc::heap; use std::ptr; use std::mem; use std::sync::atomic::AtomicPtr; use std::sync::atomic::Ordering::{Relaxed, Release}; /// One item of garbage. /// /// Stores enough information to do a deallocation. struct Item { ptr: *mut u8, size: usize, align: usize...
} fn len(&self) -> usize { self.0.len() } /// Deallocate all garbage in the bag pub unsafe fn collect(&mut self) { for item in self.0.drain(..) { heap::deallocate(item.ptr, item.size, item.align); } } } // needed because the bags store raw pointers. unsafe...
{ self.0.push(Item { ptr: elem as *mut u8, size: size, align: mem::align_of::<T>(), }) }
conditional_block
lib.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity.
// (at your option) any later version. // Parity 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. // You should have received a copy of t...
// Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or
random_line_split
str_to_string.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 rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext}; use rustc::middle::ty; use rustc_f...
match walk_ty(cx.tcx.expr_ty(expr)).sty { ty::TyStr => true, _ => false } } } }
{ match ty.sty { ty::TyRef(_, ref tm) | ty::TyRawPtr(ref tm) => walk_ty(tm.ty), _ => ty } }
identifier_body
str_to_string.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 rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext}; use rustc::middle::ty; use rustc_f...
fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) { match expr.node { hir::ExprMethodCall(ref method, _, ref args) if method.node.as_str() == "to_string" && is_str(cx, &*args[0]) => { cx.span_lint(STR_TO_STRING, expr.span, ...
impl LateLintPass for StrToStringPass {
random_line_split
str_to_string.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 rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext}; use rustc::middle::ty; use rustc_f...
(&mut self, cx: &LateContext, expr: &hir::Expr) { match expr.node { hir::ExprMethodCall(ref method, _, ref args) if method.node.as_str() == "to_string" && is_str(cx, &*args[0]) => { cx.span_lint(STR_TO_STRING, expr.span, "s...
check_expr
identifier_name
vulkan_ctx.rs
extern crate vulkano; use grid; use scene; use std::path::Path; use std::sync::Arc; use tracers::{RaycastingShader, Tracer}; pub struct VulkanCtx<'a> { pub physical: vulkano::instance::PhysicalDevice<'a>, pub device: Arc<vulkano::device::Device>, pub queue: Arc<vulkano::device::Queue>, pub scene_buff...
scene_buffers, grid_builder, tracer, }, load_future, ) } }
VulkanCtx { physical, device, queue,
random_line_split
vulkan_ctx.rs
extern crate vulkano; use grid; use scene; use std::path::Path; use std::sync::Arc; use tracers::{RaycastingShader, Tracer}; pub struct
<'a> { pub physical: vulkano::instance::PhysicalDevice<'a>, pub device: Arc<vulkano::device::Device>, pub queue: Arc<vulkano::device::Queue>, pub scene_buffers: scene::ModelBuffers, pub grid_builder: grid::GridBuilder, pub tracer: Tracer<RaycastingShader>, } impl<'a> VulkanCtx<'a> { pub fn ...
VulkanCtx
identifier_name
build.rs
#![feature(env, fs, io, path, process)] use std::env; use std::path::Path; use std::process::Command; use std::fs::File; use std::io::Write; fn main() { let src_dir_str = env::var_os("CARGO_MANIFEST_DIR").unwrap(); let src_dir = Path::new(&src_dir_str); let dst_dir_str = env::var_os("OUT_DIR").unwrap(); let dst...
panic!("nonzero exit status: {}", status); } } fn get_output(cmd: &mut Command) -> String { let output = match cmd.output() { Ok(output) => output, Err(e) => panic!("failed to spawn process: {}", e), }; if!output.status.success() { panic!("nonzero exit status: {}", output.status); } String::from_utf8(o...
Err(e) => panic!("failed to spawn process: {}", e), }; if !status.success() {
random_line_split
build.rs
#![feature(env, fs, io, path, process)] use std::env; use std::path::Path; use std::process::Command; use std::fs::File; use std::io::Write; fn
() { let src_dir_str = env::var_os("CARGO_MANIFEST_DIR").unwrap(); let src_dir = Path::new(&src_dir_str); let dst_dir_str = env::var_os("OUT_DIR").unwrap(); let dst_dir = Path::new(&dst_dir_str); let compiler = env::var("CC").unwrap_or("gcc".to_string()); let executable = dst_dir.join("rust-constants"); let ...
main
identifier_name
build.rs
#![feature(env, fs, io, path, process)] use std::env; use std::path::Path; use std::process::Command; use std::fs::File; use std::io::Write; fn main()
let output = get_output(&mut Command::new(&executable)); let mut f = File::create(&rust_dst).unwrap(); f.write_all(output.as_bytes()).unwrap(); } fn run(cmd: &mut Command) { let status = match cmd.status() { Ok(status) => status, Err(e) => panic!("failed to spawn process: {}", e), }; if!status.success() { ...
{ let src_dir_str = env::var_os("CARGO_MANIFEST_DIR").unwrap(); let src_dir = Path::new(&src_dir_str); let dst_dir_str = env::var_os("OUT_DIR").unwrap(); let dst_dir = Path::new(&dst_dir_str); let compiler = env::var("CC").unwrap_or("gcc".to_string()); let executable = dst_dir.join("rust-constants"); let c_s...
identifier_body
mod.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/. */ //! Adapter for `WebPush`. //! //! Implemented as described in the draft IETF RFC: //! https://tools.ietf.org/html...
}; info!("notified subscription {} (status {:?})", push_uri, rsp.status); } } pub struct WebPush<C> { controller: C, crypto: CryptoContext, channel_resource_id: Id<Channel>, channel_subscribe_id: Id<Channel>, channel_unsubscribe_id: Id<Channel>, channel_notify_id: Id<Channe...
// TODO: Add a retry mechanism if 429 Too Many Requests returned by push service let rsp = match req.send() { Ok(x) => x, Err(e) => { warn!("notify subscription {} failed: {:?}", push_uri, e); return; }
random_line_split
mod.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/. */ //! Adapter for `WebPush`. //! //! Implemented as described in the draft IETF RFC: //! https://tools.ietf.org/html...
(&self, user_id: i32, setter: &SubscriptionGetter) -> rusqlite::Result<()> { let db = self.get_db(); for sub in &setter.subscriptions { try!(db.unsubscribe(user_id, &sub.push_uri)); } Ok(()) } fn set_resources(&self, user_id: i32, setter: &ResourceGetter) -> rusqlite...
set_unsubscribe
identifier_name
mod.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/. */ //! Adapter for `WebPush`. //! //! Implemented as described in the draft IETF RFC: //! https://tools.ietf.org/html...
fn name(&self) -> &str { ADAPTER_NAME } fn vendor(&self) -> &str { ADAPTER_VENDOR } fn version(&self) -> &[u32;4] { &ADAPTER_VERSION } fn fetch_values(&self, mut set: Vec<Id<Channel>>, user: User) -> ResultMap<Id<Channel>, Option<Value>, Error> { set.drai...
{ Self::id() }
identifier_body
kxnorb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*;
fn kxnorb_2() { run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K4)), operand2: Some(Direct(K6)), operand3: Some(Direct(K1)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 205, 70, 225], OperandSize::Qword) }
fn kxnorb_1() { run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K5)), operand3: Some(Direct(K5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 213, 70, 205], OperandSize::Dword) }
random_line_split
kxnorb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn
() { run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K5)), operand3: Some(Direct(K5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 213, 70, 205], OperandSize::Dword) } fn kxnorb_2() { ...
kxnorb_1
identifier_name
kxnorb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn kxnorb_1()
fn kxnorb_2() { run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K4)), operand2: Some(Direct(K6)), operand3: Some(Direct(K1)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 205, 70, 225], OperandSize::Qword) }
{ run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K5)), operand3: Some(Direct(K5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 213, 70, 205], OperandSize::Dword) }
identifier_body
Option.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub enum Option<T> { // /// No value // #[stable(feature = "rust1", since = "1.0.0")] // None, ...
} }
random_line_split
Option.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub enum Option<T> { // /// No value // #[stable(feature = "rust1", since = "1.0.0")] // None, ...
() { let x: Option<T> = None::<T>; match x { Some(_) => { assert!(false); } None => { assert!(true); } } } }
Option_test2
identifier_name
Option.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub enum Option<T> { // /// No value // #[stable(feature = "rust1", since = "1.0.0")] // None, ...
#[test] #[allow(non_snake_case)] fn Option_test2() { let x: Option<T> = None::<T>; match x { Some(_) => { assert!(false); } None => { assert!(true); } } } }
{ let x: Option<T> = Some::<T>(2); match x { Some(z) => { assert_eq!(z, 2); } None => { assert!(false); } } }
identifier_body
test_regalloc.rs
//! Test command for testing the register allocator. //! //! The `regalloc` test command runs each function through the register allocator after ensuring //! that all instructions are legal for the target. //! //! The resulting function is sent to `filecheck`. use crate::subtest::{run_filecheck, Context, SubTest, Subt...
(&self) -> bool { true } fn run(&self, func: Cow<Function>, context: &Context) -> SubtestResult<()> { let isa = context.isa.expect("register allocator needs an ISA"); let mut comp_ctx = cranelift_codegen::Context::for_function(func.into_owned()); comp_ctx.compute_cfg(); ...
needs_isa
identifier_name
test_regalloc.rs
//! Test command for testing the register allocator. //! //! The `regalloc` test command runs each function through the register allocator after ensuring //! that all instructions are legal for the target. //! //! The resulting function is sent to `filecheck`. use crate::subtest::{run_filecheck, Context, SubTest, Subt...
else { Ok(Box::new(TestRegalloc)) } } impl SubTest for TestRegalloc { fn name(&self) -> &'static str { "regalloc" } fn is_mutating(&self) -> bool { true } fn needs_isa(&self) -> bool { true } fn run(&self, func: Cow<Function>, context: &Context) -> Su...
{ Err(format!("No options allowed on {}", parsed)) }
conditional_block
test_regalloc.rs
//! Test command for testing the register allocator. //! //! The `regalloc` test command runs each function through the register allocator after ensuring //! that all instructions are legal for the target. //! //! The resulting function is sent to `filecheck`. use crate::subtest::{run_filecheck, Context, SubTest, Subt...
impl SubTest for TestRegalloc { fn name(&self) -> &'static str { "regalloc" } fn is_mutating(&self) -> bool { true } fn needs_isa(&self) -> bool { true } fn run(&self, func: Cow<Function>, context: &Context) -> SubtestResult<()> { let isa = context.isa.expe...
random_line_split
oauth2.rs
use rustc_serialize::json; use datatype::{AccessToken, Error, Url}; use http::{Client, Response}; /// Authenticate with the specified OAuth2 server to retrieve a new `AccessToken`. pub fn authenticate(server: Url, client: &Client) -> Result<AccessToken, Error> { debug!("authenticating at {}", server); let re...
let client = TestClient::from(vec![r#"{"apa": 1}"#.to_string()]); let expect = r#"Failed to decode JSON: MissingFieldError("access_token")"#; assert_eq!(expect, format!("{}", authenticate(test_server(), &client).unwrap_err())); } }
#[test] fn test_authenticate_bad_json() {
random_line_split
oauth2.rs
use rustc_serialize::json; use datatype::{AccessToken, Error, Url}; use http::{Client, Response}; /// Authenticate with the specified OAuth2 server to retrieve a new `AccessToken`. pub fn authenticate(server: Url, client: &Client) -> Result<AccessToken, Error> { debug!("authenticating at {}", server); let re...
() { let client = TestClient::from(vec![r#"{"apa": 1}"#.to_string()]); let expect = r#"Failed to decode JSON: MissingFieldError("access_token")"#; assert_eq!(expect, format!("{}", authenticate(test_server(), &client).unwrap_err())); } }
test_authenticate_bad_json
identifier_name
oauth2.rs
use rustc_serialize::json; use datatype::{AccessToken, Error, Url}; use http::{Client, Response}; /// Authenticate with the specified OAuth2 server to retrieve a new `AccessToken`. pub fn authenticate(server: Url, client: &Client) -> Result<AccessToken, Error> { debug!("authenticating at {}", server); let re...
#[test] fn test_authenticate() { let token = r#"{ "access_token": "token", "token_type": "type", "expires_in": 10, "scope": "scope1 scope2" }"#; let client = TestClient::from(vec![token.to_string()]); let expect = AccessToken { ...
{ "http://localhost:8000".parse().unwrap() }
identifier_body
area.rs
use xpath_reader::{FromXml, Error, Reader}; use crate::entities::{Mbid, Resource}; use crate::client::Request; enum_mb_xml! { /// Specifies what a specific `Area` instance actually is. pub enum AreaType { /// Areas included (or previously included) in ISO 3166-1. var Country = "Country", ...
(response: Self::Response, _: Self::Options) -> Self { Area { response } } } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn area_read_xml1() { let mbid = Mbid::from_str("a1411661-be21-4290-8dc1-50f3d8e3ea67").unwrap(); let area: Area = crate::util:...
from_response
identifier_name
area.rs
use xpath_reader::{FromXml, Error, Reader}; use crate::entities::{Mbid, Resource}; use crate::client::Request; enum_mb_xml! { /// Specifies what a specific `Area` instance actually is. pub enum AreaType { /// Areas included (or previously included) in ISO 3166-1. var Country = "Country", ...
/// Type of the area, gives more information about pub fn area_type(&self) -> AreaType { self.response.area_type.clone() } /// ISO 3166 code, assigned to countries and subdivisions. pub fn iso_3166(&self) -> Option<&String> { self.response.iso_3166.as_ref() } } impl FromXml f...
{ &self.response.sort_name }
identifier_body
area.rs
use xpath_reader::{FromXml, Error, Reader}; use crate::entities::{Mbid, Resource}; use crate::client::Request; enum_mb_xml! { /// Specifies what a specific `Area` instance actually is. pub enum AreaType { /// Areas included (or previously included) in ISO 3166-1. var Country = "Country", ...
sort_name: String, area_type: AreaType, iso_3166: Option<String>, } impl Area { /// MBID of the entity in the MusicBrainz database. pub fn mbid(&self) -> &Mbid { &self.response.mbid } /// The name of the area. pub fn name(&self) -> &String { &self.response.name } ...
#[derive(Clone, Debug, Eq, PartialEq)] pub struct AreaResponse { mbid: Mbid, name: String,
random_line_split
lib.rs
#![feature(old_io)] //! This test file mostly just has tests that make sure that the macros successfully compile. extern crate fern; #[macro_use] extern crate fern_macros; use std::sync; #[test] fn
() { fern::local::set_thread_logger(sync::Arc::new( Box::new(fern::NullLogger) as fern::BoxedLogger)); log!(&fern::Level::Info, "expected info message"); } #[test] fn test_levels() { fern::local::set_thread_logger(sync::Arc::new( Box::new(fern::NullLogger) as fern::BoxedLogger)); debug!...
test_log
identifier_name
lib.rs
#![feature(old_io)] //! This test file mostly just has tests that make sure that the macros successfully compile. extern crate fern; #[macro_use] extern crate fern_macros; use std::sync; #[test] fn test_log() { fern::local::set_thread_logger(sync::Arc::new( Box::new(fern::NullLogger) as fern::BoxedLogger...
#[test] fn test_error_then_with_error() { fern::local::set_thread_logger(sync::Arc::new( Box::new(fern::NullLogger) as fern::BoxedLogger)); log_error_then!(errors(), return, "expected error: {e:?}"); panic!("Should have returned!"); } #[test] fn test_error_then_without_error() { fern::local::s...
random_line_split
lib.rs
#![feature(old_io)] //! This test file mostly just has tests that make sure that the macros successfully compile. extern crate fern; #[macro_use] extern crate fern_macros; use std::sync; #[test] fn test_log() { fern::local::set_thread_logger(sync::Arc::new( Box::new(fern::NullLogger) as fern::BoxedLogger...
#[test] fn test_error_logging() { fern::local::set_thread_logger(sync::Arc::new( Box::new(fern::NullLogger) as fern::BoxedLogger)); log_error!(errors(), "expected error: {e:?}"); log_error!(does_not_error(), "unexpected error!: {e:?}"); } #[test] fn test_error_then_with_error() { fern::local:...
{ Err("expected severe message".to_string()) }
identifier_body
event.rs
use std::mem; use crate::syntax::SyntaxKind; use crate::{ParseError, TreeSink}; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum Event { BeginMarker, Begin(SyntaxKind, Option<usize>), Leaf(SyntaxKind), End, Error, Tombstone, } pub fn process(sink: &mut dyn TreeSink, mut events: Vec<Event...
forward_parents.push(kind); forward_parent } Event::Tombstone => None, e => unreachable!("found unresolved {:#?} at position {}", e, parent_idx), }; } ...
random_line_split
event.rs
use std::mem; use crate::syntax::SyntaxKind; use crate::{ParseError, TreeSink}; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum Event { BeginMarker, Begin(SyntaxKind, Option<usize>), Leaf(SyntaxKind), End, Error, Tombstone, } pub fn
(sink: &mut dyn TreeSink, mut events: Vec<Event>) { let mut forward_parents = Vec::new(); for i in 0..events.len() { match mem::replace(&mut events[i], Event::Tombstone) { Event::BeginMarker | Event::Tombstone => {} Event::Begin(kind, forward_parent) => { // For ...
process
identifier_name
cc.rs
//! Algorithm 4.3: Depth-first search to find connected components in a graph. use super::Graph; pub struct ConnectedComponents { id: Vec<usize>, count: usize, } impl ConnectedComponents { /// Find connected components with depth-first search. pub fn find(g: &Graph) -> ConnectedComponents { ...
assert!( ! cc.connected(1, 12)); } }
random_line_split
cc.rs
//! Algorithm 4.3: Depth-first search to find connected components in a graph. use super::Graph; pub struct ConnectedComponents { id: Vec<usize>, count: usize, } impl ConnectedComponents { /// Find connected components with depth-first search. pub fn find(g: &Graph) -> ConnectedComponents { ...
} } /// Check if node `v` and node `w` in the graph are connected. pub fn connected(&self, v: usize, w: usize) -> bool { return self.id[v] == self.id[w]; } } #[cfg(test)] mod test { use super::ConnectedComponents; use super::super::Graph; use super::super::test::sample_gr...
{ self.dfs(g, marked, w); }
conditional_block
cc.rs
//! Algorithm 4.3: Depth-first search to find connected components in a graph. use super::Graph; pub struct ConnectedComponents { id: Vec<usize>, count: usize, } impl ConnectedComponents { /// Find connected components with depth-first search. pub fn find(g: &Graph) -> ConnectedComponents { ...
/// Check if node `v` and node `w` in the graph are connected. pub fn connected(&self, v: usize, w: usize) -> bool { return self.id[v] == self.id[w]; } } #[cfg(test)] mod test { use super::ConnectedComponents; use super::super::Graph; use super::super::test::sample_graph; #[test...
{ marked[v] = true; self.id[v] = self.count; let neighbors = g.adj[v].clone(); for w in neighbors { if ! marked[w] { self.dfs(g, marked, w); } } }
identifier_body
cc.rs
//! Algorithm 4.3: Depth-first search to find connected components in a graph. use super::Graph; pub struct ConnectedComponents { id: Vec<usize>, count: usize, } impl ConnectedComponents { /// Find connected components with depth-first search. pub fn find(g: &Graph) -> ConnectedComponents { ...
() { let mut g = Graph::new(3); g.add_edge(0, 1); g.add_edge(0, 2); g.add_edge(1, 2); let cc = ConnectedComponents::find(&g); assert_eq!(1, cc.count); assert!(cc.connected(0, 1)); assert!(cc.connected(0, 2)); assert!(cc.connected(1, 2)); } ...
works_for_complete_graph
identifier_name
xchacha20poly1305.rs
// Copyright 2017, 2019 Guanhao Yin <sopium@mysterious.site> // This file is part of TiTun. // TiTun is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) ...
} fn hchacha_fallback(key: &[u8; 32], nonce: &[u8; 16]) -> [u8; 32] { hchacha_real(key, nonce, BaselineMachine::new()) } hchacha_fallback(key, nonce) } pub fn encrypt(key: &[u8], nonce: &[u8], ad: &[u8], p: &[u8], out: &mut [u8]) { assert_eq!(key.len(), 32); assert_eq!(nonce.len(), 24)...
{ #[target_feature(enable = "ssse3")] unsafe fn hchacha_ssse3(key: &[u8; 32], nonce: &[u8; 16]) -> [u8; 32] { use super::simd::SSSE3Machine; hchacha_real(key, nonce, SSSE3Machine::new()) } unsafe { return hchacha_ssse3(key, ...
conditional_block
xchacha20poly1305.rs
// Copyright 2017, 2019 Guanhao Yin <sopium@mysterious.site> // This file is part of TiTun. // TiTun is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) ...
u32x4::load_le(key[..16].try_into().unwrap()), u32x4::load_le(key[16..].try_into().unwrap()), u32x4::load_le(nonce), ]; for _ in 0..10 { round_pair(&mut state, m); } let mut out = [0u8; 32]; state[0].store_le((&mut out[..16]).try_into().unwrap()); state[3].store...
fn hchacha_real<M: Machine>(key: &[u8; 32], nonce: &[u8; 16], m: M) -> [u8; 32] { #[allow(clippy::unreadable_literal)] let mut state: [u32x4; 4] = [ u32x4::new(0x61707865, 0x3320646e, 0x79622d32, 0x6b206574),
random_line_split
xchacha20poly1305.rs
// Copyright 2017, 2019 Guanhao Yin <sopium@mysterious.site> // This file is part of TiTun. // TiTun is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) ...
(key: &[u8; 32], nonce: &[u8; 16]) -> [u8; 32] { #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { if is_x86_feature_detected!("ssse3") { #[target_feature(enable = "ssse3")] unsafe fn hchacha_ssse3(key: &[u8; 32], nonce: &[u8; 16]) -> [u8; 32] { use super...
hchacha
identifier_name
xchacha20poly1305.rs
// Copyright 2017, 2019 Guanhao Yin <sopium@mysterious.site> // This file is part of TiTun. // TiTun is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) ...
#[inline(always)] fn unshuffle(state: &mut [u32x4; 4]) { state[0] = state[0].shuffle_right(1); state[1] = state[1].shuffle_right(2); state[2] = state[2].shuffle_right(3); } #[inline(always)] fn round_pair<M: Machine>(state: &mut [u32x4; 4], m: M) { round(state, m); shuffle(state); round(state...
{ state[0] = state[0].shuffle_left(1); state[1] = state[1].shuffle_left(2); state[2] = state[2].shuffle_left(3); }
identifier_body
error.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 detail(&self) -> Option<String> { Some(self.to_string()) } } #[stable] impl Error for FromUtf8Error { fn description(&self) -> &str { "invalid utf-8" } fn detail(&self) -> Option<String> { Some(self.to_string()) } } #[stable] impl Error for FromUtf16Error { fn description(&self) -> &str { "invali...
{ match *self { Utf8Error::TooShort => "invalid utf-8: not enough bytes", Utf8Error::InvalidByte(..) => "invalid utf-8: corrupt contents", } }
identifier_body
error.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 ...
(&self) -> Option<&Error> { None } } /// A trait for types that can be converted from a given error type `E`. #[stable] pub trait FromError<E> { /// Perform the conversion. fn from_error(err: E) -> Self; } // Any type is convertable from itself #[stable] impl<E> FromError<E> for E { fn from_error(err: E) ...
cause
identifier_name
error.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 ...
/// A trait for types that can be converted from a given error type `E`. #[stable] pub trait FromError<E> { /// Perform the conversion. fn from_error(err: E) -> Self; } // Any type is convertable from itself #[stable] impl<E> FromError<E> for E { fn from_error(err: E) -> E { err } } #[stable] ...
/// The lower-level cause of this error, if any. fn cause(&self) -> Option<&Error> { None } }
random_line_split
generic-box.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: @Box<int> = box_it::<int>(Box{x: 1, y: 2, z: 3}); assert_eq!(x.y, 2); }
identifier_body
generic-box.rs
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
random_line_split
generic-box.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 ...
<T> {x: T, y: T, z: T} pub fn main() { let x: @Box<int> = box_it::<int>(Box{x: 1, y: 2, z: 3}); assert_eq!(x.y, 2); }
Box
identifier_name
build.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 ...
(host: &str, target: &str) -> Result<(), ()> { let native = native_lib_boilerplate("libbacktrace", "libbacktrace", "backtrace", ".libs")?; run(Command::new("sh") .current_dir(&native.out_dir) .arg(native.src_dir.join("configure").to_str().unwrap() ...
build_libbacktrace
identifier_name
build.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 ...
println!("cargo:rustc-link-lib=posix4"); println!("cargo:rustc-link-lib=pthread"); println!("cargo:rustc-link-lib=resolv"); } else if target.contains("apple-darwin") { println!("cargo:rustc-link-lib=System"); // res_init and friends require -lresolv on macOS/iOS. // ...
} else if target.contains("solaris") { println!("cargo:rustc-link-lib=socket");
random_line_split
build.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 ...
println!("cargo:rustc-link-lib=rt"); println!("cargo:rustc-link-lib=pthread"); } } else if target.contains("freebsd") { println!("cargo:rustc-link-lib=execinfo"); println!("cargo:rustc-link-lib=pthread"); } else if target.contains("dragonfly") || target.contains("...
{ let target = env::var("TARGET").expect("TARGET was not set"); let host = env::var("HOST").expect("HOST was not set"); if cfg!(feature = "backtrace") && !target.contains("cloudabi") && !target.contains("emscripten") && !target.contains("fuchsia") && !target.contains("msvc") ...
identifier_body
github.rs
//! Implements talking to the Github API use bytes::buf::BufExt as _; use futures::future::{BoxFuture, FutureExt, TryFutureExt}; use hyper; use hyper::{Body, Request, Response, StatusCode}; use mockall::automock; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json; use snafu::{ResultEx...
} /// Used to talk to the Github API. /// /// Can safely be cloned. #[derive(Debug, Clone)] pub struct GithubApi<G: GenericHttpClient> { pub http_client: G, } /// An error occured talking to Github. #[derive(Debug, Snafu)] pub enum HttpError { /// Failed to parse response as expected JSON object/ #[snafu...
{ self.as_ref().request(request).boxed() }
identifier_body