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
points.rs
use glium::{Program, Surface}; use glium::backend::Facade; use super::Figure; /// This figure is responsible for rendering points in two and three dimensions pub struct Points <'display_lifetime>{ program: Program, display: &'display_lifetime Facade } #[derive(Copy, Clone)] struct Vertex { position: [f3...
let index_buffer = NoIndices(PrimitiveType::Points); let vertex_buffer = VertexBuffer::new(self.display, &points).unwrap(); surface.draw(&vertex_buffer, &index_buffer, &self.program, &uniform!(), &Default::defau...
Vertex { position: [0.0, -0.5]}, ];
random_line_split
points.rs
use glium::{Program, Surface}; use glium::backend::Facade; use super::Figure; /// This figure is responsible for rendering points in two and three dimensions pub struct
<'display_lifetime>{ program: Program, display: &'display_lifetime Facade } #[derive(Copy, Clone)] struct Vertex { position: [f32; 2] } implement_vertex!(Vertex, position); impl <'display_lifetime> Points<'display_lifetime> { pub fn new(display: &Facade) -> Points { Points { pro...
Points
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] use std::collections::HashSet; use std::fs::create_dir_all; use std::ops::RangeBounds; use std::path::{Path, PathBuf}; ...
} _ => Err(format_err!("Fileblob does not support token, only ranges")), } } } #[cfg(test)] mod test { use super::*; use fbinit::FacebookInit; #[fbinit::test] async fn test_persist_error(fb: FacebookInit) -> Result<()> { let ctx = CoreContext::test_mock(fb...
{ match range { BlobstoreKeyParam::Start(ref range) => { let mut enum_data = BlobstoreEnumerationData { keys: HashSet::new(), next_token: None, }; WalkDir::new(&self.base) .into_iter() ...
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] use std::collections::HashSet; use std::fs::create_dir_all; use std::ops::RangeBounds; use std::path::{Path, PathBuf}; ...
// This uses hardlink semantics as the production blobstores also have hardlink like semantics // (i.e. you can't discover a canonical link source when loading by the target) async fn copy<'a>( &'a self, _ctx: &'a CoreContext, old_key: &'a str, new_key: String, ) -> Resul...
) -> Result<()> { BlobstorePutOps::put_with_status(self, ctx, key, value).await?; Ok(()) }
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] use std::collections::HashSet; use std::fs::create_dir_all; use std::ops::RangeBounds; use std::path::{Path, PathBuf}; ...
<'a>( &'a self, _ctx: &'a CoreContext, old_key: &'a str, new_key: String, ) -> Result<()> { // from std::fs::hard_link: The dst path will be a link pointing to the src path let src_path = self.path(old_key); let dst_path = self.path(&new_key); // hard_...
copy
identifier_name
type_of.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...
} ty::ty_bare_fn(_) => { type_of_fn_from_ty(cx, t).ptr_to() } ty::ty_closure(_) => { let fn_ty = type_of_fn_from_ty(cx, t).ptr_to(); Type::struct_(cx, [fn_ty, Type::i8p(cx)], false) } ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_tup(..) => {...
} ty::ty_vec(ref mt, Some(n)) => { Type::array(&type_of(cx, mt.ty), n as u64)
random_line_split
type_of.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
}; let tstr = ppaux::parameterized(cx.tcx(), ty::item_path_str(cx.tcx(), did).as_slice(), &ty::NonerasedRegions( OwnedSlice::empty()), ...
{ "enum" }
conditional_block
type_of.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: &CrateContext, what: named_ty, did: ast::DefId, tps: &[ty::t]) -> String { let name = match what { a_struct => { "struct" } an_enum => { "enum" } }; let tstr = ppaux::parameterized(cx.tcx(), ...
llvm_type_name
identifier_name
type_of.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...
Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false) } _ => Type::i8p(cx), } } ty::ty_bare_fn(..) => Type::i8p(cx), ty::ty_closure(..) => Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false), ty::ty_trait(..) => Typ...
{ match cx.llsizingtypes.borrow().find_copy(&t) { Some(t) => return t, None => () } let llsizingty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from...
identifier_body
env.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
}; let msg = match exprs.next() { None => { token::intern_and_get_ident(&format!("environment variable `{}` \ not defined", var)) } Some(second) => { match expr_to_str...
random_line_split
env.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>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { let var = match get_single_str_from_tts(cx, sp, tts, "option_env!") { None => return DummyResult::expr(sp), Some(v) => v }; let e = match env::var(&var[..]) { Err(...
expand_option_env
identifier_name
env.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...
var)) } Some(second) => { match expr_to_string(cx, second, "expected string literal") { None => return DummyResult::expr(sp), Some((s, _style)) => s } } }; match exprs.next() { ...
{ let mut exprs = match get_exprs_from_tts(cx, sp, tts) { Some(ref exprs) if exprs.is_empty() => { cx.span_err(sp, "env! takes 1 or 2 arguments"); return DummyResult::expr(sp); } None => return DummyResult::expr(sp), Some(exprs) => exprs.into_iter() }; ...
identifier_body
lib.rs
#![recursion_limit = "1024"] mod async_rt; mod backend; mod codec; mod dealer; mod endpoint; mod error; mod fair_queue; mod message; mod r#pub; mod pull; mod push; mod rep; mod req; mod router; mod sub; mod task_handle; mod transport; pub mod util; #[doc(hidden)] pub mod __async_rt { //! DO NOT USE! PRIVATE IMPLE...
Err(e) => { if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::AcceptFailed(e)); } } } } }; let (endpoint...
{ if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Accepted(endpoint, peer_id)); } }
conditional_block
lib.rs
#![recursion_limit = "1024"] mod async_rt; mod backend; mod codec; mod dealer; mod endpoint; mod error; mod fair_queue; mod message; mod r#pub; mod pull; mod push; mod rep; mod req; mod router; mod sub; mod task_handle; mod transport; pub mod util; #[doc(hidden)] pub mod __async_rt { //! DO NOT USE! PRIVATE IMPLE...
errs } /// Connects to the given endpoint. async fn connect(&mut self, endpoint: &str) -> ZmqResult<()> { let backend = self.backend(); let endpoint = endpoint.try_into()?; let result = match util::connect_forever(endpoint).await { Ok((socket, endpoint)) => matc...
} }
random_line_split
lib.rs
#![recursion_limit = "1024"] mod async_rt; mod backend; mod codec; mod dealer; mod endpoint; mod error; mod fair_queue; mod message; mod r#pub; mod pull; mod push; mod rep; mod req; mod router; mod sub; mod task_handle; mod transport; pub mod util; #[doc(hidden)] pub mod __async_rt { //! DO NOT USE! PRIVATE IMPLE...
{ pub(crate) peer_id: Option<PeerIdentity>, } impl SocketOptions { pub fn peer_identity(&mut self, peer_id: PeerIdentity) -> &mut Self { self.peer_id = Some(peer_id); self } } #[async_trait] pub trait MultiPeerBackend: SocketBackend { /// This should not be public.. /// Find a bet...
SocketOptions
identifier_name
lib.rs
#![recursion_limit = "1024"] mod async_rt; mod backend; mod codec; mod dealer; mod endpoint; mod error; mod fair_queue; mod message; mod r#pub; mod pull; mod push; mod rep; mod req; mod router; mod sub; mod task_handle; mod transport; pub mod util; #[doc(hidden)] pub mod __async_rt { //! DO NOT USE! PRIVATE IMPLE...
} } Err(e) => { if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::AcceptFailed(e)); } } } ...
{ let endpoint = endpoint.try_into()?; let cloned_backend = self.backend(); let cback = move |result| { let cloned_backend = cloned_backend.clone(); async move { let result = match result { Ok((socket, endpoint)) => { ...
identifier_body
kiss.rs
use std::io; use std::io::prelude::*; use std::net::Shutdown; use std::net::TcpStream; use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; const FEND: u8 = 0xC0; const FESC: u8 = 0xDB; const TFEND: u8 = 0xDC; const TFESC: u8 = 0xDD; pub(crate) struct TcpKissInterface { ...
<A: ToSocketAddrs>(addr: A) -> io::Result<TcpKissInterface> { let tx_stream = TcpStream::connect(addr)?; let rx_stream = tx_stream.try_clone()?; Ok(TcpKissInterface { tx_stream: Mutex::new(tx_stream), rx_stream: Mutex::new(rx_stream), buffer: Mutex::new(Vec::n...
new
identifier_name
kiss.rs
use std::io; use std::io::prelude::*; use std::net::Shutdown; use std::net::TcpStream; use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; const FEND: u8 = 0xC0; const FESC: u8 = 0xDB; const TFEND: u8 = 0xDC; const TFESC: u8 = 0xDD; pub(crate) struct TcpKissInterface { ...
state = Scan::Data; } } } match final_idx { 0 => None, n => { // Draining up to "n" will leave the final FEND in place // This way we can use it as the start marker for the next frame buffer.drain(0..n); Some(p...
{ // Successfully read a non-zero-length frame final_idx = idx; break; }
conditional_block
kiss.rs
use std::io; use std::io::prelude::*; use std::net::Shutdown; use std::net::TcpStream; use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; const FEND: u8 = 0xC0; const FESC: u8 = 0xDB; const TFEND: u8 = 0xDC; const TFESC: u8 = 0xDD; pub(crate) struct TcpKissInterface { ...
pub(crate) fn receive_frame(&self) -> io::Result<Vec<u8>> { loop { { let mut buffer = self.buffer.lock().unwrap(); if let Some(frame) = make_frame_from_buffer(&mut buffer) { return Ok(frame); } } let mu...
{ let tx_stream = TcpStream::connect(addr)?; let rx_stream = tx_stream.try_clone()?; Ok(TcpKissInterface { tx_stream: Mutex::new(tx_stream), rx_stream: Mutex::new(rx_stream), buffer: Mutex::new(Vec::new()), is_shutdown: AtomicBool::new(false), ...
identifier_body
kiss.rs
use std::io; use std::io::prelude::*; use std::net::Shutdown; use std::net::TcpStream; use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; const FEND: u8 = 0xC0; const FESC: u8 = 0xDB; const TFEND: u8 = 0xDC; const TFESC: u8 = 0xDD; pub(crate) struct TcpKissInterface { ...
let mut rx = vec![0x03, 0x04, FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_consecutive_marker() { let mut rx = vec![FEND, FEND, FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(ve...
assert_eq!(rx, vec![FEND, 0x03, 0x04]); } #[test] fn test_leading_data() {
random_line_split
ccw_face_normal.rs
use crate::math::{Point, Vector}; use na::{RealField, Unit}; /// Computes the direction pointing toward the right-hand-side of an oriented segment. /// /// Returns `None` if the segment is degenerate. #[inline] #[cfg(feature = "dim2")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 2]) -> Option<Unit<Vector<N>>...
<N: RealField>(pts: [&Point<N>; 3]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let ac = pts[2] - pts[0]; let res = ab.cross(&ac); Unit::try_new(res, N::default_epsilon()) }
ccw_face_normal
identifier_name
ccw_face_normal.rs
use crate::math::{Point, Vector}; use na::{RealField, Unit}; /// Computes the direction pointing toward the right-hand-side of an oriented segment. /// /// Returns `None` if the segment is degenerate. #[inline] #[cfg(feature = "dim2")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 2]) -> Option<Unit<Vector<N>>...
/// Computes the normal of a counter-clock-wise triangle. /// /// Returns `None` if the triangle is degenerate. #[inline] #[cfg(feature = "dim3")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 3]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let ac = pts[2] - pts[0]; let res = ab.cross(&...
{ let ab = pts[1] - pts[0]; let res = Vector::new(ab[1], -ab[0]); Unit::try_new(res, N::default_epsilon()) }
identifier_body
ccw_face_normal.rs
use crate::math::{Point, Vector}; use na::{RealField, Unit}; /// Computes the direction pointing toward the right-hand-side of an oriented segment. /// /// Returns `None` if the segment is degenerate. #[inline] #[cfg(feature = "dim2")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 2]) -> Option<Unit<Vector<N>>...
/// /// Returns `None` if the triangle is degenerate. #[inline] #[cfg(feature = "dim3")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 3]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let ac = pts[2] - pts[0]; let res = ab.cross(&ac); Unit::try_new(res, N::default_epsilon()) }
/// Computes the normal of a counter-clock-wise triangle.
random_line_split
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See t...
let font_match = pat.font_match(); font_match.name().and_then(|name| font_match.filename().map(|filename| Font { name: name.into_string(), path: Path::new(filename), } )) } #[allow(dead_code)] fn print_debug(&self) { ...
{ pat.add_string("style", style); }
conditional_block
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See t...
/// This is just to hold the RAII C-strings while the `FcPattern` is alive. strings: Vec<CString>, } impl<'a> Pattern<'a> { pub fn new() -> Pattern<'a> { fc_init(); Pattern { _m: marker::ContravariantLifetime, pat: unsafe{ fontconfig::FcPatternCreate() }, ...
/// A safe wrapper around fontconfig's `FcPattern`. pub struct Pattern<'a> { _m: marker::ContravariantLifetime<'a>, pat: *mut FcPattern,
random_line_split
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See t...
} /// A safe wrapper around fontconfig's `FcPattern`. pub struct Pattern<'a> { _m: marker::ContravariantLifetime<'a>, pat: *mut FcPattern, /// This is just to hold the RAII C-strings while the `FcPattern` is alive. strings: Vec<CString>, } impl<'a> Pattern<'a> { pub fn new() -> Pattern<'a> { ...
{ debug!("Name: {}\nPath: {}", self.name, self.path.display()); }
identifier_body
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See t...
<'a>(&'a self, name: &str) -> Option<&'a str> { name.with_c_str(|c_str| unsafe { let ret = mem::uninitialized(); if fontconfig::FcPatternGetString(&*self.pat, c_str, 0, ret) == 0 { Some(std::str::from_c_str(*ret as *const i8)) } else { None } }) } ...
get_string
identifier_name
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[...
ptxt } // k=IV recovery attack // --- // C_1' = C_1 // C_2' = 0 // C_3' = C_1 // P_1' = D_k(C_1') ^ k // = D_k(C_1) ^ k // P_3' = D_k(C_3') ^ C_2' // = D_k(C_1) ^ 0 // = D_k(C_1) // k = P_1' ^ P_3' // = D_k(C_1') ^ k ^ D_k(C_1) // = k #[test] fn run() { let mut rng = weak_rng(); ...
{ println!("Oh no there's an error!"); }
conditional_block
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[...
// k=IV recovery attack // --- // C_1' = C_1 // C_2' = 0 // C_3' = C_1 // P_1' = D_k(C_1') ^ k // = D_k(C_1) ^ k // P_3' = D_k(C_3') ^ C_2' // = D_k(C_1) ^ 0 // = D_k(C_1) // k = P_1' ^ P_3' // = D_k(C_1') ^ k ^ D_k(C_1) // = k #[test] fn run() { let mut rng = weak_rng(); let key:...
{ let iv = Some(key); let ptxt = decrypt(symm::Cipher::aes_128_cbc(), key, iv, data).unwrap(); let invalid = ptxt.iter() .find(|&&b| b < 32 || b >= 127) .is_some(); if invalid { println!("Oh no there's an error!"); } ptxt }
identifier_body
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[...
.unwrap(); let ctxt = encryption_oracle(&key, &msg); let mut new_ctxt = ctxt[0..16].to_vec(); new_ctxt.extend_from_slice(&[0_u8; 16]); new_ctxt.extend_from_slice(&ctxt[0..16]); new_ctxt.extend_from_slice(&ctxt[48..]); let ptxt = decryption_oracle(&key, &new_ctxt); let key_recovered...
let msg = "RE9TJ1QgVEhPVSBQUkFURSwgUk9HVUU/PyBET1MnVCBUSE9VIEpFRVIgQU5EIFQ\ tVEFVTlQgTUUgSU4gVEhFIFRFRVRIPz8K" .from_base64()
random_line_split
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[...
() { let mut rng = weak_rng(); let key: [u8; 16] = rng.gen(); let msg = "RE9TJ1QgVEhPVSBQUkFURSwgUk9HVUU/PyBET1MnVCBUSE9VIEpFRVIgQU5EIFQ\ tVEFVTlQgTUUgSU4gVEhFIFRFRVRIPz8K" .from_base64() .unwrap(); let ctxt = encryption_oracle(&key, &msg); let mut new_ctxt = ctxt[0..16].to_vec(...
run
identifier_name
enumeration.rs
use crate::model::create::{CreateError, CreateResult}; use crate::model::enumeration::Enumeration; use crate::model::symbol::Symbol; use crate::model::Def; use crate::xsd::restriction::Facet; use crate::xsd::simple_type::{Payload, SimpleType}; use crate::xsd::{simple_type, Xsd}; pub(super) fn is_enumeration(st: &Simpl...
pub(super) fn model_enumeration(st: &SimpleType, xsd: &Xsd) -> CreateResult { let restriction = if let simple_type::Payload::Restriction(r) = &st.payload { r } else { return Err(CreateError::new("expected restriction")); }; let mut members = Vec::new(); for facet in &restriction.fa...
{ match &st.payload { Payload::Restriction(r) => { if r.facets.is_empty() { return false; } for facet in &r.facets { match facet { Facet::Enumeration(_) => continue, _ => return false, ...
identifier_body
enumeration.rs
use crate::model::create::{CreateError, CreateResult}; use crate::model::enumeration::Enumeration; use crate::model::symbol::Symbol; use crate::model::Def; use crate::xsd::restriction::Facet; use crate::xsd::simple_type::{Payload, SimpleType}; use crate::xsd::{simple_type, Xsd}; pub(super) fn is_enumeration(st: &Simpl...
(st: &SimpleType, xsd: &Xsd) -> CreateResult { let restriction = if let simple_type::Payload::Restriction(r) = &st.payload { r } else { return Err(CreateError::new("expected restriction")); }; let mut members = Vec::new(); for facet in &restriction.facets { let s = if let Fac...
model_enumeration
identifier_name
enumeration.rs
use crate::model::create::{CreateError, CreateResult}; use crate::model::enumeration::Enumeration; use crate::model::symbol::Symbol; use crate::model::Def; use crate::xsd::restriction::Facet; use crate::xsd::simple_type::{Payload, SimpleType}; use crate::xsd::{simple_type, Xsd}; pub(super) fn is_enumeration(st: &Simpl...
Facet::Enumeration(_) => continue, _ => return false, } } return true; } _ => false, } } pub(super) fn model_enumeration(st: &SimpleType, xsd: &Xsd) -> CreateResult { let restriction = if let simple_type::Payload::R...
random_line_split
mod.rs
mod ffi; pub mod error; pub mod vars; pub mod options; pub mod status; pub mod chat; pub mod file; mod friend; mod network; mod custom; mod events; #[cfg(feature = "groupchat")] pub mod group; #[cfg(feature = "groupchat")] mod peer; pub use self::options::ToxOptions; pub use self::status::Status; pub use self::netwo...
/// Get Address. pub fn address(&self) -> ::address::Address { out!( get out <- vec_with!(vars::TOX_ADDRESS_SIZE), ffi::tox_self_get_address(self.core, out.as_mut_ptr()) ).into() } /// Get SecretKey. pub fn secretkey(&self) -> Vec<u8> { out!( get ...
{ out!( get out <- vec_with!(ffi::tox_get_savedata_size(self.core)), ffi::tox_get_savedata(self.core, out.as_mut_ptr()) ) }
identifier_body
mod.rs
mod ffi; pub mod error; pub mod vars; pub mod options; pub mod status; pub mod chat; pub mod file; mod friend; mod network; mod custom; mod events; #[cfg(feature = "groupchat")] pub mod group; #[cfg(feature = "groupchat")] mod peer; pub use self::options::ToxOptions; pub use self::status::Status; pub use self::netwo...
<S: AsRef<[u8]>>(&self, message: S) -> Result<(), error::InfoSetErr> { let message = message.as_ref(); out!( bool err, ffi::tox_self_set_status_message( self.core, message.as_ptr(), message.len(), &mut err ...
set_status_message
identifier_name
mod.rs
mod ffi; pub mod error; pub mod vars; pub mod options; pub mod status; pub mod chat; pub mod file; mod friend; mod network; mod custom; mod events; #[cfg(feature = "groupchat")] pub mod group; #[cfg(feature = "groupchat")] mod peer; pub use self::options::ToxOptions; pub use self::status::Status; pub use self::netwo...
pub use self::peer::Peer; /// Tox. #[derive(Clone, Debug)] pub struct Tox { pub core: *mut ffi::Tox } impl Tox { /// from ToxOptions create Tox. pub fn new(opts: ToxOptions) -> Result<Tox, error::NewErr> { out!(err err, ffi::tox_new(&opts.opts, &mut err)) .map(Tox::from) } ///...
#[cfg(feature = "groupchat")]
random_line_split
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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...
} impl<A: Address> FromColumn<A> for A { fn from_column<'a>(row: &'a Row, column_name: &str) -> Result<A, db_error> { let address_str : String = row.get(column_name); match A::from_string(&address_str) { Some(a) => Ok(a), None => Err(db_error::ParseError) } } }
{ let pubkey_hex : String = row.get(column_name); match VRFPublicKey::from_hex(&pubkey_hex) { Some(pubk) => Ok(pubk), None => Err(db_error::ParseError) } }
identifier_body
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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...
} } impl<A: Address> FromColumn<A> for A { fn from_column<'a>(row: &'a Row, column_name: &str) -> Result<A, db_error> { let address_str : String = row.get(column_name); match A::from_string(&address_str) { Some(a) => Ok(a), None => Err(db_error::ParseError) } ...
let pubkey_hex : String = row.get(column_name); match VRFPublicKey::from_hex(&pubkey_hex) { Some(pubk) => Ok(pubk), None => Err(db_error::ParseError) }
random_line_split
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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...
<'a>(row: &'a Row, column_name: &str) -> Result<A, db_error> { let address_str : String = row.get(column_name); match A::from_string(&address_str) { Some(a) => Ok(a), None => Err(db_error::ParseError) } } }
from_column
identifier_name
convex_polygon.rs
use crate::math::{Isometry, Point, Vector}; use crate::shape::{ConvexPolygonalFeature, ConvexPolyhedron, FeatureId, SupportMap}; use crate::transformation; use crate::utils; use na::{self, RealField, Unit}; use std::f64; /// A 2D convex polygon. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(C...
if normals[i1].dot(&*normals[i2]) > N::one() - eps { // Remove nremoved += 1; } else { points[i2 - nremoved] = points[i2]; normals[i2 - nremoved] = normals[i2]; } } let new_length = points.len() - nremov...
{ let eps = N::default_epsilon().sqrt(); let mut normals = Vec::with_capacity(points.len()); // First, compute all normals. for i1 in 0..points.len() { let i2 = (i1 + 1) % points.len(); normals.push(utils::ccw_face_normal([&points[i1], &points[i2]])?); } ...
identifier_body
convex_polygon.rs
use crate::math::{Isometry, Point, Vector}; use crate::shape::{ConvexPolygonalFeature, ConvexPolyhedron, FeatureId, SupportMap}; use crate::transformation; use crate::utils; use na::{self, RealField, Unit}; use std::f64; /// A 2D convex polygon. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(C...
} impl<N: RealField> ConvexPolyhedron<N> for ConvexPolygon<N> { fn vertex(&self, id: FeatureId) -> Point<N> { self.points[id.unwrap_vertex()] } fn face(&self, id: FeatureId, out: &mut ConvexPolygonalFeature<N>) { out.clear(); let ia = id.unwrap_face(); let ib = (ia + 1) % ...
}
random_line_split
convex_polygon.rs
use crate::math::{Isometry, Point, Vector}; use crate::shape::{ConvexPolygonalFeature, ConvexPolyhedron, FeatureId, SupportMap}; use crate::transformation; use crate::utils; use na::{self, RealField, Unit}; use std::f64; /// A 2D convex polygon. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(C...
(&self, id: FeatureId) -> Point<N> { self.points[id.unwrap_vertex()] } fn face(&self, id: FeatureId, out: &mut ConvexPolygonalFeature<N>) { out.clear(); let ia = id.unwrap_face(); let ib = (ia + 1) % self.points.len(); out.push(self.points[ia], FeatureId::Vertex(ia)); ...
vertex
identifier_name
lib.rs
/*! * The ```ladspa``` crate provides an interface for writing [LADSPA](http://www.ladspa.org/) * plugins safely in Rust. * * ##Creating the project * * Run ```cargo new my_ladspa_plugin``` to generate a Cargo project for your plugin, then add * the following to the generated Cargo.toml: * * ``` * [dependenci...
<'a> { AudioInput(&'a [Data]), AudioOutput(RefCell<&'a mut [Data]>), ControlInput(&'a Data), ControlOutput(RefCell<&'a mut Data>), } unsafe impl<'a> Sync for PortData<'a> { } impl<'a> PortConnection<'a> { /// Returns a slice pointing to the internal data of an audio input port. Panics if this port...
PortData
identifier_name
lib.rs
/*! * The ```ladspa``` crate provides an interface for writing [LADSPA](http://www.ladspa.org/) * plugins safely in Rust. * * ##Creating the project * * Run ```cargo new my_ladspa_plugin``` to generate a Cargo project for your plugin, then add * the following to the generated Cargo.toml: * * ``` * [dependenci...
} /// Returns a mutable refrence to the internal data of an audio output port. Panics if /// this port is not an ```ControlOut``` port. pub fn unwrap_control_mut(&'a self) -> RefMut<'a, &'a mut Data> { if let PortData::ControlOutput(ref data) = self.data { data.borrow_mut() ...
{ panic!("PortConnection::unwrap_control called on a non control input port!") }
conditional_block
lib.rs
/*! * The ```ladspa``` crate provides an interface for writing [LADSPA](http://www.ladspa.org/) * plugins safely in Rust. * * ##Creating the project * * Run ```cargo new my_ladspa_plugin``` to generate a Cargo project for your plugin, then add * the following to the generated Cargo.toml: * * ``` * [dependenci...
} else { panic!("PortConnection::unwrap_audio_mut called on a non audio output port!") } } /// Returns a refrence to the internal data of an control input port. Panics if this port /// is not an ```ControlIn``` port. pub fn unwrap_control(&'a self) -> &'a Data { if l...
/// this port is not an ```AudioOut``` port. pub fn unwrap_audio_mut(&'a self) -> RefMut<'a, &'a mut [Data]> { if let PortData::AudioOutput(ref data) = self.data { data.borrow_mut()
random_line_split
lib.rs
/*! * The ```ladspa``` crate provides an interface for writing [LADSPA](http://www.ladspa.org/) * plugins safely in Rust. * * ##Creating the project * * Run ```cargo new my_ladspa_plugin``` to generate a Cargo project for your plugin, then add * the following to the generated Cargo.toml: * * ``` * [dependenci...
/// Runs the plugin on a number of samples, given the connected ports. fn run<'a>(&mut self, sample_count: usize, ports: &[&'a PortConnection<'a>]); /// Indicates the plugin is no longer live. fn deactivate(&mut self) { } }
{ }
identifier_body
enum_iterator.rs
#[macro_use] extern crate custom_derive; macro_rules! EnumIterator { (() $(pub)* enum $name:ident { $($body:tt)* }) => { EnumIterator! { @collect_variants ($name), ($($body)*,) -> () } }; ( @collect_variants ($name:ident), ($(,)*) -> ($($var_names:id...
} #[test] fn test_enum_iterator() { let vs: Vec<_> = Get::iter_variant_names().zip(Get::iter_variants()).collect(); assert_eq!(&*vs, &[("Up", Get::Up), ("Down", Get::Down), ("AllAround", Get::AllAround)]); }
random_line_split
enum_iterator.rs
#[macro_use] extern crate custom_derive; macro_rules! EnumIterator { (() $(pub)* enum $name:ident { $($body:tt)* }) => { EnumIterator! { @collect_variants ($name), ($($body)*,) -> () } }; ( @collect_variants ($name:ident), ($(,)*) -> ($($var_names:id...
{ let vs: Vec<_> = Get::iter_variant_names().zip(Get::iter_variants()).collect(); assert_eq!(&*vs, &[("Up", Get::Up), ("Down", Get::Down), ("AllAround", Get::AllAround)]); }
identifier_body
enum_iterator.rs
#[macro_use] extern crate custom_derive; macro_rules! EnumIterator { (() $(pub)* enum $name:ident { $($body:tt)* }) => { EnumIterator! { @collect_variants ($name), ($($body)*,) -> () } }; ( @collect_variants ($name:ident), ($(,)*) -> ($($var_names:id...
() { let vs: Vec<_> = Get::iter_variant_names().zip(Get::iter_variants()).collect(); assert_eq!(&*vs, &[("Up", Get::Up), ("Down", Get::Down), ("AllAround", Get::AllAround)]); }
test_enum_iterator
identifier_name
lib.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 ...
<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } // FIXME: Instantiated functions with i128 in the signature is not supported in Emscripten. // See https://github.com/kripken/emscripten-fastcomp/issues/169 #[cfg(not(target_os = "emscripten"))] #[test] fn test_boxed_h...
hash
identifier_name
lib.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 ...
// FIXME: Instantiated functions with i128 in the signature is not supported in Emscripten. // See https://github.com/kripken/emscripten-fastcomp/issues/169 #[cfg(not(target_os = "emscripten"))] #[test] fn test_boxed_hasher() { let ordinary_hash = hash(&5u32); let mut hasher_1 = Box::new(DefaultHasher::new()...
{ let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() }
identifier_body
lib.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 ...
mod arc; mod binary_heap; mod btree; mod cow_str; mod fmt; mod heap; mod linked_list; mod rc; mod slice; mod str; mod string; mod vec_deque; mod vec; fn hash<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } // FIXME: Instantiated functions with i128 in the signature ...
random_line_split
lib.rs
pub fn sing(start: i32, end: i32) -> String { let mut out = String::new(); let mut count = start; while count >= end { out.push_str(verse(count).as_str()); out.push('\n'); count -= 1; } out.pop(); return out; } pub fn
(num: i32) -> String { let mut out = String::new(); match num { 0 => { out.push_str(format!("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n").as_str()); }, 1 => { out.push_str(fo...
verse
identifier_name
lib.rs
pub fn sing(start: i32, end: i32) -> String
pub fn verse(num: i32) -> String { let mut out = String::new(); match num { 0 => { out.push_str(format!("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n").as_str()); }, 1 => { o...
{ let mut out = String::new(); let mut count = start; while count >= end { out.push_str(verse(count).as_str()); out.push('\n'); count -= 1; } out.pop(); return out; }
identifier_body
lib.rs
pub fn sing(start: i32, end: i32) -> String { let mut out = String::new(); let mut count = start; while count >= end { out.push_str(verse(count).as_str()); out.push('\n'); count -= 1; } out.pop(); return out; } pub fn verse(num: i32) -> String { let mut out = Strin...
, 1 => { out.push_str(format!("{x} bottle of beer on the wall, {x} bottle of beer.\n", x = num).as_str()); out.push_str(format!("Take it down and pass it around, no more bottles of beer on the wall.\n").as_str()); }, 2 => { out.push_str(format!("{x} bottles of...
{ out.push_str(format!("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n").as_str()); }
conditional_block
lib.rs
pub fn sing(start: i32, end: i32) -> String { let mut out = String::new(); let mut count = start; while count >= end { out.push_str(verse(count).as_str()); out.push('\n'); count -= 1; } out.pop(); return out; } pub fn verse(num: i32) -> String { let mut out = Strin...
2 => { out.push_str(format!("{x} bottles of beer on the wall, {x} bottles of beer.\n", x = num).as_str()); out.push_str(format!("Take one down and pass it around, {x} bottle of beer on the wall.\n", x = num - 1).as_str()); }, _ => { out.push_str(format!("{x} b...
},
random_line_split
type_filter.rs
use std::collections::HashSet; use botocore::{Service, ShapeType, Shape}; use super::mutate_type_name; pub fn filter_types(service: &Service) -> (HashSet<String>, HashSet<String>) { let mut deserialized_types: HashSet<String> = HashSet::new(); let mut serialized_types: HashSet<String> = HashSet::new(); for...
_ => {} } } // output shapes with a payload blob don't get deserialized // unless they have non-payload elements from the headers etc. fn can_skip_deserializer(service: &Service, output_shape: &Shape) -> bool { match output_shape.payload { None => false, Some(ref payload_member) => { ...
{ recurse_find_shapes(service, types, shape.member_type()); }
conditional_block
type_filter.rs
use std::collections::HashSet; use botocore::{Service, ShapeType, Shape}; use super::mutate_type_name; pub fn filter_types(service: &Service) -> (HashSet<String>, HashSet<String>) { let mut deserialized_types: HashSet<String> = HashSet::new(); let mut serialized_types: HashSet<String> = HashSet::new(); for...
member.location!= Some("headers".to_owned()) && !types.contains(&member.shape) { recurse_find_shapes(service, types, &member.shape); } } } } ShapeType::Map => { recurse_find_s...
member.location != Some("header".to_owned()) &&
random_line_split
type_filter.rs
use std::collections::HashSet; use botocore::{Service, ShapeType, Shape}; use super::mutate_type_name; pub fn
(service: &Service) -> (HashSet<String>, HashSet<String>) { let mut deserialized_types: HashSet<String> = HashSet::new(); let mut serialized_types: HashSet<String> = HashSet::new(); for operation in service.operations.values() { if let Some(ref output) = operation.output { let output_sh...
filter_types
identifier_name
type_filter.rs
use std::collections::HashSet; use botocore::{Service, ShapeType, Shape}; use super::mutate_type_name; pub fn filter_types(service: &Service) -> (HashSet<String>, HashSet<String>) { let mut deserialized_types: HashSet<String> = HashSet::new(); let mut serialized_types: HashSet<String> = HashSet::new(); for...
ShapeType::List => { recurse_find_shapes(service, types, shape.member_type()); } _ => {} } } // output shapes with a payload blob don't get deserialized // unless they have non-payload elements from the headers etc. fn can_skip_deserializer(service: &Service, output_shape: &Sha...
{ types.insert(mutate_type_name(shape_name).to_owned()); let shape = service.shapes.get(shape_name).expect("Shape type missing from service definition"); match shape.shape_type { ShapeType::Structure => { if let Some(ref members) = shape.members { for member in members.va...
identifier_body
lint-unnecessary-parens.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 ...
if (true) {} //~ ERROR unnecessary parentheses around `if` condition while (true) {} //~ ERROR unnecessary parentheses around `while` condition match (true) { //~ ERROR unnecessary parentheses around `match` head expression _ => {} } }
random_line_split
lint-unnecessary-parens.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 ...
{ foo(); if (true) {} //~ ERROR unnecessary parentheses around `if` condition while (true) {} //~ ERROR unnecessary parentheses around `while` condition match (true) { //~ ERROR unnecessary parentheses around `match` head expression _ => {} } }
identifier_body
lint-unnecessary-parens.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 ...
} }
{}
conditional_block
lint-unnecessary-parens.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 ...
() { foo(); if (true) {} //~ ERROR unnecessary parentheses around `if` condition while (true) {} //~ ERROR unnecessary parentheses around `while` condition match (true) { //~ ERROR unnecessary parentheses around `match` head expression _ => {} } }
main
identifier_name
hiphopabotamus.rs
#![feature(box_syntax)] #![feature(plugin)] #![plugin(postgres_macros,regex_macros)] use irc::event_stream::{Action, HandlerAction, Response}; use irc::protocol; use postgres::{Connection, SslMode}; use regex::Regex; use rand::{thread_rng, Rng}; use std::ascii::AsciiExt; use std::env; use std::str::FromStr; use std::s...
fn main() { env_logger::init().unwrap(); let mut opts = getopts::Options::new(); opts.reqopt("", "host", "irc server hostname", "HOSTNAME"); opts.optopt("", "port", "irc server port", "PORT"); opts.reqopt("n", "nick", "nickname", "NICK"); opts.optmulti("c", "chan", "channels to join", "CHAN")...
{ let pg = Connection::connect("postgres://leif@localhost", &SslMode::None).unwrap(); pg.execute("CREATE TABLE IF NOT EXISTS knowledge ( key VARCHAR, val VARCHAR, PRIMARY KEY(key, val) )", &[]).unwrap(); pg.execute("CREATE TABLE IF NOT EX...
identifier_body
hiphopabotamus.rs
#![feature(box_syntax)] #![feature(plugin)] #![plugin(postgres_macros,regex_macros)] use irc::event_stream::{Action, HandlerAction, Response}; use irc::protocol; use postgres::{Connection, SslMode}; use regex::Regex; use rand::{thread_rng, Rng}; use std::ascii::AsciiExt; use std::env; use std::str::FromStr; use std::s...
() { env_logger::init().unwrap(); let mut opts = getopts::Options::new(); opts.reqopt("", "host", "irc server hostname", "HOSTNAME"); opts.optopt("", "port", "irc server port", "PORT"); opts.reqopt("n", "nick", "nickname", "NICK"); opts.optmulti("c", "chan", "channels to join", "CHAN"); le...
main
identifier_name
hiphopabotamus.rs
#![feature(box_syntax)] #![feature(plugin)] #![plugin(postgres_macros,regex_macros)] use irc::event_stream::{Action, HandlerAction, Response}; use irc::protocol; use postgres::{Connection, SslMode}; use regex::Regex; use rand::{thread_rng, Rng}; use std::ascii::AsciiExt; use std::env; use std::str::FromStr; use std::s...
; if count == 0 { conn.execute(sql!("INSERT INTO karma (nick, karma) VALUES ($1, $2)"), &[&n, &change]).unwrap(); } else { conn.execute(sql!("UPDATE karma SET karma = karma + $2 WHERE nick = $1"), &[&n, &change]).unwrap(); } ...
{ -1 }
conditional_block
hiphopabotamus.rs
#![feature(box_syntax)] #![feature(plugin)] #![plugin(postgres_macros,regex_macros)] use irc::event_stream::{Action, HandlerAction, Response}; use irc::protocol; use postgres::{Connection, SslMode}; use regex::Regex; use rand::{thread_rng, Rng}; use std::ascii::AsciiExt; use std::env; use std::str::FromStr; use std::s...
} } Response::nothing() }; let join_nick = nick.clone(); let join_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&join_nick)) { if let Some(c) = regex!(r"^(join|part) (#[^\s]+)").captures(pm.ms...
.into_iter().next().and_then(|r| r.get(0)).or(Some(0)).unwrap(); return Response::respond(protocol::Privmsg::new(reply_to, &format!("{}: {}", n, k)).format()) }
random_line_split
hello.rs
use std::ops::Add; fn main() { println!("hello, world"); println!("> Primitives"); primitives(); println!("> Tuples"); tuples(); println!("> Arrays"); arrays(); println!("> Structs"); structs(); println!("> References"); references(); println!("> Enums"); enums(); } ...
fn tuples() { fn reverse(pair: (i32, i32)) -> (i32, i32) { let (x, y) = pair; (y, x) } let pair = (3, 2); let reversed = reverse(pair); println!("reversed: ({}, {})", reversed.0, reversed.1); } fn arrays() { fn sum(slice: &[i32]) -> i32 { let mut total = 0; for...
{ // List of Rust primitive types // https://doc.rust-lang.org/book/primitive-types.html println!("1 + 2 = {}", 1 + 2); println!("1 - 2 = {}", 1 - 2); println!("true and true = {}", true && true); let x: char = 'x'; println!("x = {}", x); let y: f32 = 3.14; println!("y = {}", y); }
identifier_body
hello.rs
use std::ops::Add; fn main() { println!("hello, world"); println!("> Primitives"); primitives(); println!("> Tuples"); tuples(); println!("> Arrays"); arrays(); println!("> Structs"); structs(); println!("> References"); references(); println!("> Enums"); enums(); } ...
() { // standard enum. enum Color { RED, GREEN, BLACK, }; fn categorize_color(c: Color) { match c { Color::RED => println!("color is red!"), Color::GREEN => println!("color is green!"), _ => println!("Unknown color."), } } ...
enums
identifier_name
hello.rs
use std::ops::Add; fn main() { println!("hello, world"); println!("> Primitives"); primitives(); println!("> Tuples"); tuples(); println!("> Arrays"); arrays(); println!("> Structs"); structs(); println!("> References"); references(); println!("> Enums"); enums(); } ...
enum Option { None, Some(i32), } fn app(o: Option, function: fn(i32) -> i32) -> Option { match o { Option::None => Option::None, Option::Some(x) => Option::Some(function(x)), } } fn add_one(x: i32) -> i32 { x + 1 } fn print_valu...
categorize_color(Color::BLACK); // pattern matching enum.
random_line_split
9_billion_names_of_god_the_integer.rs
// http://rosettacode.org/wiki/9_billion_names_of_God_the_integer extern crate num; use std::cmp::min; use num::{BigUint, Zero, One}; pub struct Solver { // The `cache` is a private implementation detail, // it would be an improvement to throw away unused values // from the cache (to reduce memory for la...
} #[cfg(not(test))] fn main() { let mut solver = Solver::new(); println!("rows"); for n in 1..11 { println!("{}: {}", n, solver.row_string(n)); } println!("sums"); for &y in &[23, 123, 1234, 12345] { println!("{}: {}", y, solver.row_sum(y)); } } #[cfg(test)] mod test { ...
{ for l in self.cache.len()..idx + 1 { let mut r : Vec<BigUint> = vec![Zero::zero()]; for x in 1..l + 1 { let w = { let y = &r[x-1]; let z = &self.cache[l-x][min(x, l-x)]; y + z }; ...
identifier_body
9_billion_names_of_god_the_integer.rs
// http://rosettacode.org/wiki/9_billion_names_of_God_the_integer extern crate num; use std::cmp::min; use num::{BigUint, Zero, One}; pub struct Solver { // The `cache` is a private implementation detail, // it would be an improvement to throw away unused values // from the cache (to reduce memory for la...
use num::BigUint; #[test] fn test_cumulative() { let mut solver = Solver::new(); let mut t = |n: usize, expected: &str| { assert_eq!(solver.row_sum(n), &expected.parse::<BigUint>().unwrap()); }; t(23, "1255"); t(123, "2552338241"); t(1234, "15697...
#[cfg(test)] mod test { use super::Solver;
random_line_split
9_billion_names_of_god_the_integer.rs
// http://rosettacode.org/wiki/9_billion_names_of_God_the_integer extern crate num; use std::cmp::min; use num::{BigUint, Zero, One}; pub struct Solver { // The `cache` is a private implementation detail, // it would be an improvement to throw away unused values // from the cache (to reduce memory for la...
(&mut self, idx: usize) -> &[BigUint] { for l in self.cache.len()..idx + 1 { let mut r : Vec<BigUint> = vec![Zero::zero()]; for x in 1..l + 1 { let w = { let y = &r[x-1]; let z = &self.cache[l-x][min(x, l-x)]; y...
cumulative
identifier_name
linked_list.rs
use List::*; enum List { // Cons: 元组结构体,包含一个元素和一个指向下一节点的指针 Cons(u32, Box<List>), // Nil: 末结点,表明链表结束 Nil, } impl List { // 创建一个空链表 fn new() -> List { Nil } // 向头部节点前一个位置追加元素 fn prepend(self, elem: u32) -> List { Cons(elem, Box::new(self)) } // 返回链表的长度 f...
identifier_body
linked_list.rs
use List::*; enum List { // Cons: 元组结构体,包含一个元素和一个指向下一节点的指针 Cons(u32, Box<List>), // Nil: 末结点,表明链表结束 Nil, } impl List { // 创建一个空链表 fn new() -> List { Nil } // 向头部节点前一个位置追加元素 fn prepend(self, elem: u32) -> List { Cons(elem, Box::new(self)) } // 返回链表的长度 f...
println!("{}", list.stringify()); }
println!("linked list has length: {}", list.len());
random_line_split
linked_list.rs
use List::*; enum List { // Cons: 元组结构体,包含一个元素和一个指向下一节点的指针 Cons(u32, Box<List>), // Nil: 末结点,表明链表结束 Nil, } impl List { // 创建一个空链表 fn new() -> List { Nil } // 向头部节点前一个位置追加元素 fn prepend(self, elem: u32) -> List { Cons(elem, Box::new(self)) } // 返回链表的长度 f...
// `self` 必须匹配,因为这个方法的行为取决于 `self` 的变化类型 // `self` 为 `&List` 类型,`*self` 为 `List` 类型,一个具体的 `T` 类型的匹配 // 要参考引用 `&T` 的匹配 match *self { // 不能得到 tail 的所有权,因为 `self` 是借用的; // 而是得到一个 tail 引用 Cons(_, ref tail) => 1 + tail.len(), // 基本情形:空列表的长度为 0 ...
32 {
identifier_name
pool.rs
//! Client Connection Pooling use std::borrow::ToOwned; use std::collections::HashMap; use std::io::{self, Read, Write}; use std::net::{SocketAddr, Shutdown}; use std::sync::{Arc, Mutex}; use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier}; /// The `NetworkConnector` that behaves as a connectio...
<S> { inner: Option<(Key, S)>, is_closed: bool, is_drained: bool, pool: Arc<Mutex<PoolImpl<S>>> } impl<S: NetworkStream> Read for PooledStream<S> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self.inner.as_mut().unwrap().1.read(buf) { Ok(0) => {...
PooledStream
identifier_name
pool.rs
//! Client Connection Pooling use std::borrow::ToOwned; use std::collections::HashMap; use std::io::{self, Read, Write}; use std::net::{SocketAddr, Shutdown}; use std::sync::{Arc, Mutex}; use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier}; /// The `NetworkConnector` that behaves as a connectio...
pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; { let locked = pool.inner.lock().unwrap(); assert_eq!(locked.conns.len(), 1); assert_eq!(locked.conns.get(&key).unwrap().len(), 1); } pool.connect("127.0.0.1", 3000, "http").unwrap().i...
random_line_split
pool.rs
//! Client Connection Pooling use std::borrow::ToOwned; use std::collections::HashMap; use std::io::{self, Read, Write}; use std::net::{SocketAddr, Shutdown}; use std::sync::{Arc, Mutex}; use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier}; /// The `NetworkConnector` that behaves as a connectio...
} impl<S: NetworkStream> NetworkStream for PooledStream<S> { #[inline] fn peer_addr(&mut self) -> io::Result<SocketAddr> { self.inner.as_mut().unwrap().1.peer_addr() } #[inline] fn close(&mut self, how: Shutdown) -> io::Result<()> { self.is_closed = true; self.inner.as_mut...
{ self.inner.as_mut().unwrap().1.flush() }
identifier_body
main.rs
#![feature(augmented_assignments)] #![feature(asm)] #![feature(box_syntax)] #![feature(collections)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(core_str_ext)] #![feature(core_slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(op_assign_traits)] #![feature(unbo...
} else { if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 { console.draw = true; console.redraw = true; } else { // TODO: Magical orbital hack ...
} _ => (), }
random_line_split
main.rs
#![feature(augmented_assignments)] #![feature(asm)] #![feature(box_syntax)] #![feature(collections)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(core_str_ext)] #![feature(core_slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(op_assign_traits)] #![feature(unbox...
(font_data: usize, tss_data: usize) { // Zero BSS, this initializes statics that are set to 0 { extern { static mut __bss_start: u8; static mut __bss_end: u8; } let start_ptr = &mut __bss_start; let end_ptr = &mut __bss_end; if start_ptr as *cons...
init
identifier_name
main.rs
#![feature(augmented_assignments)] #![feature(asm)] #![feature(box_syntax)] #![feature(collections)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(core_str_ext)] #![feature(core_slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(op_assign_traits)] #![feature(unbox...
context_switch(false); } } /// Event poll loop fn poll_loop() { loop { env().on_poll(); unsafe { context_switch(false) }; } } /// Event loop fn event_loop() { { let mut console = env().console.lock(); console.instant = false; } let mut cmd = String:...
{ loop { asm!("cli" : : : : "intel", "volatile"); let mut halt = true; for i in env().contexts.lock().iter().skip(1) { if i.interrupted { halt = false; break; } } if halt { asm!("sti" : : : : "intel", "vo...
identifier_body
main.rs
#![feature(augmented_assignments)] #![feature(asm)] #![feature(box_syntax)] #![feature(collections)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(core_str_ext)] #![feature(core_slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(op_assign_traits)] #![feature(unbox...
} unsafe { context_switch(false) }; } } static BSS_TEST_ZERO: usize = 0; static BSS_TEST_NONZERO: usize = usize::MAX; /// Initialize kernel unsafe fn init(font_data: usize, tss_data: usize) { // Zero BSS, this initializes statics that are set to 0 { extern { static mu...
{ console.redraw = false; console.display.flip(); }
conditional_block
cleanup-rvalue-scopes.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 ...
#![feature(macro_rules)] use std::ops::Drop; static mut FLAGS: u64 = 0; struct Box<T> { f: T } struct AddFlags { bits: u64 } fn AddFlags(bits: u64) -> AddFlags { AddFlags { bits: bits } } fn arg(exp: u64, _x: &AddFlags) { check_flags(exp); } fn pass<T>(v: T) -> T { v } fn check_flags(exp: u64) { ...
// Test that destructors for rvalue temporaries run either at end of // statement or end of block, as appropriate given the temporary // lifetime rules.
random_line_split
cleanup-rvalue-scopes.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 bits(&self) -> u64 { self.bits } } impl Drop for AddFlags { fn drop(&mut self) { unsafe { FLAGS = FLAGS + self.bits; } } } macro_rules! end_of_block( ($pat:pat, $expr:expr) => ( { println!("end_of_block({})", stringify!({let $pat = $expr...
{ check_flags(exp); self }
identifier_body
cleanup-rvalue-scopes.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 ...
(&mut self) { unsafe { FLAGS = FLAGS + self.bits; } } } macro_rules! end_of_block( ($pat:pat, $expr:expr) => ( { println!("end_of_block({})", stringify!({let $pat = $expr;})); { // Destructor here does not run until exit from the bloc...
drop
identifier_name
htmloptionelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOpti...
}
{ self.htmlelement.reflector() }
identifier_body
htmloptionelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOpti...
(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId)) } } impl HTMLOptionElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLOptionElement { HTMLOptionElement { htmlelement: HTMLElement::new_inherited(HTMLO...
is_htmloptionelement
identifier_name
htmloptionelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOpti...
use dom::document::Document; use dom::element::HTMLOptionElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLOptionElement { pub htmlelement: HTMLElem...
random_line_split
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>,...
{ let input = io::stdin().read_to_string().unwrap(); let dom: RcDom = parse(one_input(input), ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }); // The validator.nu HTML2HTML always prints a do...
identifier_body
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>,...
() { let input = io::stdin().read_to_string().unwrap(); let dom: RcDom = parse(one_input(input), ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }); // The validator.nu HTML2HTML always prints a d...
main
identifier_name
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>,...
serialize(&mut io::stdout(), &dom.document, Default::default()) .ok().expect("serialization failed"); }
.ok().expect("writing DOCTYPE failed");
random_line_split
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. ...
pub fn split_off(&mut self, at: usize) -> Vec<BTreeMap<K, V>> { self.0.split_off(at) } pub fn extend(&mut self, xs: Vec<BTreeMap<K, V>>) { self.0.extend(xs) } pub fn contains_key<Q:?Sized>(&self, key: &Q) -> bool where Q: Ord + Eq, K: Borrow<Q>, { s...
pub fn pop(&mut self) -> Option<BTreeMap<K, V>> { self.0.pop() }
random_line_split
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. ...
pub fn get_with_height<Q:?Sized>(&self, key: &Q) -> Option<(&V, usize)> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate().rev() { if let Some(def) = scope.get(key) { return Some((def, height)); } } ...
{ for scope in self.0.iter_mut().rev() { if let Some(def) = scope.remove(key) { return Some(def); } } None }
identifier_body
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. ...
<Q:?Sized>(&self, key: &Q) -> Option<usize> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate() { if scope.contains_key(key) { return Some(height); } } None } pub fn get<Q:?Sized>(&self, key:...
get_height
identifier_name
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. ...
else { unsafe { (*self.next).as_ref().and_then(|n| n.entry(key)) } } } fn add(&self, key: K, val: V) -> (&K, &V) where K: PartialEq<K>, { if self.key == key { panic!("Key already exists in map") } else { unsafe { match...
{ Some((&self.key, &self.val)) }
conditional_block
cssstylerule.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 cssparser::{Parser as CssParser, ParserInput as CssParserInput}; use cssparser::ToCss; use dom::bindings::code...
(&self, value: DOMString) { // It's not clear from the spec if we should use the stylesheet's namespaces. // https://github.com/w3c/csswg-drafts/issues/1511 let namespaces = self.cssrule.parent_stylesheet().style_stylesheet().contents.namespaces.read(); let parser = SelectorParser { ...
SetSelectorText
identifier_name
cssstylerule.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 cssparser::{Parser as CssParser, ParserInput as CssParserInput}; use cssparser::ToCss; use dom::bindings::code...
} impl SpecificCSSRule for CSSStyleRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::STYLE_RULE } fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); self.stylerule.read_with(&...
{ reflect_dom_object(box CSSStyleRule::new_inherited(parent_stylesheet, stylerule), window, CSSStyleRuleBinding::Wrap) }
identifier_body