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
custom_build.rs
use std::collections::{HashMap, BTreeSet, HashSet}; use std::fs; use std::path::{PathBuf, Path}; use std::str; use std::sync::{Mutex, Arc}; use package_id::PackageId; use util::{CraftResult, Human, Freshness, internal, ChainError, profile, paths}; use super::job::Work; use super::{fingerprint, Kind, Context, Unit}; ...
let data = &state.metadata; for &(ref key, ref value) in data.iter() { cmd.env(&format!("DEP_{}_{}", super::envify(&name), super::envify(key)), value); } } if let Some(build_scripts) = build_scripts {...
internal(format!("failed to locate build state for env vars: {}/{:?}", id, kind)) })?;
random_line_split
wrapper.rs
usize, 0) } unsafe fn from_unsafe(n: &UnsafeNode) -> Self { GeckoNode(&*(n.0 as *mut RawGeckoNode)) } fn children(self) -> LayoutIterator<GeckoChildrenIterator<'ln>> { let maybe_iter = unsafe { Gecko_MaybeCreateStyleChildrenIterator(self.0) }; if let Some(iter) = maybe_iter.in...
h_attr_dash(&se
identifier_name
wrapper.rs
)] pub struct GeckoNode<'ln>(pub &'ln RawGeckoNode); impl<'ln> fmt::Debug for GeckoNode<'ln> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(el) = self.as_element() { el.fmt(f) } else { if self.is_text_node() { write!(f, "<text node> ({:#...
self.set_flags(NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32) } unsafe fn unset_dirty_descendants(&self) { self.unset_flags(NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32) } fn store_children_to_process(&self, _: isize) { // This is only used for bottom-up traversal, and is thus a n...
debug!("Setting dirty descendants: {:?}", self);
random_line_split
wrapper.rs
pub struct GeckoNode<'ln>(pub &'ln RawGeckoNode); impl<'ln> fmt::Debug for GeckoNode<'ln> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(el) = self.as_element() { el.fmt(f) } else { if self.is_text_node() { write!(f, "<text node> ({:#x}...
/// Ensures the element has data, returning the existing data or allocating /// it. /// /// Only safe to call with exclusive access to the element, given otherwise /// it could race to allocate and leak. pub unsafe fn ensure_data(&self) -> &AtomicRefCell<ElementData> { match self.get_data(...
let ptr = self.0.mServoData.get(); if !ptr.is_null() { debug!("Dropping ElementData for {:?}", self); let data = unsafe { Box::from_raw(self.0.mServoData.get()) }; self.0.mServoData.set(ptr::null_mut()); // Perform a mutable borrow of the data in debug buil...
identifier_body
lib.rs
// Copyright 2017 The Grin 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 agree...
//! # Overview //! //! <b>cuckoo-miner</b> is a Rust wrapper around John Tromp's Cuckoo Miner //! C implementations, intended primarily for use in the Grin MimbleWimble //! blockhain development project. However, it is also suitable for use as //! a standalone miner or by any other project needing to use the //! cuck...
// See the License for the specific language governing permissions and // limitations under the License.
random_line_split
mem_map.rs
const BOOT_ROM_START: u16 = 0x0000; const BOOT_ROM_END: u16 = 0x00FF; const CART_ROM_START: u16 = 0x0000; const CART_ROM_END: u16 = 0x7FFF; const CART_ENTRY_POINT: u16 = 0x0100; const CART_HEADER_START: u16 = 0x0100; const CART_HEADER_END: u16 = 0x014F; const CART_FIXED_START: u16 = 0x0150; const CART_FIXED_END: u16...
pub fn ram_size(byte: u8) -> &'static str { match byte { 0x00 => "None", 0x01 => "2 KBytes", 0x02 => "8 Kbytes", 0x03 => "32 KBytes (4 banks of 8KBytes each)", 0x04 => "128 KBytes (16 banks of 8KBytes each)", 0x05 => "64 KBytes (8 banks of 8KBytes each)", _ ...
{ match byte { 0x00 => "32KByte (no ROM banking)", 0x01 => "64KByte (4 banks)", 0x02 => "128KByte (8 banks)", 0x03 => "256KByte (16 banks)", 0x04 => "512KByte (32 banks)", 0x05 => "1MByte (64 banks)", 0x06 => "2MByte (128 banks)", 0x07 => "4MByte (256 ...
identifier_body
mem_map.rs
const BOOT_ROM_START: u16 = 0x0000; const BOOT_ROM_END: u16 = 0x00FF; const CART_ROM_START: u16 = 0x0000; const CART_ROM_END: u16 = 0x7FFF; const CART_ENTRY_POINT: u16 = 0x0100; const CART_HEADER_START: u16 = 0x0100; const CART_HEADER_END: u16 = 0x014F; const CART_FIXED_START: u16 = 0x0150; const CART_FIXED_END: u16...
{ BootRom(u16), CartHeader(u16), CartFixed(u16), CartSwitch(u16), VideoRam(u16), SoundRegister(u16), HighRam(u16), } pub fn cartridge_type(byte: u8) -> &'static str { match byte { 0x00 => "ROM ONLY", 0x01 => "MBC1", 0x02 => "MBC1+RAM", 0x03 => "MBC1+RAM+...
Addr
identifier_name
mem_map.rs
const BOOT_ROM_START: u16 = 0x0000; const BOOT_ROM_END: u16 = 0x00FF; const CART_ROM_START: u16 = 0x0000; const CART_ROM_END: u16 = 0x7FFF; const CART_ENTRY_POINT: u16 = 0x0100; const CART_HEADER_START: u16 = 0x0100; const CART_HEADER_END: u16 = 0x014F; const CART_FIXED_START: u16 = 0x0150; const CART_FIXED_END: u16...
pub fn rom_size(byte: u8) -> &'static str { match byte { 0x00 => "32KByte (no ROM banking)", 0x01 => "64KByte (4 banks)", 0x02 => "128KByte (8 banks)", 0x03 => "256KByte (16 banks)", 0x04 => "512KByte (32 banks)", 0x05 => "1MByte (64 banks)", 0x06 => "2MByte ...
0xFF => "HuC1+RAM+BATTERY", _ => panic!("Unknown Cartridge Type"), } }
random_line_split
ent.rs
use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Serialize, Deserialize)] pub struct PutRequest { pub blobs: Vec<Vec<u8>>, } #[derive(Serialize, Deserialize)] pub struct GetRequest { pub items: Vec<GetItem>, } #[derive(Serialize, Deserialize)] pub struct GetItem { pub root: St...
{ pub api_url: String, } impl EntClient { pub async fn upload_blob(&self, content: &[u8]) -> Result<(), Box<dyn std::error::Error>> { let req = PutRequest { blobs: vec![content.to_vec()], }; self.upload_blobs(&req).await?; Ok(()) } pub async fn upload_blobs...
EntClient
identifier_name
ent.rs
use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Serialize, Deserialize)] pub struct PutRequest { pub blobs: Vec<Vec<u8>>, } #[derive(Serialize, Deserialize)] pub struct GetRequest { pub items: Vec<GetItem>, } #[derive(Serialize, Deserialize)] pub struct GetItem { pub root: St...
} pub async fn upload_blobs(&self, req: &PutRequest) -> Result<(), Box<dyn std::error::Error>> { let req_json = serde_json::to_string(&req)?; reqwasm::http::Request::post(&format!("{}/api/v1/blobs/put", self.api_url)) .body(req_json) .send() .await .m...
self.upload_blobs(&req).await?; Ok(())
random_line_split
borrowed-c-style-enum.rs
// compile-flags:-g // min-lldb-version: 310 // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print *the_a_ref // gdbg-check:$1 = TheA // gdbr-check:$1 = borrowed_c_style_enum::ABC::TheA // gdb-command:print *the_b_ref // gdbg-che...
() { let the_a = ABC::TheA; let the_a_ref: &ABC = &the_a; let the_b = ABC::TheB; let the_b_ref: &ABC = &the_b; let the_c = ABC::TheC; let the_c_ref: &ABC = &the_c; zzz(); // #break } fn zzz() {()}
main
identifier_name
borrowed-c-style-enum.rs
// compile-flags:-g // min-lldb-version: 310 // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print *the_a_ref // gdbg-check:$1 = TheA // gdbr-check:$1 = borrowed_c_style_enum::ABC::TheA // gdb-command:print *the_b_ref // gdbg-che...
{()}
identifier_body
borrowed-c-style-enum.rs
// compile-flags:-g // min-lldb-version: 310 // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print *the_a_ref
// gdbr-check:$2 = borrowed_c_style_enum::ABC::TheB // gdb-command:print *the_c_ref // gdbg-check:$3 = TheC // gdbr-check:$3 = borrowed_c_style_enum::ABC::TheC // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print *the_a_ref /...
// gdbg-check:$1 = TheA // gdbr-check:$1 = borrowed_c_style_enum::ABC::TheA // gdb-command:print *the_b_ref // gdbg-check:$2 = TheB
random_line_split
ext.rs
use std::io; use std::mem; use std::net::SocketAddr; use std::os::unix::io::RawFd; use libc; use sys::unix::err::cvt; #[inline] #[allow(dead_code)] pub fn pipe() -> io::Result<(RawFd, RawFd)> { let mut fds = [0 as libc::c_int; 2]; cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK)...
#[inline] pub fn socket_v6() -> io::Result<RawFd> { let res = unsafe { libc::socket( libc::AF_INET6, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0, ) }; cvt(res) } #[inline] pub fn accept(listener_fd: RawFd) -> io::Result<(RawFd, Socke...
{ let res = unsafe { libc::socket( libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0, ) }; cvt(res) }
identifier_body
ext.rs
use std::io; use std::mem; use std::net::SocketAddr; use std::os::unix::io::RawFd; use libc; use sys::unix::err::cvt; #[inline] #[allow(dead_code)] pub fn pipe() -> io::Result<(RawFd, RawFd)> { let mut fds = [0 as libc::c_int; 2]; cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK)...
() -> io::Result<RawFd> { let res = unsafe { libc::socket( libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0, ) }; cvt(res) } #[inline] pub fn socket_v6() -> io::Result<RawFd> { let res = unsafe { libc::socket( ...
socket_v4
identifier_name
ext.rs
use std::net::SocketAddr; use std::os::unix::io::RawFd; use libc; use sys::unix::err::cvt; #[inline] #[allow(dead_code)] pub fn pipe() -> io::Result<(RawFd, RawFd)> { let mut fds = [0 as libc::c_int; 2]; cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) })?; Ok((fds[0], fds[1...
use std::io; use std::mem;
random_line_split
normalize_projection_ty.rs
use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::TraitEngineExt as _; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::trai...
fn normalize_projection_ty<'tcx>( tcx: TyCtxt<'tcx>, goal: CanonicalProjectionGoal<'tcx>, ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, NormalizationResult<'tcx>>>, NoSolution> { debug!("normalize_provider(goal={:#?})", goal); tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering:...
{ *p = Providers { normalize_projection_ty, ..*p }; }
identifier_body
normalize_projection_ty.rs
use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::TraitEngineExt as _; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::trai...
<'tcx>( tcx: TyCtxt<'tcx>, goal: CanonicalProjectionGoal<'tcx>, ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, NormalizationResult<'tcx>>>, NoSolution> { debug!("normalize_provider(goal={:#?})", goal); tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering::Relaxed); tcx.infer_ctx...
normalize_projection_ty
identifier_name
normalize_projection_ty.rs
use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::TraitEngineExt as _; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::trai...
); fulfill_cx.register_predicate_obligations(infcx, obligations); Ok(NormalizationResult { normalized_ty: answer }) }, ) }
goal, cause, 0, &mut obligations,
random_line_split
x86_64_linux_android.rs
// https://developer.android.com/ndk/guides/abis.html#86-64 base.features = "+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt".to_string(); base.max_atomic_width = Some(64); base.pre_link_args.entry(LinkerFlavor::Gcc).or_default().push("-m64".to_string()); // don't use probe-stack=inline-asm unt...
use crate::spec::{LinkerFlavor, StackProbeType, Target}; pub fn target() -> Target { let mut base = super::android_base::opts(); base.cpu = "x86-64".to_string();
random_line_split
x86_64_linux_android.rs
use crate::spec::{LinkerFlavor, StackProbeType, Target}; pub fn
() -> Target { let mut base = super::android_base::opts(); base.cpu = "x86-64".to_string(); // https://developer.android.com/ndk/guides/abis.html#86-64 base.features = "+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt".to_string(); base.max_atomic_width = Some(64); base.pre_link_args.entry(L...
target
identifier_name
x86_64_linux_android.rs
use crate::spec::{LinkerFlavor, StackProbeType, Target}; pub fn target() -> Target
{ let mut base = super::android_base::opts(); base.cpu = "x86-64".to_string(); // https://developer.android.com/ndk/guides/abis.html#86-64 base.features = "+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt".to_string(); base.max_atomic_width = Some(64); base.pre_link_args.entry(LinkerFlavor::...
identifier_body
sync.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
/// Network information pub network: PeerNetworkInfo, /// Protocols information pub protocols: PeerProtocolsInfo, } /// Peer network information #[derive(Default, Debug, Serialize)] pub struct PeerNetworkInfo { /// Remote endpoint address #[serde(rename="remoteAddress")] pub remote_address: String, /// Local e...
/// Node client ID pub name: String, /// Capabilities pub caps: Vec<String>,
random_line_split
sync.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
#[test] fn test_serialize_peers() { let t = Peers::default(); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"active":0,"connected":0,"max":0,"peers":[]}"#); } #[test] fn test_serialize_sync_status() { let t = SyncStatus::None; let serialized = serde_json::to_string(&t...
{ let t = SyncInfo::default(); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"startingBlock":"0x0","currentBlock":"0x0","highestBlock":"0x0"}"#); }
identifier_body
sync.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
{ /// Public node id pub id: Option<String>, /// Node client ID pub name: String, /// Capabilities pub caps: Vec<String>, /// Network information pub network: PeerNetworkInfo, /// Protocols information pub protocols: PeerProtocolsInfo, } /// Peer network information #[derive(Default, Debug, Serialize)] pub...
PeerInfo
identifier_name
error.rs
extern crate backtrace; extern crate libc; use std::fmt; use std::ops::Deref; use std::io; use std::string::FromUtf8Error; use self::backtrace::Backtrace; use self::backtrace::BacktraceFrame; #[derive(Debug)] pub struct RError<E> { e: E, bt: Option<Backtrace>, } pub fn is_enoent(e: &io::Error) -> bool { ...
pub fn from(e: E) -> RError<E> { let mut bt = Backtrace::new(); let mut i: usize = 0; let mut chop: usize = 0; for f in bt.frames() { if let Some(sym) = f.symbols().first() { if let Some(p) = sym.filename() { if p.file_name().unwrap()...
{ RError { e: e, bt: Default::default(), } }
identifier_body
error.rs
extern crate backtrace; extern crate libc; use std::fmt; use std::ops::Deref; use std::io; use std::string::FromUtf8Error; use self::backtrace::Backtrace; use self::backtrace::BacktraceFrame; #[derive(Debug)] pub struct RError<E> { e: E, bt: Option<Backtrace>, } pub fn is_enoent(e: &io::Error) -> bool { ...
else { return libc::EIO; } } impl<E> RError<E> { pub fn propagate(e: E) -> RError<E> { RError { e: e, bt: Default::default(), } } pub fn from(e: E) -> RError<E> { let mut bt = Backtrace::new(); let mut i: usize = 0; let mut chop...
{ return e.e.raw_os_error().unwrap(); }
conditional_block
error.rs
extern crate backtrace; extern crate libc; use std::fmt; use std::ops::Deref; use std::io; use std::string::FromUtf8Error; use self::backtrace::Backtrace; use self::backtrace::BacktraceFrame; #[derive(Debug)] pub struct RError<E> { e: E, bt: Option<Backtrace>, } pub fn is_enoent(e: &io::Error) -> bool { ...
<T>(e: io::Error) -> Result<T> { return Err(RError::propagate(e)); } pub fn errno(e: &RError<io::Error>) -> libc::c_int { if RError::expected(e) { return e.e.raw_os_error().unwrap(); } else { return libc::EIO; } } impl<E> RError<E> { pub fn propagate(e: E) -> RError<E> { R...
propagate
identifier_name
error.rs
extern crate backtrace; extern crate libc; use std::fmt; use std::ops::Deref; use std::io; use std::string::FromUtf8Error; use self::backtrace::Backtrace; use self::backtrace::BacktraceFrame;
pub struct RError<E> { e: E, bt: Option<Backtrace>, } pub fn is_enoent(e: &io::Error) -> bool { return e.kind() == io::ErrorKind::NotFound; } pub fn try_enoent(e: io::Error) -> Result<bool> { if is_enoent(&e) { return Ok(true); } else { return Err(RError::from(e)); } } pub fn ...
#[derive(Debug)]
random_line_split
main.rs
use std::net::SocketAddr; use std::sync::Arc; use hyper::server::Server; use hyper::service::{make_service_fn, service_fn}; use log::{error, info}; use crate::runtime; use crate::server::github_handler::GithubHandlerState; use crate::server::octobot_service::OctobotService; use crate::server::sessions::Sessions; use ...
Ok(s) => Arc::new(s), Err(e) => panic!("Error initiating github session: {}", e), }; } let jira: Option<Arc<dyn jira::api::Session>>; if let Some(ref jira_config) = config.jira { jira = match JiraSession::new(jira_config, Some(metrics.clone())).await { Ok...
.await {
random_line_split
main.rs
use std::net::SocketAddr; use std::sync::Arc; use hyper::server::Server; use hyper::service::{make_service_fn, service_fn}; use log::{error, info}; use crate::runtime; use crate::server::github_handler::GithubHandlerState; use crate::server::octobot_service::OctobotService; use crate::server::sessions::Sessions; use ...
(config: Config) { let num_http_threads = config.main.num_http_threads.unwrap_or(20); let metrics = metrics::Metrics::new(); runtime::run(num_http_threads, metrics.clone(), async move { run_server(config, metrics).await }); } async fn run_server(config: Config, metrics: Arc<metrics::Metrics>) ...
start
identifier_name
main.rs
use std::net::SocketAddr; use std::sync::Arc; use hyper::server::Server; use hyper::service::{make_service_fn, service_fn}; use log::{error, info}; use crate::runtime; use crate::server::github_handler::GithubHandlerState; use crate::server::octobot_service::OctobotService; use crate::server::sessions::Sessions; use ...
config .github .api_token .as_ref() .expect("expected an api_token"), Some(metrics.clone()), ) .await { Ok(s) => Arc::new(s), Err(e) => panic!("Error initiating github session: {}", e), ...
{ let config = Arc::new(config); let github: Arc<dyn github::api::GithubSessionFactory>; if config.github.app_id.is_some() { github = match github::api::GithubApp::new( &config.github.host, config.github.app_id.expect("expected an app_id"), &config.github.app_ke...
identifier_body
local_ptr.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. /// Leaves the old pointer in TLS for speed. #[inline(never)] // see comments above pub unsafe fn unsafe_take<T>() -> ~T { cast::transmute(RT_TLS_P...
{ let ptr: ~T = cast::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` RT_TLS_PTR = cast::transmute(0); Some(ptr) }
conditional_block
local_ptr.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>() -> ~T { cast::transmute(RT_TLS_PTR) } /// Check whether there is a thread-local pointer installed. #[inline(never)] // see comments above pub fn exists() -> bool { unsafe { RT_TLS_PTR.is_not_null() } } #[inline(never)] // see comments above pub uns...
unsafe_take
identifier_name
local_ptr.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. /// Leaves the old pointer in TLS for speed. #[inline] pub unsafe fn unsafe_take<T>() -> ~T { let key = tls_key(); let void_ptr: *mut u8 = tls::g...
{ match maybe_tls_key() { Some(key) => { let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { None } else { let ptr: ~T = cast::transmute(void_ptr); tls::set(key, ptr::mut_null()); ...
identifier_body
local_ptr.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let key = tls_key(); let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } let ptr: ~T = cast::transmute(void_ptr); return ptr; } /// Check whether there is a thread-local pointer installed....
pub unsafe fn unsafe_take<T>() -> ~T {
random_line_split
mod.rs
mod arrays; mod strings; use self::strings::unescape; pub use self::{arrays::ArrayMethod, strings::StringMethod}; use super::Expander; use crate::{parser::lexers::ArgumentSplitter, types}; use thiserror::Error; #[derive(Debug, PartialEq, Clone)] pub enum Pattern<'a> { StringPattern(&'a str), Whitespace, } #...
/// /// Ex: `$join($scalar)` (can't join a scala) or `$unknown(@variable)` (unknown method) #[derive(Debug, Clone, Error)] pub enum MethodError { /// Unknown array method #[error("'{0}' is an unknown array method")] InvalidArrayMethod(String), /// Unknown scalar method #[error("'{0}' is an unknown s...
expand: &'b mut E, } /// Error during method expansion
random_line_split
mod.rs
mod arrays; mod strings; use self::strings::unescape; pub use self::{arrays::ArrayMethod, strings::StringMethod}; use super::Expander; use crate::{parser::lexers::ArgumentSplitter, types}; use thiserror::Error; #[derive(Debug, PartialEq, Clone)] pub enum Pattern<'a> { StringPattern(&'a str), Whitespace, } #...
}
{ MethodArgs { args, expand } }
identifier_body
mod.rs
mod arrays; mod strings; use self::strings::unescape; pub use self::{arrays::ArrayMethod, strings::StringMethod}; use super::Expander; use crate::{parser::lexers::ArgumentSplitter, types}; use thiserror::Error; #[derive(Debug, PartialEq, Clone)] pub enum Pattern<'a> { StringPattern(&'a str), Whitespace, } #...
(self, pattern: &str) -> super::Result<types::Str, E::Error> { Ok(unescape(&self.expand.expand_string(self.args)?.join(pattern))) } pub fn new(args: &'a str, expand: &'b mut E) -> MethodArgs<'a, 'b, E> { MethodArgs { args, expand } } }
join
identifier_name
main.rs
#![allow(unused_variables)] fn
() { // Rust let bindings are immutable by default. let z = 3; // This will raise a compiler error: // z += 2; //~ ERROR cannot assign twice to immutable variable `z` // You must declare a variable mutable explicitly: let mut x = 3; // Similarly, references are immutable by default e.g. ...
main
identifier_name
main.rs
#![allow(unused_variables)] fn main() { // Rust let bindings are immutable by default. let z = 3; // This will raise a compiler error: // z += 2; //~ ERROR cannot assign twice to immutable variable `z` // You must declare a variable mutable explicitly: let mut x = 3; // Similarly, referen...
}
random_line_split
main.rs
#![allow(unused_variables)] fn main()
// y = &mut z; //~ ERROR re-assignment of immutable variable `y` }
{ // Rust let bindings are immutable by default. let z = 3; // This will raise a compiler error: // z += 2; //~ ERROR cannot assign twice to immutable variable `z` // You must declare a variable mutable explicitly: let mut x = 3; // Similarly, references are immutable by default e.g. /...
identifier_body
ordered.rs
use std::fmt; use std::collections::VecMap; use std::collections::vec_map::Entry; use std::sync::atomic::{AtomicUsize,Ordering}; #[allow(non_camel_case_types)] #[derive(Copy)] pub enum Category { TOKEN = 0, RULE = 1, STATE = 2 } pub trait Ordered { fn get_order(&self) -> usize; } pub struct Manager { ne...
(&mut self, c: Category) -> usize { match self.next_order.entry(c as usize) { Entry::Vacant(entry) => { entry.insert(AtomicUsize::new(1)); 0 }, Entry::Occupied(mut entry) => { let val = entry.get_mut(); ...
next_order
identifier_name
ordered.rs
use std::fmt; use std::collections::VecMap; use std::collections::vec_map::Entry; use std::sync::atomic::{AtomicUsize,Ordering}; #[allow(non_camel_case_types)] #[derive(Copy)] pub enum Category { TOKEN = 0, RULE = 1, STATE = 2 } pub trait Ordered { fn get_order(&self) -> usize; } pub struct Manager { ne...
}
random_line_split
ordered.rs
use std::fmt; use std::collections::VecMap; use std::collections::vec_map::Entry; use std::sync::atomic::{AtomicUsize,Ordering}; #[allow(non_camel_case_types)] #[derive(Copy)] pub enum Category { TOKEN = 0, RULE = 1, STATE = 2 } pub trait Ordered { fn get_order(&self) -> usize; } pub struct Manager { ne...
} impl fmt::Debug for Manager { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ordered::Manager{{}}") } }
{ match self.next_order.entry(c as usize) { Entry::Vacant(entry) => { entry.insert(AtomicUsize::new(1)); 0 }, Entry::Occupied(mut entry) => { let val = entry.get_mut(); val.fetch_add(1, Ordering::SeqCst) } ...
identifier_body
ordered.rs
use std::fmt; use std::collections::VecMap; use std::collections::vec_map::Entry; use std::sync::atomic::{AtomicUsize,Ordering}; #[allow(non_camel_case_types)] #[derive(Copy)] pub enum Category { TOKEN = 0, RULE = 1, STATE = 2 } pub trait Ordered { fn get_order(&self) -> usize; } pub struct Manager { ne...
, Entry::Occupied(mut entry) => { let val = entry.get_mut(); val.fetch_add(1, Ordering::SeqCst) } } } } impl fmt::Debug for Manager { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ordered::Manager{{}}") } }
{ entry.insert(AtomicUsize::new(1)); 0 }
conditional_block
conditional-compile.rs
// xfail-fast // 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 // <...
{ i: int, } fn r(i:int) -> r { r { i: i } } #[cfg(bogus)] mod m { // This needs to parse but would fail in typeck. Since it's not in // the current config it should not be typechecked. pub fn bogus() { return 0; } } mod m { // Submodules have slightly different code paths than the ...
r
identifier_name
conditional-compile.rs
// xfail-fast // 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 // <...
impl Fooable for Foo { #[cfg(bogus)] fn what(&self) { } fn what(&self) { } #[cfg(bogus)] fn the(&self) { } fn the(&self) { } } trait Fooable { #[cfg(bogus)] fn what(&self); fn what(&self); #[cfg(bogus)] fn the(&sel...
mod test_methods { struct Foo { bar: uint }
random_line_split
conditional-compile.rs
// xfail-fast // 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 // <...
#[cfg(bogus)] fn the(&self) { } fn the(&self) { } } trait Fooable { #[cfg(bogus)] fn what(&self); fn what(&self); #[cfg(bogus)] fn the(&self); fn the(&self); } }
{ }
identifier_body
unused_async.rs
use clippy_utils::diagnostics::span_lint_and_help; use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor}; use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{d...
( &mut self, cx: &LateContext<'tcx>, fn_kind: FnKind<'tcx>, fn_decl: &'tcx FnDecl<'tcx>, body: &Body<'tcx>, span: Span, hir_id: HirId, ) { if let FnKind::ItemFn(_, _, FnHeader { asyncness,.. }, _) = &fn_kind { if matches!(asyncness, IsAsync...
check_fn
identifier_name
unused_async.rs
use clippy_utils::diagnostics::span_lint_and_help; use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor}; use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{d...
}
random_line_split
unused_async.rs
use clippy_utils::diagnostics::span_lint_and_help; use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor}; use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{d...
} }
{ if matches!(asyncness, IsAsync::Async) { let mut visitor = AsyncFnVisitor { cx, found_await: false }; walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), span, hir_id); if !visitor.found_await { span_lint_and_help( ...
conditional_block
unused_async.rs
use clippy_utils::diagnostics::span_lint_and_help; use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor}; use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{d...
}
{ if let FnKind::ItemFn(_, _, FnHeader { asyncness, .. }, _) = &fn_kind { if matches!(asyncness, IsAsync::Async) { let mut visitor = AsyncFnVisitor { cx, found_await: false }; walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), span, hir_id); if !visito...
identifier_body
simpleapi.rs
// Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample // This is a simple introductory example of how to interface to Lua from Rust. // The Rust program loads a Lua script file, sets some Lua variables, runs the // Lua script, and reads back the return value.
#![allow(non_snake_case)] extern crate lua; use std::io::{self, Write}; use std::path::Path; use std::process; fn main() { let mut L = lua::State::new(); L.openlibs(); // Load Lua libraries // Load the file containing the script we are going to run let path = Path::new("simpleapi.lua"); match L....
random_line_split
simpleapi.rs
// Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample // This is a simple introductory example of how to interface to Lua from Rust. // The Rust program loads a Lua script file, sets some Lua variables, runs the // Lua script, and reads back the return value. #![allow(non_snake_case)] exte...
*/ L.newtable(); // We will pass a table /* * To put values into the table, we first push the index, then the * value, and then call rawset() with the index of the table in the * stack. Let's see why it's -3: In Lua, the value -1 always refers to * the top of the stack. When you create...
{ let mut L = lua::State::new(); L.openlibs(); // Load Lua libraries // Load the file containing the script we are going to run let path = Path::new("simpleapi.lua"); match L.loadfile(Some(&path)) { Ok(_) => (), Err(_) => { // If something went wrong, error message is at...
identifier_body
simpleapi.rs
// Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample // This is a simple introductory example of how to interface to Lua from Rust. // The Rust program loads a Lua script file, sets some Lua variables, runs the // Lua script, and reads back the return value. #![allow(non_snake_case)] exte...
() { let mut L = lua::State::new(); L.openlibs(); // Load Lua libraries // Load the file containing the script we are going to run let path = Path::new("simpleapi.lua"); match L.loadfile(Some(&path)) { Ok(_) => (), Err(_) => { // If something went wrong, error message is...
main
identifier_name
route-list.rs
extern crate neli; use std::error::Error; use std::net::IpAddr; use neli::consts::*; use neli::err::NlError; use neli::nl::Nlmsghdr; use neli::rtnl::*; use neli::socket::*; fn parse_route_table(rtm: Nlmsghdr<Rtm, Rtmsg>)
Rta::Dst => dst = to_addr(&attr.rta_payload), Rta::Prefsrc => src = to_addr(&attr.rta_payload), Rta::Gateway => gateway = to_addr(&attr.rta_payload), _ => (), } } if let Some(dst) = dst { print!("{}/{} ", dst, rtm.n...
{ // This sample is only interested in the main table. if rtm.nl_payload.rtm_table == RtTable::Main { let mut src = None; let mut dst = None; let mut gateway = None; for attr in rtm.nl_payload.rtattrs.iter() { fn to_addr(b: &[u8]) -> Option<IpAddr> { ...
identifier_body
route-list.rs
extern crate neli; use std::error::Error; use std::net::IpAddr; use neli::consts::*; use neli::err::NlError; use neli::nl::Nlmsghdr; use neli::rtnl::*; use neli::socket::*; fn parse_route_table(rtm: Nlmsghdr<Rtm, Rtmsg>) { // This sample is only interested in the main table. if rtm.nl_payload.rtm_table == Rt...
() -> Result<(), Box<dyn Error>> { let mut socket = NlSocket::connect(NlFamily::Route, None, None, true).unwrap(); let rtmsg = Rtmsg { rtm_family: RtAddrFamily::Inet, rtm_dst_len: 0, rtm_src_len: 0, rtm_tos: 0, rtm_table: RtTable::Unspec, rtm_protocol: Rtprot::Un...
main
identifier_name
route-list.rs
extern crate neli; use std::error::Error; use std::net::IpAddr; use neli::consts::*; use neli::err::NlError; use neli::nl::Nlmsghdr; use neli::rtnl::*; use neli::socket::*; fn parse_route_table(rtm: Nlmsghdr<Rtm, Rtmsg>) { // This sample is only interested in the main table. if rtm.nl_payload.rtm_table == Rt...
} } } } Ok(()) }
nl_payload: nl.nl_payload, }; // Some other message type, so let's try to deserialize as a Rtm. parse_route_table(rtm)
random_line_split
proto.rs
use bytes::{BufMut, BytesMut}; use futures::Future; use std::{io, str}; use std::net::SocketAddr; use tokio_core::net::TcpStream; use tokio_core::reactor::Handle; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::codec::{Decoder, Encoder, Framed}; use tokio_proto::TcpClient; use tokio_proto::multiplex::{ClientPr...
}
{ Ok(io.framed(MultiplexedCodec { header: None })) }
identifier_body
proto.rs
use bytes::{BufMut, BytesMut}; use futures::Future; use std::{io, str}; use std::net::SocketAddr; use tokio_core::net::TcpStream; use tokio_core::reactor::Handle; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::codec::{Decoder, Encoder, Framed}; use tokio_proto::TcpClient; use tokio_proto::multiplex::{ClientPr...
else { let header = buffer.split_to(header_length); let mut reader = io::Cursor::new(header); let header = DataFrameHeader::from_bytes(&mut reader)?; self.decode_frame(header, buffer) } } } } impl Encoder for MultiplexedCodec { ...
{ Ok(None) }
conditional_block
proto.rs
use bytes::{BufMut, BytesMut}; use futures::Future; use std::{io, str}; use std::net::SocketAddr; use tokio_core::net::TcpStream; use tokio_core::reactor::Handle; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::codec::{Decoder, Encoder, Framed}; use tokio_proto::TcpClient; use tokio_proto::multiplex::{ClientProt...
fn bind_transport(&self, io: T) -> Self::BindTransport { Ok(io.framed(MultiplexedCodec { header: None })) } }
type Transport = Framed<T, MultiplexedCodec>; type BindTransport = Result<Self::Transport, io::Error>;
random_line_split
proto.rs
use bytes::{BufMut, BytesMut}; use futures::Future; use std::{io, str}; use std::net::SocketAddr; use tokio_core::net::TcpStream; use tokio_core::reactor::Handle; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::codec::{Decoder, Encoder, Framed}; use tokio_proto::TcpClient; use tokio_proto::multiplex::{ClientPr...
{ inner: ClientService<TcpStream, MultiplexedProto>, } impl MultiplexedClient { pub fn connect( addr: &SocketAddr, handle: &Handle, ) -> Box<Future<Item = MultiplexedClient, Error = io::Error>> { Box::new(TcpClient::new(MultiplexedProto).connect(addr, handle).map( |serv...
MultiplexedClient
identifier_name
expr-match-panic.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 r = match true { true => { true } false => { panic!() } }; assert_eq!(r, true); } fn test_box() { let r = match true { true => { vec!(10) } false => { panic!() } }; assert_eq!(r[0], 10); } pub fn main() { test_simple(); test_box(); }
test_simple
identifier_name
expr-match-panic.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 ...
false => { panic!() } }; assert_eq!(r, true); } fn test_box() { let r = match true { true => { vec!(10) } false => { panic!() } }; assert_eq!(r[0], 10); } pub fn main() { test_simple(); test_box(); }
{ true }
conditional_block
expr-match-panic.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() { test_simple(); test_box(); }
let r = match true { true => { vec!(10) } false => { panic!() } }; assert_eq!(r[0], 10);
random_line_split
expr-match-panic.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() { test_simple(); test_box(); }
{ let r = match true { true => { vec!(10) } false => { panic!() } }; assert_eq!(r[0], 10); }
identifier_body
last-use-in-cap-clause.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 ...
{ a: ~int } fn foo() -> @fn() -> int { let k = ~22; let _u = A {a: k.clone()}; let result: @fn() -> int = || 22; result } pub fn main() { assert!(foo()() == 22); }
A
identifier_name
agent.rs
#![allow(non_snake_case)] use std::collections::HashMap; use request::Handler; use serde_json; use error::ConsulResult; use std::error::Error; use super::{Service, RegisterService, TtlHealthCheck}; /// Agent can be used to query the Agent endpoints pub struct Agent{ handler: Handler } /// AgentMember represent...
(&self, health_check: TtlHealthCheck) -> ConsulResult<()> { let json_str = serde_json::to_string(&health_check) .map_err(|e| e.description().to_owned())?; if let Err(e) = self.handler.put("check/register", json_str, Some("application/json")) { Err(format!("Consul: Error registeri...
register_ttl_check
identifier_name
agent.rs
#![allow(non_snake_case)] use std::collections::HashMap; use request::Handler; use serde_json; use error::ConsulResult; use std::error::Error; use super::{Service, RegisterService, TtlHealthCheck}; /// Agent can be used to query the Agent endpoints pub struct Agent{ handler: Handler } /// AgentMember represent...
else { Ok(()) } } pub fn register_ttl_check(&self, health_check: TtlHealthCheck) -> ConsulResult<()> { let json_str = serde_json::to_string(&health_check) .map_err(|e| e.description().to_owned())?; if let Err(e) = self.handler.put("check/register", json_...
{ Err(format!("Consul: Error registering a service. Err:{}", e)) }
conditional_block
agent.rs
#![allow(non_snake_case)] use std::collections::HashMap; use request::Handler; use serde_json; use error::ConsulResult; use std::error::Error; use super::{Service, RegisterService, TtlHealthCheck}; /// Agent can be used to query the Agent endpoints pub struct Agent{ handler: Handler } /// AgentMember represent...
}
{ let result = self.handler.get("self")?; let json_data = serde_json::from_str(&result) .map_err(|e| e.description().to_owned())?; Ok(super::get_string(&json_data, &["Config", "AdvertiseAddr"])) }
identifier_body
agent.rs
#![allow(non_snake_case)] use std::collections::HashMap; use request::Handler; use serde_json; use error::ConsulResult; use std::error::Error;
/// Agent can be used to query the Agent endpoints pub struct Agent{ handler: Handler } /// AgentMember represents a cluster member known to the agent #[derive(Serialize, Deserialize)] pub struct AgentMember { Name: String, Addr: String, Port: u16, Tags: HashMap<String, String>, Status: usize, ProtocolMin: ...
use super::{Service, RegisterService, TtlHealthCheck};
random_line_split
main.rs
// Copyright (C) 2015, Alberto Corona <alberto@0x1a.us> // All rights reserved. This file is part of core-utils, distributed under the // GPL v3 license. For full terms please see the LICENSE file. #![crate_type = "bin"] #![crate_name = "rm"] #![feature(path_ext)] static VERS: &'static str = "0.1.0"; static PROG: &'s...
} } fn print_usage(opts: Options) { print!("Usage: rm [OPTION...] FILE...\n\ Remove FILE(s) {}\n\ Examples: rm -r dir\tDeletes `dir` and all of its contents", opts.usage("")); } fn main() { let args: Vec<String> = env::args().collect(); let mut opts = Options::new(); opts.optflag("v"...
{ rm_dir(path, recurse, verbose); }
conditional_block
main.rs
// Copyright (C) 2015, Alberto Corona <alberto@0x1a.us> // All rights reserved. This file is part of core-utils, distributed under the // GPL v3 license. For full terms please see the LICENSE file. #![crate_type = "bin"] #![crate_name = "rm"] #![feature(path_ext)] static VERS: &'static str = "0.1.0"; static PROG: &'s...
fn rm_dir(dir: &PathBuf, recurse: bool, verbose: bool) { if recurse { match fs::remove_dir_all(dir) { Ok(_) => { if verbose { println!("Removed: '{}'", dir.display()); } }, Err(e) => { util::err(PROG, S...
{ match fs::remove_file(file) { Ok(_) => { if verbose { println!("Removed: '{}'", file.display()); } }, Err(e) => { util::err(PROG, Status::Error, e.to_string()); panic!(); } }; }
identifier_body
main.rs
// Copyright (C) 2015, Alberto Corona <alberto@0x1a.us> // All rights reserved. This file is part of core-utils, distributed under the // GPL v3 license. For full terms please see the LICENSE file. #![crate_type = "bin"] #![crate_name = "rm"] #![feature(path_ext)] static VERS: &'static str = "0.1.0"; static PROG: &'s...
for item in matches.free.iter() { rm_target(&PathBuf::from(&item), recurse, verb); } } else if matches.free.is_empty() { util::prog_try(PROG); } }
} else if matches.opt_present("version") { util::copyright(PROG, VERS, "2015", vec!["Alberto Corona"]); } else if !matches.free.is_empty() {
random_line_split
main.rs
// Copyright (C) 2015, Alberto Corona <alberto@0x1a.us> // All rights reserved. This file is part of core-utils, distributed under the // GPL v3 license. For full terms please see the LICENSE file. #![crate_type = "bin"] #![crate_name = "rm"] #![feature(path_ext)] static VERS: &'static str = "0.1.0"; static PROG: &'s...
(file: &PathBuf, verbose: bool) { match fs::remove_file(file) { Ok(_) => { if verbose { println!("Removed: '{}'", file.display()); } }, Err(e) => { util::err(PROG, Status::Error, e.to_string()); panic!(); } }; } fn...
rm_file
identifier_name
draw.rs
use nannou::prelude::*; fn main()
fn view(app: &App, frame: Frame) { // Begin drawing let draw = app.draw(); // Clear the background to blue. draw.background().color(CORNFLOWERBLUE); // Draw a purple triangle in the top left half of the window. let win = app.window_rect(); draw.tri() .points(win.bottom_left(), win...
{ nannou::sketch(view).run() }
identifier_body
draw.rs
use nannou::prelude::*; fn main() { nannou::sketch(view).run() } fn view(app: &App, frame: Frame) { // Begin drawing let draw = app.draw(); // Clear the background to blue. draw.background().color(CORNFLOWERBLUE); // Draw a purple triangle in the top left half of the window. let win = ap...
draw.line() .weight(10.0 + (t.sin() * 0.5 + 0.5) * 90.0) .caps_round() .color(PALEGOLDENROD) .points(win.top_left() * t.sin(), win.bottom_right() * t.cos()); // Draw a quad that follows the inverse of the ellipse. draw.quad() .x_y(-app.mouse.x, app.mouse.y) .color(...
.radius(win.w() * 0.125 * t.sin()) .color(RED); // Draw a line!
random_line_split
draw.rs
use nannou::prelude::*; fn
() { nannou::sketch(view).run() } fn view(app: &App, frame: Frame) { // Begin drawing let draw = app.draw(); // Clear the background to blue. draw.background().color(CORNFLOWERBLUE); // Draw a purple triangle in the top left half of the window. let win = app.window_rect(); draw.tri() ...
main
identifier_name
option-like-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { let some_str: Option<&'static str> = Some("abc"); let none_str: Option<&'static str> = None; let some: Option<&u32> = Some(unsafe { std::mem::transmute(0x12345678_usize) }); let none: Option<&u32> = None; let full = MoreFields::Full(454545, unsafe { std::mem::transmute(0x87654321_usize) }, 9...
main
identifier_name
option-like-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
let full = MoreFields::Full(454545, unsafe { std::mem::transmute(0x87654321_usize) }, 9988); let empty = MoreFields::Empty; let empty_gdb: &MoreFieldsRepr = unsafe { std::mem::transmute(&MoreFields::Empty) }; let droid = NamedFields::Droid { id: 675675, range: 10000001, interna...
let some: Option<&u32> = Some(unsafe { std::mem::transmute(0x12345678_usize) }); let none: Option<&u32> = None;
random_line_split
option-like-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{()}
identifier_body
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 https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS handling of specified and computed values of //! [`position`](https://drafts.csswg.org/...
#[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericZIndex<I> { /// An integer value. Integer...
} /// A generic value for the `z-index` property.
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 https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS handling of specified and computed values of //! [`position`](https://drafts.csswg.org/...
<H, V> { /// The horizontal component of position. pub horizontal: H, /// The vertical component of position. pub vertical: V, } pub use self::GenericPosition as Position; impl<H, V> Position<H, V> { /// Returns a new position. pub fn new(horizontal: H, vertical: V) -> Self { Self { ...
GenericPosition
identifier_name
semantic_version.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
{ /// Major version - API/feature removals & breaking changes. pub major: u8, /// Minor version - API/feature additions. pub minor: u8, /// Tiny version - bug fixes. pub tiny: u8, } impl SemanticVersion { /// Create a new object. pub fn new(major: u8, minor: u8, tiny: u8) -> SemanticVe...
SemanticVersion
identifier_name
semantic_version.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
// along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Semantic version formatting and comparing. /// A version value with strict meaning. Use `as_u32` to convert to a simple integer. /// /// # Example /// ``` /// extern crate util; /// use util::semantic_version::*; /// /// fn main() { /// assert_e...
// You should have received a copy of the GNU General Public License
random_line_split
rows.rs
use crate::{ Dao, Value, }; use serde_derive::{ Deserialize, Serialize, }; use std::slice; /// use this to store data retrieved from the database /// This is also slimmer than Vec<Dao> when serialized #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] pub struct Rows { pub columns: Vec<Stri...
#[test] fn dao() { let columns = vec!["id".to_string(), "username".to_string()]; let data: Vec<Vec<Value>> = vec![vec![1.into(), "ivanceras".into()]]; let rows = Rows { columns, data, count: None, }; let mut dao = Dao::new(); ...
{ let columns = vec!["id".to_string(), "username".to_string()]; let data: Vec<Vec<Value>> = vec![vec![1.into(), "ivanceras".into()], vec![ 2.into(), "lee".into(), ]]; let rows = Rows { columns, data, count: None, }; ...
identifier_body
rows.rs
use crate::{ Dao, Value, }; use serde_derive::{ Deserialize, Serialize, }; use std::slice; /// use this to store data retrieved from the database /// This is also slimmer than Vec<Dao> when serialized #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] pub struct Rows { pub columns: Vec<Stri...
} Some(dao) } else { None } } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a> ExactSizeIterator for Iter<'a> {} #[cfg(test)] mod test { use super::*; ...
{ dao.insert_value(column, value); }
conditional_block
rows.rs
use crate::{ Dao, Value, }; use serde_derive::{ Deserialize, Serialize, }; use std::slice; /// use this to store data retrieved from the database /// This is also slimmer than Vec<Dao> when serialized #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] pub struct Rows { pub columns: Vec<Stri...
(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a> ExactSizeIterator for Iter<'a> {} #[cfg(test)] mod test { use super::*; #[test] fn iteration_count() { let columns = vec!["id".to_string(), "username".to_string()]; let data: Vec<Vec<Value>> = vec![vec![1.into(), "ivan...
size_hint
identifier_name
rows.rs
use crate::{ Dao, Value, }; use serde_derive::{ Deserialize, Serialize, }; use std::slice; /// use this to store data retrieved from the database /// This is also slimmer than Vec<Dao> when serialized #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] pub struct Rows { pub columns: Vec<Stri...
pub fn new(columns: Vec<String>) -> Self { Rows { columns, data: vec![], count: None, } } pub fn push(&mut self, row: Vec<Value>) { self.data.push(row) } /// Returns an iterator over the `Row`s. pub fn iter(&self) -> Iter { Iter { ...
impl Rows { pub fn empty() -> Self { Rows::new(vec![]) }
random_line_split
query14.rs
use timely::order::TotalOrder; use timely::dataflow::*; use timely::dataflow::operators::probe::Handle as ProbeHandle; use differential_dataflow::operators::*; use differential_dataflow::operators::arrange::ArrangeBySelf; use differential_dataflow::difference::DiffPair; use differential_dataflow::lattice::Lattice; us...
{ let arrangements = arrangements.in_scope(scope, experiment); experiment .lineitem(scope) .explode(|l| if create_date(1995,9,1) <= l.ship_date && l.ship_date < create_date(1995,10,1) { Some((l.part_key, (l.extended_price * (100 - l.discount) / 100) as isize )) ...
identifier_body
query14.rs
use differential_dataflow::operators::*; use differential_dataflow::operators::arrange::ArrangeBySelf; use differential_dataflow::difference::DiffPair; use differential_dataflow::lattice::Lattice; use {Arrangements, Experiment, Collections}; use ::types::create_date; // -- $ID$ // -- TPC-H/TPC-R Promotion Effect Quer...
use timely::order::TotalOrder; use timely::dataflow::*; use timely::dataflow::operators::probe::Handle as ProbeHandle;
random_line_split
query14.rs
use timely::order::TotalOrder; use timely::dataflow::*; use timely::dataflow::operators::probe::Handle as ProbeHandle; use differential_dataflow::operators::*; use differential_dataflow::operators::arrange::ArrangeBySelf; use differential_dataflow::difference::DiffPair; use differential_dataflow::lattice::Lattice; us...
) .arrange_by_self() .join_core(&arrangements.part, |_pk,&(),p| Some(DiffPair::new(1, if starts_with(&p.typ.as_bytes(), b"PROMO") { 1 } else { 0 }))) .explode(|dp| Some(((),dp))) .count_total() .probe_with(probe); }
{ None }
conditional_block
query14.rs
use timely::order::TotalOrder; use timely::dataflow::*; use timely::dataflow::operators::probe::Handle as ProbeHandle; use differential_dataflow::operators::*; use differential_dataflow::operators::arrange::ArrangeBySelf; use differential_dataflow::difference::DiffPair; use differential_dataflow::lattice::Lattice; us...
(source: &[u8], query: &[u8]) -> bool { source.len() >= query.len() && &source[..query.len()] == query } pub fn query<G: Scope>(collections: &mut Collections<G>, probe: &mut ProbeHandle<G::Timestamp>) where G::Timestamp: Lattice+TotalOrder+Ord { let lineitems = collections .lineitems() .expl...
starts_with
identifier_name
request.rs
//! Client Requests use std::marker::PhantomData; use std::io::{self, Write, BufWriter}; use url::Url; use method::{self, Method}; use header::Headers; use header::{self, Host}; use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming}; use http::{HttpWriter, LINE_ENDING}; use http::HttpWriter::{Thr...
debug!("headers [\n{:?}]", self.headers); try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); if chunked { ChunkedWriter(self.body.into_inner()) } else { SizedWriter(self.body.into_inner(), len) ...
{ let encodings = match self.headers.get_mut::<header::TransferEncoding>() { Some(&mut header::TransferEncoding(ref mut encodings)) => { //TODO: check if chunked is already in encodings. use HashSet? encodings.push(heade...
conditional_block
request.rs
//! Client Requests use std::marker::PhantomData; use std::io::{self, Write, BufWriter}; use url::Url; use method::{self, Method}; use header::Headers; use header::{self, Host}; use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming}; use http::{HttpWriter, LINE_ENDING}; use http::HttpWriter::{Thr...
} impl Request<Streaming> { /// Completes writing the request, and returns a response to read from. /// /// Consumes the Request. pub fn send(self) -> HttpResult<Response> { let raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes Response::new(raw) } } impl...
{ &mut self.headers }
identifier_body
request.rs
//! Client Requests use std::marker::PhantomData; use std::io::{self, Write, BufWriter}; use url::Url; use method::{self, Method}; use header::Headers; use header::{self, Host}; use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming}; use http::{HttpWriter, LINE_ENDING}; use http::HttpWriter::{Thr...
debug!("headers [\n{:?}]", self.headers); try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); if chunked { ChunkedWriter(self.body.into_inner()) } else { SizedWriter(self.body.into_inner(), len) ...
random_line_split
request.rs
//! Client Requests use std::marker::PhantomData; use std::io::{self, Write, BufWriter}; use url::Url; use method::{self, Method}; use header::Headers; use header::{self, Host}; use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming}; use http::{HttpWriter, LINE_ENDING}; use http::HttpWriter::{Thr...
(&mut self, msg: &[u8]) -> io::Result<usize> { self.body.write(msg) } #[inline] fn flush(&mut self) -> io::Result<()> { self.body.flush() } } #[cfg(test)] mod tests { use std::str::from_utf8; use url::Url; use method::Method::{Get, Head}; use mock::{MockStream, MockConn...
write
identifier_name
lib.rs
//! Boron is a small and expressive web framework for Rust which aims to give a robust foundation //! for web applications and APIs. //! //! ## Installation //! Add the following line to your `[dependecies]` section in `Cargo.toml`: //! //! ```toml //! boron = "0.0.2" //! ``` //! //! ## Your first app //! //! ```rust,n...
pub mod server; pub mod response; pub mod request; pub mod middleware; pub mod router; mod matcher;
extern crate regex; extern crate typemap;
random_line_split
fun-call-variants.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 b: isize = ho(direct); // indirect unbound assert_eq!(a, b); }
pub fn main() { let a: isize = direct(3); // direct
random_line_split