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
main.rs
#![recursion_limit = "1024"] #[cfg(test)] extern crate float_cmp; #[cfg(test)] #[macro_use] extern crate quickcheck; #[macro_use] extern crate error_chain; #[macro_use] extern crate derive_error_chain; #[macro_use] extern crate lazy_static; extern crate clap; #[macro_use] extern crate combine; extern crate conv; e...
() { use std::sync::Arc; println!("Expr: {}", ::std::mem::size_of::<types::Expr>()); println!("String: {}", ::std::mem::size_of::<String>()); println!("Symbol: {}", ::std::mem::size_of::<types::Symbol>()); println!("Arc<Fn>: {}", ::std::mem::size_of::<Arc<types::Function>>()); println!("Arc<Macr...
main
identifier_name
main.rs
#![recursion_limit = "1024"] #[cfg(test)] extern crate float_cmp; #[cfg(test)] #[macro_use] extern crate quickcheck; #[macro_use] extern crate error_chain; #[macro_use] extern crate derive_error_chain; #[macro_use] extern crate lazy_static; extern crate clap; #[macro_use] extern crate combine; extern crate conv; e...
let env = ops::env(); if let Some(file) = matches.value_of("input") { if file == "-" { } else { match input::file(file, env.clone()) { Ok(_) => (), Err(err) => println!("{}", err), } } } if!matches.is_present...
"[input] 'Read program from file (- for stdin)'", )) .get_matches();
random_line_split
main.rs
#![recursion_limit = "1024"] #[cfg(test)] extern crate float_cmp; #[cfg(test)] #[macro_use] extern crate quickcheck; #[macro_use] extern crate error_chain; #[macro_use] extern crate derive_error_chain; #[macro_use] extern crate lazy_static; extern crate clap; #[macro_use] extern crate combine; extern crate conv; e...
)) .get_matches(); let env = ops::env(); if let Some(file) = matches.value_of("input") { if file == "-" { } else { match input::file(file, env.clone()) { Ok(_) => (), Err(err) => println!("{}", err), } ...
{ use std::sync::Arc; println!("Expr: {}", ::std::mem::size_of::<types::Expr>()); println!("String: {}", ::std::mem::size_of::<String>()); println!("Symbol: {}", ::std::mem::size_of::<types::Symbol>()); println!("Arc<Fn>: {}", ::std::mem::size_of::<Arc<types::Function>>()); println!("Arc<Macro>:...
identifier_body
cci_intrinsic.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 ...
{ unsafe { rusti::atomic_xchg(dst, src) } }
identifier_body
cci_intrinsic.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 ...
(dst: &mut int, src: int) -> int { unsafe { rusti::atomic_xchg(dst, src) } }
atomic_xchg
identifier_name
cci_intrinsic.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 atomic_xadd_acq(dst: &mut int, src: int) -> int; pub fn atomic_xadd_rel(dst: &mut int, src: int) -> int; pub fn atomic_xsub(dst: &mut int, src: int) -> int; pub fn atomic_xsub_acq(dst: &mut int, src: int) -> int; pub fn atomic_xsub_rel(dst: &mut int, src: int) -> int; ...
pub fn atomic_xadd(dst: &mut int, src: int) -> int;
random_line_split
unsendable-class.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 ...
fn main() { let cat = "kitty".to_string(); let (tx, _) = channel(); //~ ERROR `core::kinds::Send` is not implemented tx.send(foo(42, Rc::new(cat))); //~ ERROR `core::kinds::Send` is not implemented }
{ foo { i: i, j: j } }
identifier_body
unsendable-class.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 ...
// sent use std::rc::Rc; struct foo { i: int, j: Rc<String>, } fn foo(i:int, j: Rc<String>) -> foo { foo { i: i, j: j } } fn main() { let cat = "kitty".to_string(); let (tx, _) = channel(); //~ ERROR `core::kinds::Send` is not implemented tx.send(foo(42, Rc::new(cat))); //~ ERROR `...
// Test that a class with an unsendable field can't be
random_line_split
unsendable-class.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 cat = "kitty".to_string(); let (tx, _) = channel(); //~ ERROR `core::kinds::Send` is not implemented tx.send(foo(42, Rc::new(cat))); //~ ERROR `core::kinds::Send` is not implemented }
main
identifier_name
border.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Keyword, Method, PHYSICAL_SIDES, ALL_SID...
BorderImageSideWidth::Length( LengthOrPercentage::from_gecko_style_coord(&sides.data_at(${i})) .expect("sides[${i}] could not convert to LengthOrPercentager")) }, }, % endfor ...
random_line_split
border.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Keyword, Method, PHYSICAL_SIDES, ALL_SID...
(&self, sides: &mut ::gecko_bindings::structs::nsStyleSides) { use gecko_bindings::sugar::ns_style_coord::{CoordDataMut, CoordDataValue}; use gecko::values::GeckoStyleCoordConvertible; use values::generics::border::BorderImageSideWidth; % for i in range(0, 4): match self.${i} { ...
to_gecko_rect
identifier_name
border.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Keyword, Method, PHYSICAL_SIDES, ALL_SID...
pub fn from_gecko_rect(sides: &::gecko_bindings::structs::nsStyleSides) -> Option<::values::computed::BorderImageWidth> { use gecko_bindings::structs::nsStyleUnit::{eStyleUnit_Factor, eStyleUnit_Auto}; use gecko_bindings::sugar::ns_style_coord::CoordData; use gec...
{ use gecko_bindings::sugar::ns_style_coord::{CoordDataMut, CoordDataValue}; use gecko::values::GeckoStyleCoordConvertible; use values::generics::border::BorderImageSideWidth; % for i in range(0, 4): match self.${i} { BorderImageSideWidth::Auto => { s...
identifier_body
border.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Keyword, Method, PHYSICAL_SIDES, ALL_SID...
, }, % endfor ) ) } }
{ BorderImageSideWidth::Length( LengthOrPercentage::from_gecko_style_coord(&sides.data_at(${i})) .expect("sides[${i}] could not convert to LengthOrPercentager")) }
conditional_block
decompression.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; w...
pub fn http2_encoding_fromvec(&mut self, input: &Vec<u8>) { //use first encoding... if self.encoding == HTTP2ContentEncoding::HTTP2ContentEncodingUnknown { if *input == "gzip".as_bytes().to_vec() { self.encoding = HTTP2ContentEncoding::HTTP2ContentEncodingGzip; ...
encoding: HTTP2ContentEncoding::HTTP2ContentEncodingUnknown, decoder: HTTP2Decompresser::UNASSIGNED, } }
random_line_split
decompression.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; w...
else { self.encoding = HTTP2ContentEncoding::HTTP2ContentEncodingUnrecognized; } } } pub fn decompress<'a>( &'a mut self, input: &'a [u8], output: &'a mut Vec<u8>, ) -> io::Result<&'a [u8]> { match self.decoder { HTTP2Decompresser::GZIP(ref m...
{ self.encoding = HTTP2ContentEncoding::HTTP2ContentEncodingBr; self.decoder = HTTP2Decompresser::BROTLI(brotli::Decompressor::new( HTTP2cursor::new(), HTTP2_DECOMPRESSION_CHUNK_SIZE, )); }
conditional_block
decompression.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; w...
} pub enum HTTP2Decompresser { UNASSIGNED, GZIP(GzDecoder<HTTP2cursor>), BROTLI(brotli::Decompressor<HTTP2cursor>), } struct HTTP2DecoderHalf { encoding: HTTP2ContentEncoding, decoder: HTTP2Decompresser, } pub trait GetMutCursor { fn get_mut(&mut self) -> &mut HTTP2cursor; } impl GetMutCurs...
{ //use the cursor, except it turns eof into blocking error let r = self.cursor.read(buf); match r { Err(ref err) => { if err.kind() == io::ErrorKind::UnexpectedEof { return Err(io::ErrorKind::WouldBlock.into()); } } ...
identifier_body
decompression.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; w...
() -> HTTP2Decoder { HTTP2Decoder { decoder_tc: HTTP2DecoderHalf::new(), decoder_ts: HTTP2DecoderHalf::new(), } } pub fn http2_encoding_fromvec(&mut self, input: &Vec<u8>, dir: u8) { if dir == STREAM_TOCLIENT { self.decoder_tc.http2_encoding_fromvec(i...
new
identifier_name
cfgs-on-items.rs
// Copyright 2012-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...
#[cfg(fooC)] #[cfg(fooB, not(bar))] fn foo2() -> int { 3 } // fooA AND bar #[cfg(fooA, bar)] fn foo3() -> int { 2 } //!(fooA AND bar) #[cfg(not(fooA, bar))] fn foo3() -> int { 3 } pub fn main() { assert_eq!(1, foo1()); assert_eq!(3, foo2()); assert_eq!(3, foo3()); }
random_line_split
cfgs-on-items.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ assert_eq!(1, foo1()); assert_eq!(3, foo2()); assert_eq!(3, foo3()); }
identifier_body
cfgs-on-items.rs
// Copyright 2012-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...
() -> int { 3 } pub fn main() { assert_eq!(1, foo1()); assert_eq!(3, foo2()); assert_eq!(3, foo3()); }
foo3
identifier_name
neproblem.rs
use rand; use rand::{Rng, StdRng, SeedableRng}; use ea::*; use neuro::{ActivationFunctionType, MultilayeredNetwork, NeuralArchitecture, NeuralNetwork}; use problem::*; //-------------------------------------------- /// Trait for problem where NN is a solution. /// /// # Example: Custom NE problem /// ``` /// extern...
} } impl NeuroProblem for SymbolicRegressionProblem { fn get_inputs_num(&self) -> usize { 1 } fn get_outputs_num(&self) -> usize { 1 } fn get_default_net(&self) -> MultilayeredNetwork { let mut rng = rand::thread_rng(); let mut net: MultilayeredNetwork = MultilayeredNetwork::new(self.ge...
random_line_split
neproblem.rs
use rand; use rand::{Rng, StdRng, SeedableRng}; use ea::*; use neuro::{ActivationFunctionType, MultilayeredNetwork, NeuralArchitecture, NeuralNetwork}; use problem::*; //-------------------------------------------- /// Trait for problem where NN is a solution. /// /// # Example: Custom NE problem /// ``` /// extern...
fn get_default_net(&self) -> MultilayeredNetwork { let mut rng = rand::thread_rng(); let mut net: MultilayeredNetwork = MultilayeredNetwork::new(self.get_inputs_num(), self.get_outputs_num()); net.add_hidden_layer(5 as usize, ActivationFunctionType::Sigmoid) .build(&mut rng, Neur...
{ 1 }
identifier_body
neproblem.rs
use rand; use rand::{Rng, StdRng, SeedableRng}; use ea::*; use neuro::{ActivationFunctionType, MultilayeredNetwork, NeuralArchitecture, NeuralNetwork}; use problem::*; //-------------------------------------------- /// Trait for problem where NN is a solution. /// /// # Example: Custom NE problem /// ``` /// extern...
(&self) -> MultilayeredNetwork { let mut rng = rand::thread_rng(); let mut net: MultilayeredNetwork = MultilayeredNetwork::new(self.get_inputs_num(), self.get_outputs_num()); net.add_hidden_layer(5 as usize, ActivationFunctionType::Sigmoid) .build(&mut rng, NeuralArchitecture::Multila...
get_default_net
identifier_name
shortcuts.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use std::ops::Range; use ndarray::Zip; use ndarray_parallel::NdarrayIntoParallelIterator; use rayon::iter::Map; use rayon::prelude::{IntoParallelIterator, ParallelIterator}; /// Utility trait that adds shortcuts ...
R: Send; } impl<T> ParallelShortcuts for Range<T> where Range<T>: IntoParallelIterator, { type Iter = <Range<T> as IntoParallelIterator>::Iter; fn par_map<F, R>(self, map_op: F) -> Map<Self::Iter, F> where F: Fn(<Self::Iter as ParallelIterator>::Item) -> R + Sync + Send, R: Sen...
F: Fn(<Self::Iter as ParallelIterator>::Item) -> R + Sync + Send,
random_line_split
shortcuts.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use std::ops::Range; use ndarray::Zip; use ndarray_parallel::NdarrayIntoParallelIterator; use rayon::iter::Map; use rayon::prelude::{IntoParallelIterator, ParallelIterator}; /// Utility trait that adds shortcuts ...
, R>(self, map_op: F) -> Map<Self::Iter, F> where F: Fn(<Self::Iter as ParallelIterator>::Item) -> R + Sync + Send, R: Send, { self.into_par_iter().map(map_op) } } impl<Parts, D> ParallelShortcuts for Zip<Parts, D> where Zip<Parts, D>: NdarrayIntoParallelIterator, { type Ite...
r_map<F
identifier_name
shortcuts.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use std::ops::Range; use ndarray::Zip; use ndarray_parallel::NdarrayIntoParallelIterator; use rayon::iter::Map; use rayon::prelude::{IntoParallelIterator, ParallelIterator}; /// Utility trait that adds shortcuts ...
self.into_par_iter().map(map_op) } }
identifier_body
io_split.rs
#![warn(rust_2018_idioms)] #![cfg(feature = "full")] use tokio::io::{split, AsyncRead, AsyncWrite, ReadBuf, ReadHalf, WriteHalf}; use std::io; use std::pin::Pin; use std::task::{Context, Poll}; struct
; impl AsyncRead for RW { fn poll_read( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { buf.put_slice(&[b'z']); Poll::Ready(Ok(())) } } impl AsyncWrite for RW { fn poll_write( self: Pin<&mut Self>, ...
RW
identifier_name
io_split.rs
#![warn(rust_2018_idioms)] #![cfg(feature = "full")] use tokio::io::{split, AsyncRead, AsyncWrite, ReadBuf, ReadHalf, WriteHalf}; use std::io; use std::pin::Pin; use std::task::{Context, Poll}; struct RW; impl AsyncRead for RW { fn poll_read( self: Pin<&mut Self>, _cx: &mut Context<'_>, ...
fn split_stream_id() { let (r1, w1) = split(RW); let (r2, w2) = split(RW); assert!(r1.is_pair_of(&w1)); assert!(!r1.is_pair_of(&w2)); assert!(r2.is_pair_of(&w2)); assert!(!r2.is_pair_of(&w1)); } #[test] fn unsplit_ok() { let (r, w) = split(RW); r.unsplit(w); } #[test] #[should_panic] f...
} #[test]
random_line_split
io_split.rs
#![warn(rust_2018_idioms)] #![cfg(feature = "full")] use tokio::io::{split, AsyncRead, AsyncWrite, ReadBuf, ReadHalf, WriteHalf}; use std::io; use std::pin::Pin; use std::task::{Context, Poll}; struct RW; impl AsyncRead for RW { fn poll_read( self: Pin<&mut Self>, _cx: &mut Context<'_>, ...
} #[test] fn is_send_and_sync() { fn assert_bound<T: Send + Sync>() {} assert_bound::<ReadHalf<RW>>(); assert_bound::<WriteHalf<RW>>(); } #[test] fn split_stream_id() { let (r1, w1) = split(RW); let (r2, w2) = split(RW); assert!(r1.is_pair_of(&w1)); assert!(!r1.is_pair_of(&w2)); asse...
{ Poll::Ready(Ok(())) }
identifier_body
kcp_server.rs
extern crate futures; extern crate tokio_core; extern crate tokio_kcp; extern crate tokio_io; extern crate env_logger; use std::env; use std::net::SocketAddr; use futures::future::Future; use futures::stream::Stream; use tokio_core::reactor::Core; use tokio_io::AsyncRead; use tokio_io::io::copy; use tokio_kcp::KcpLis...
}); core.run(echo).unwrap(); }
Ok(())
random_line_split
kcp_server.rs
extern crate futures; extern crate tokio_core; extern crate tokio_kcp; extern crate tokio_io; extern crate env_logger; use std::env; use std::net::SocketAddr; use futures::future::Future; use futures::stream::Stream; use tokio_core::reactor::Core; use tokio_io::AsyncRead; use tokio_io::io::copy; use tokio_kcp::KcpLis...
() { // let socket = UdpSocket::bind("127.0.0.1:1234").expect("couldn't bind to address"); // // let addr = "127.0.0.1:8080".parse::<SocketAddr>().unwrap(); // // for _ in 0..20 { // socket.send_to("123123".as_bytes(), addr).expect("sendto failed"); // } // // let mut vec = vec![]; // // printl...
main
identifier_name
kcp_server.rs
extern crate futures; extern crate tokio_core; extern crate tokio_kcp; extern crate tokio_io; extern crate env_logger; use std::env; use std::net::SocketAddr; use futures::future::Future; use futures::stream::Stream; use tokio_core::reactor::Core; use tokio_io::AsyncRead; use tokio_io::io::copy; use tokio_kcp::KcpLis...
let addr = env::args() .nth(1) .unwrap_or_else(|| "192.168.12.82:1234".to_string()); let addr = addr.parse::<SocketAddr>().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); let listener = KcpListener::bind(&addr, &handle).unwrap(); println!("listening on: ...
{ // let socket = UdpSocket::bind("127.0.0.1:1234").expect("couldn't bind to address"); // // let addr = "127.0.0.1:8080".parse::<SocketAddr>().unwrap(); // // for _ in 0..20 { // socket.send_to("123123".as_bytes(), addr).expect("sendto failed"); // } // // let mut vec = vec![]; // // println!(...
identifier_body
long_tests_client.rs
use grpc::ClientStubExt; use long_tests::long_tests_pb::*; use long_tests::long_tests_pb_grpc::*; use futures::executor; use std::env; fn single_num_arg_or(cmd_args: &[String], or: u64) -> u64 { if cmd_args.len() == 0 { or } else if cmd_args.len() == 1 { cmd_args[0].parse().expect("failed to p...
else { panic!("unknown command: {}", cmd); } }
{ run_echo(client, cmd_args); }
conditional_block
long_tests_client.rs
use grpc::ClientStubExt; use long_tests::long_tests_pb::*; use long_tests::long_tests_pb_grpc::*; use futures::executor; use std::env; fn single_num_arg_or(cmd_args: &[String], or: u64) -> u64
fn run_echo(client: LongTestsClient, cmd_args: &[String]) { let count = single_num_arg_or(cmd_args, 1); println!("running {} iterations of echo", count); for i in 0..count { let payload = format!("payload {}", i); let mut req = EchoRequest::new(); req.set_payload(payload.clone()...
{ if cmd_args.len() == 0 { or } else if cmd_args.len() == 1 { cmd_args[0].parse().expect("failed to parse as u64") } else { panic!("too many args"); } }
identifier_body
long_tests_client.rs
use grpc::ClientStubExt; use long_tests::long_tests_pb::*; use long_tests::long_tests_pb_grpc::*; use futures::executor; use std::env; fn single_num_arg_or(cmd_args: &[String], or: u64) -> u64 { if cmd_args.len() == 0 { or } else if cmd_args.len() == 1 { cmd_args[0].parse().expect("failed to p...
} fn main() { env_logger::init(); let args: Vec<String> = env::args().collect(); if args.len() < 2 { panic!("too few args") } let client = LongTestsClient::new_plain("localhost", 23432, Default::default()).expect("init"); let cmd = &args[1]; let cmd_args = &args[2..]; if cmd ...
assert!(payload == r.get_payload()); } println!("done");
random_line_split
long_tests_client.rs
use grpc::ClientStubExt; use long_tests::long_tests_pb::*; use long_tests::long_tests_pb_grpc::*; use futures::executor; use std::env; fn
(cmd_args: &[String], or: u64) -> u64 { if cmd_args.len() == 0 { or } else if cmd_args.len() == 1 { cmd_args[0].parse().expect("failed to parse as u64") } else { panic!("too many args"); } } fn run_echo(client: LongTestsClient, cmd_args: &[String]) { let count = single_num_a...
single_num_arg_or
identifier_name
error.rs
//! A Status encapsulates the result of an operation. //! //! It may indicate success, //! or it may indicate an error with an associated error message. //! //! Multiple threads can invoke const methods on a Status without //! external synchronization, but if any of the threads may call a //! non-const method, all thre...
(&self) -> Severity { unsafe { mem::transmute(ll::rocks_status_severity(self.raw())) } } /// string indicating the message of the Status pub fn state(&self) -> &str { unsafe { let ptr = ll::rocks_status_get_state(self.raw()); ptr.as_ref().and_then(|s| CStr::from_ptr(...
severity
identifier_name
error.rs
//! A Status encapsulates the result of an operation. //!
//! non-const method, all threads accessing the same Status must use //! external synchronization. use std::ffi::CStr; use std::fmt; use std::mem; use std::str; use rocks_sys as ll; use crate::to_raw::{FromRaw, ToRaw}; #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Code { _Ok = 0, // wil...
//! It may indicate success, //! or it may indicate an error with an associated error message. //! //! Multiple threads can invoke const methods on a Status without //! external synchronization, but if any of the threads may call a
random_line_split
error.rs
//! A Status encapsulates the result of an operation. //! //! It may indicate success, //! or it may indicate an error with an associated error message. //! //! Multiple threads can invoke const methods on a Status without //! external synchronization, but if any of the threads may call a //! non-const method, all thre...
else { Err(Error::LowLevel(raw)) } } } impl Drop for Error { fn drop(&mut self) { if!self.raw().is_null() { unsafe { ll::rocks_status_destroy(self.raw()) } } } } impl Error { pub fn is_not_found(&self) -> bool { self.code() == Code::NotFound ...
{ Ok(()) }
conditional_block
credentials.rs
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
/// build a [`ChannelCredentials`]. pub struct ChannelCredentials { creds: *mut grpc_channel_credentials, } impl ChannelCredentials { pub fn as_mut_ptr(&mut self) -> *mut grpc_channel_credentials { self.creds } /// Try to build a [`ChannelCredentials`] to authenticate with Google OAuth credent...
/// Use [`ChannelCredentialsBuilder`] or [`ChannelCredentials::google_default_credentials`] to
random_line_split
credentials.rs
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
(mut self) -> ServerCredentials { let root_cert = self .root .take() .map_or_else(ptr::null_mut, CString::into_raw); let cert_chains = self.cert_chains.as_mut_ptr(); let private_keys = self.private_keys.as_mut_ptr(); let force_auth = if self.force_client_...
build
identifier_name
credentials.rs
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
; let credentials = unsafe { grpc_sys::grpcwrap_ssl_server_credentials_create( root_cert, cert_chains as _, private_keys as _, self.cert_chains.len(), force_auth, ) }; if!root_cert.is_null()...
{ 0 }
conditional_block
defaults-unsound-62211-1.rs
//! Regression test for https://github.com/rust-lang/rust/issues/62211 //! //! The old implementation of defaults did not check whether the provided //! default actually fulfills all bounds on the assoc. type, leading to //! unsoundness, demonstrated here as a use-after-free. //! //! Note that the underlying cause of t...
fn main() { bug(String::from("hello!")); }
{ let origin = T::make_origin(origin); let mut copy = T::unchecked_copy(&origin); // assert we indeed have 2 strings pointing to the same buffer. assert_eq!(origin.as_ptr(), copy.as_ptr()); // Drop the origin. Any use of `copy` is UB. drop(origin); copy += "This is invalid!"; println!...
identifier_body
defaults-unsound-62211-1.rs
//! Regression test for https://github.com/rust-lang/rust/issues/62211 //! //! The old implementation of defaults did not check whether the provided //! default actually fulfills all bounds on the assoc. type, leading to //! unsoundness, demonstrated here as a use-after-free. //! //! Note that the underlying cause of t...
(other: &Self::Output) -> Self::Output { (*other) } fn make_origin(s: Self) -> Self::Output { s.into() } } impl<T> UncheckedCopy for T {} fn bug<T: UncheckedCopy>(origin: T) { let origin = T::make_origin(origin); let mut copy = T::unchecked_copy(&origin); // assert we indeed ...
unchecked_copy
identifier_name
defaults-unsound-62211-1.rs
//! Regression test for https://github.com/rust-lang/rust/issues/62211 //! //! The old implementation of defaults did not check whether the provided //! default actually fulfills all bounds on the assoc. type, leading to //! unsoundness, demonstrated here as a use-after-free. //!
//! Note that the underlying cause of this is still not yet fixed. //! See: https://github.com/rust-lang/rust/issues/33017 #![feature(associated_type_defaults)] use std::{ fmt::Display, ops::{AddAssign, Deref}, }; trait UncheckedCopy: Sized { // This Output is said to be Copy. Yet we default to Self ...
random_line_split
protocol.rs
//============================================================================ // // A simple Mandelbrot image generator in Rust // // Protocol for communicating with Engine task // // Copyright (c) 2014 Gavin Baker <gavinb@antonym.org> // Published under the MIT license // //===========================================...
#[derive(Debug)] pub enum EngineCommand { UpdateRegion(f32, f32, f32, f32), ZoomIn, ZoomOut, PanLeft, PanRight, PanUp, PanDown, Render(RenderType), Shutdown, } //----------------------------------------------------------------------------
random_line_split
protocol.rs
//============================================================================ // // A simple Mandelbrot image generator in Rust // // Protocol for communicating with Engine task // // Copyright (c) 2014 Gavin Baker <gavinb@antonym.org> // Published under the MIT license // //===========================================...
{ Startup, Processing(u32), RenderComplete(RenderType, Vec<u8>), Error(u32) } //---------------------------------------------------------------------------- #[derive(Debug)] pub enum EngineCommand { UpdateRegion(f32, f32, f32, f32), ZoomIn, ZoomOut, PanLeft, PanRight, PanUp, ...
EngineStatus
identifier_name
descrobject.rs
use libc::{c_char, c_int, c_void}; use crate::methodobject::PyMethodDef; use crate::object::{PyObject, PyTypeObject, Py_TYPE}; use crate::structmember::PyMemberDef; pub type getter = unsafe extern "C" fn(slf: *mut PyObject, closure: *mut c_void) -> *mut PyObject; pub type setter = unsafe extern "C" fn(slf: *mut ...
{ pub name: *mut c_char, pub offset: c_int, pub function: *mut c_void, pub wrapper: Option<wrapperfunc>, pub doc: *mut c_char, pub flags: c_int, pub name_strobj: *mut PyObject, } impl Clone for wrapperbase { #[inline] fn clone(&self) -> wrapperbase { *self } } pub cons...
wrapperbase
identifier_name
descrobject.rs
use libc::{c_char, c_int, c_void}; use crate::methodobject::PyMethodDef; use crate::object::{PyObject, PyTypeObject, Py_TYPE}; use crate::structmember::PyMemberDef; pub type getter = unsafe extern "C" fn(slf: *mut PyObject, closure: *mut c_void) -> *mut PyObject; pub type setter = unsafe extern "C" fn(slf: *mut ...
#[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { ignore! { // PyDictProxy_New is also defined in dictobject.h pub fn PyDictProxy_New(arg1: *mut PyObject) -> *mut PyObject; } pub fn PyWrapper_New(arg1: *mut PyObject, arg2: *mut PyObject) -> *mut PyObject; }
{ (*Py_TYPE(d)).tp_descr_set.is_some() as c_int }
identifier_body
descrobject.rs
use libc::{c_char, c_int, c_void}; use crate::methodobject::PyMethodDef; use crate::object::{PyObject, PyTypeObject, Py_TYPE}; use crate::structmember::PyMemberDef; pub type getter = unsafe extern "C" fn(slf: *mut PyObject, closure: *mut c_void) -> *mut PyObject; pub type setter = unsafe extern "C" fn(slf: *mut ...
slf: *mut PyObject, args: *mut PyObject, wrapped: *mut c_void, kwds: *mut PyObject, ) -> *mut PyObject; #[repr(C)] #[derive(Copy)] pub struct wrapperbase { pub name: *mut c_char, pub offset: c_int, pub function: *mut c_void, pub wrapper: Option<wrapperfunc>, pub doc: *mut c_char, ...
args: *mut PyObject, wrapped: *mut c_void, ) -> *mut PyObject; pub type wrapperfunc_kwds = unsafe extern "C" fn(
random_line_split
stylesheet_set.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/. */ //! A centralized set of stylesheets for a document. use dom::TElement; use invalidation::stylesheets::Stylesheet...
(&self) -> StylesheetIterator<S> { StylesheetIterator(self.entries.iter()) } /// Mark the stylesheets as dirty, because something external may have /// invalidated it. /// /// FIXME(emilio): Make this more granular. pub fn force_dirty(&mut self) { for (data, _) in self.invalidat...
iter
identifier_name
stylesheet_set.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/. */ //! A centralized set of stylesheets for a document. use dom::TElement; use invalidation::stylesheets::Stylesheet...
} /// The set of stylesheets effective for a given document. pub struct StylesheetSet<S> where S: StylesheetInDocument + PartialEq +'static, { /// The actual list of all the stylesheets that apply to the given document, /// each stylesheet associated with a unique ID. /// /// This is only a list o...
{ self.0.next().map(|entry| &entry.sheet) }
identifier_body
stylesheet_set.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/. */ //! A centralized set of stylesheets for a document. use dom::TElement; use invalidation::stylesheets::Stylesheet...
impl<S> StylesheetSet<S> where S: StylesheetInDocument + PartialEq +'static, { /// Create a new empty StylesheetSet. pub fn new() -> Self { StylesheetSet { entries: vec![], invalidation_data: Default::default(), author_style_disabled: false, } } /...
}
random_line_split
stylesheet_set.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/. */ //! A centralized set of stylesheets for a document. use dom::TElement; use invalidation::stylesheets::Stylesheet...
} self.iter() } /// Returns an iterator over the current list of stylesheets. pub fn iter(&self) -> StylesheetIterator<S> { StylesheetIterator(self.entries.iter()) } /// Mark the stylesheets as dirty, because something external may have /// invalidated it. /// ...
{ data.invalidations.flush(document_element); data.dirty = false; }
conditional_block
push.rs
/* * Copyright 2018 Google Inc. All rights reserved. * * 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 applica...
(&self, o: usize) -> Self { PushAlignment::new(max(self.0, o)) } } /// Macro to implement Push for EndianScalar types. macro_rules! impl_push_for_endian_scalar { ($ty:ident) => { impl Push for $ty { type Output = $ty; #[inline] fn push(&self, dst: &mut [u8],...
max_of
identifier_name
push.rs
/* * Copyright 2018 Google Inc. All rights reserved. * * 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 applica...
} /// Ensure Push alignment calculations are typesafe (because this helps reduce /// implementation issues when using FlatBufferBuilder::align). pub struct PushAlignment(usize); impl PushAlignment { #[inline] pub fn new(x: usize) -> Self { PushAlignment { 0: x } } #[inline] pub fn value(&s...
{ PushAlignment::new(align_of::<Self::Output>()) }
identifier_body
push.rs
/* * Copyright 2018 Google Inc. All rights reserved. * * 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 applica...
impl_push_for_endian_scalar!(i16); impl_push_for_endian_scalar!(u32); impl_push_for_endian_scalar!(i32); impl_push_for_endian_scalar!(u64); impl_push_for_endian_scalar!(i64); impl_push_for_endian_scalar!(f32); impl_push_for_endian_scalar!(f64);
impl_push_for_endian_scalar!(u16);
random_line_split
event.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Core/async/event.rs //! Asynchronous event waiter #[allow(unused_imports)] use prelude::*; use core::sync::atomic::{AtomicBool,ATOMIC_BOOL_INIT,Ordering}; use core::fmt; /// A general-purpose wait event (when flag is set, waiters will be informed) /// /// On...
}
{ if let Some(r) = self.source { *r.waiter.lock() = None; } }
identifier_body
event.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Core/async/event.rs //! Asynchronous event waiter #[allow(unused_imports)] use prelude::*; use core::sync::atomic::{AtomicBool,ATOMIC_BOOL_INIT,Ordering}; use core::fmt; /// A general-purpose wait event (when flag is set, waiters will be informed) /// /// On...
(&self) { //log_debug!("Trigger"); self.flag.store(true, Ordering::SeqCst); // prevents reodering around this self.waiter.lock().as_mut().map(|r| r.signal()); } /// Register to wake the specified sleep object pub fn wait_upon(&self, waiter: &mut ::threads::SleepObject) -> bool { { let mut lh = self.wai...
trigger
identifier_name
event.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Core/async/event.rs //! Asynchronous event waiter #[allow(unused_imports)] use prelude::*; use core::sync::atomic::{AtomicBool,ATOMIC_BOOL_INIT,Ordering}; use core::fmt; /// A general-purpose wait event (when flag is set, waiters will be informed) /// /// On...
} /// Event waiter pub struct Waiter<'a> { /// Event source source: Option<&'a Source>, } //static S_EVENT_NONE: Source = Source { flag: ATOMIC_BOOL_INIT, waiter: mutex_init!(None) }; impl Source { /// Create a new event source pub fn new() -> Source { Source { flag: ATOMIC_BOOL_INIT, waiter: ::sync::mu...
pub struct ManySource { flag: AtomicBool, waiters: super::queue::Source,
random_line_split
event.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Core/async/event.rs //! Asynchronous event waiter #[allow(unused_imports)] use prelude::*; use core::sync::atomic::{AtomicBool,ATOMIC_BOOL_INIT,Ordering}; use core::fmt; /// A general-purpose wait event (when flag is set, waiters will be informed) /// /// On...
else { // Completed, don't impede sleeping true } } fn unbind_signal(&mut self) { if let Some(r) = self.source { *r.waiter.lock() = None; } } }
{ // Store the sleep object reference *r.waiter.lock() = Some( sleeper.get_ref() ); // If the waiter's flag is already set, return 'false' to force polling ! r.flag.load(::core::sync::atomic::Ordering::Relaxed) }
conditional_block
csssupportsrule.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, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
} } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self....
{ let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports), ...
conditional_block
csssupportsrule.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, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule.enabled = enabled; } } } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleC...
let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports), PARSING_MODE_DEFAULT, quirks_mode); let enabled = cond.eval(&context); ...
random_line_split
csssupportsrule.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, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
} impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.suppor...
{ let mut input = ParserInput::new(&text); let mut input = Parser::new(&mut input); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond { let global = self.global(); let win = global.as_window(); let url = win.Document().url(); ...
identifier_body
csssupportsrule.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, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn set_condition_text(&self, text:...
get_condition_text
identifier_name
netns_linux.rs
extern crate nix; use std::error::Error; use std::fmt; use std::path::PathBuf; use nix::sched::{unshare, setns}; use nix::fcntl::open; use nix::unistd::{getpid, gettid}; use nix::sys::stat::Mode; use nix::Error as NError; pub struct NetNS { fd: i32, path: PathBuf, } #[derive(Debug)] pub enum NetNSError { ...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "NetNS {{ fd: {}, path: {} }}", self.fd, self.path.display()) } } impl NetNS { pub fn new() -> Result<NetNS, NetNSError> { unshare(nix::sched::CLONE_NEWNET).expect("failed"); NetNS::get() } pub fn get() -> Result<NetNS,...
fmt
identifier_name
netns_linux.rs
extern crate nix; use std::error::Error; use std::fmt; use std::path::PathBuf; use nix::sched::{unshare, setns}; use nix::fcntl::open; use nix::unistd::{getpid, gettid}; use nix::sys::stat::Mode; use nix::Error as NError; pub struct NetNS { fd: i32, path: PathBuf, } #[derive(Debug)] pub enum NetNSError { ...
pub fn set(ns: NetNS) -> Result<(), NError> { setns(ns.fd, nix::sched::CLONE_NEWNET) } pub fn get_from_thread(pid: i32, tid: i32) -> Result<NetNS, NetNSError> { return NetNS::get_from_path(PathBuf::from(format!("/proc/{}/task/{}/ns/net", pid, tid) .as_str())); } pub fn...
{ return NetNS::get_from_thread(getpid(), gettid()); }
identifier_body
netns_linux.rs
extern crate nix; use std::error::Error; use std::fmt;
use nix::unistd::{getpid, gettid}; use nix::sys::stat::Mode; use nix::Error as NError; pub struct NetNS { fd: i32, path: PathBuf, } #[derive(Debug)] pub enum NetNSError { CreateNetNSError, } impl Error for NetNSError { fn description(&self) -> &str { "Cannot create" } } impl fmt::Debug f...
use std::path::PathBuf; use nix::sched::{unshare, setns}; use nix::fcntl::open;
random_line_split
rest_mod.rs
///! A helper to make local computer browsing of file paths possible ///! on smarter devices a dialog would do it.... use dirs; use std::{fs, path::Path, string::String, vec::Vec}; pub fn return_directory(given: String) -> Vec<String>
if entry.is_err() { continue; } let entry = entry.unwrap(); // filter out ".dirs" if entry.file_name().to_str().unwrap_or("").starts_with(".") { continue; ...
{ let trying_path = if given.is_empty() { dirs::home_dir() } else { Path::new(&given).canonicalize().ok() }; match trying_path { Some(try_as_dir) => { if let Ok(good_dir) = fs::read_dir(&try_as_dir) { let mut return_vec = vec![]; // a...
identifier_body
rest_mod.rs
///! A helper to make local computer browsing of file paths possible ///! on smarter devices a dialog would do it.... use dirs; use std::{fs, path::Path, string::String, vec::Vec}; pub fn return_directory(given: String) -> Vec<String> { let trying_path = if given.is_empty() { dirs::home_dir() } else { ...
} for entry in good_dir { if entry.is_err() { continue; } let entry = entry.unwrap(); // filter out ".dirs" if entry.file_name().to_str().unwrap_or("").starts_wit...
{ return_vec.push(parent_unicode_str.to_string()); }
conditional_block
rest_mod.rs
///! A helper to make local computer browsing of file paths possible ///! on smarter devices a dialog would do it.... use dirs; use std::{fs, path::Path, string::String, vec::Vec}; pub fn return_directory(given: String) -> Vec<String> { let trying_path = if given.is_empty() { dirs::home_dir() } else { ...
for entry in good_dir { if entry.is_err() { continue; } let entry = entry.unwrap(); // filter out ".dirs" if entry.file_name().to_str().unwrap_or("").starts_with(".") { ...
}
random_line_split
rest_mod.rs
///! A helper to make local computer browsing of file paths possible ///! on smarter devices a dialog would do it.... use dirs; use std::{fs, path::Path, string::String, vec::Vec}; pub fn
(given: String) -> Vec<String> { let trying_path = if given.is_empty() { dirs::home_dir() } else { Path::new(&given).canonicalize().ok() }; match trying_path { Some(try_as_dir) => { if let Ok(good_dir) = fs::read_dir(&try_as_dir) { let mut return_vec ...
return_directory
identifier_name
scanner.rs
use std::old_io as io; use std::fmt; #[derive(Debug, PartialEq)] pub enum Token { BinOp(&'static str), Number(i64), EOL, EOF, } impl fmt::String for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Token::BinOp(ref op) => write!(f, "BinOp: {}", op), ...
} struct MockReader { ch: char } impl Reader for MockReader { fn read_byte(&mut self) -> io::IoResult<u8> { Ok('+' as u8) } fn read(&mut self, buf: &mut [u8]) -> io::IoResult<usize> { Ok(0) } } #[test] fn add_token() { let mut scanner = Scanner::new(MockReader{ch: '+'}); l...
Ok(c) => {debug!("curr char: {}", c); Ok(c as char) }, Err(e) => Err(e), }; }
random_line_split
scanner.rs
use std::old_io as io; use std::fmt; #[derive(Debug, PartialEq)] pub enum Token { BinOp(&'static str), Number(i64), EOL, EOF, } impl fmt::String for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} pub struct Scanner<R: io::Reader> { curr_char: io::IoResult<char>, reader: R, } impl<R: io::Reader> Scanner<R> { pub fn new(r: R) -> Scanner<R> { let mut scanner = Scanner { curr_char: Result::Ok(' '), reader: r, }; scanner.get_char(); return scan...
{ match *self { Token::BinOp(ref op) => write!(f, "BinOp: {}", op), Token::Number(n) => write!(f, "Number: {}", n), Token::EOF => write!(f, "EOF"), Token::EOL => write!(f, "EOL"), } }
identifier_body
scanner.rs
use std::old_io as io; use std::fmt; #[derive(Debug, PartialEq)] pub enum Token { BinOp(&'static str), Number(i64), EOL, EOF, } impl fmt::String for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Token::BinOp(ref op) => write!(f, "BinOp: {}", op), ...
, Ok(c) if c.is_digit(10) => Ok(Token::Number(self.get_number())), Ok(_) => { self.get_char(); Err("Unknown symbol") }, Err(ref e) => { Ok(Token::EOF) }, } } fn get_number(&mut self) -> i64 { let mut number = 0i64; loop { match self.curr_c...
{ self.curr_char = Ok(' '); Ok(Token::EOL) }
conditional_block
scanner.rs
use std::old_io as io; use std::fmt; #[derive(Debug, PartialEq)] pub enum Token { BinOp(&'static str), Number(i64), EOL, EOF, } impl fmt::String for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Token::BinOp(ref op) => write!(f, "BinOp: {}", op), ...
(&mut self) -> Result<Token, &'static str> { match self.curr_char { Ok(' ') => { self.get_char(); self.get_token() }, Ok('+') => { self.get_char(); Ok(Token::BinOp("+")) }, Ok('-') => { self.get_char(); Ok(Token::BinOp("-")) }, Ok('*') => { self.get_char(); Ok(Tok...
get_token
identifier_name
dns.rs
use std::io; use std::net::{SocketAddr, ToSocketAddrs}; use std::vec; use ::futures::{Future, Poll}; use ::futures_cpupool::{CpuPool, CpuFuture}; #[derive(Clone)] pub struct Dns { pool: CpuPool, } impl Dns { pub fn new(threads: usize) -> Dns { Dns { pool: CpuPool::new(threads) } ...
(CpuFuture<IpAddrs, io::Error>); impl Future for Query { type Item = IpAddrs; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.0.poll() } } pub struct IpAddrs { iter: vec::IntoIter<SocketAddr>, } impl Iterator for IpAddrs { type Item = SocketAddr; ...
Query
identifier_name
dns.rs
use std::io; use std::net::{SocketAddr, ToSocketAddrs}; use std::vec; use ::futures::{Future, Poll}; use ::futures_cpupool::{CpuPool, CpuFuture}; #[derive(Clone)] pub struct Dns { pool: CpuPool, } impl Dns { pub fn new(threads: usize) -> Dns { Dns { pool: CpuPool::new(threads) } ...
type Item = SocketAddr; #[inline] fn next(&mut self) -> Option<SocketAddr> { self.iter.next() } } pub type Answer = io::Result<IpAddrs>; fn work(hostname: String, port: u16) -> Answer { debug!("resolve {:?}:{:?}", hostname, port); (&*hostname, port).to_socket_addrs().map(|i| IpAddrs { ...
impl Iterator for IpAddrs {
random_line_split
box_renderer.rs
use cgmath::{self, Vector2}; use gfx; use gfx_device_gl; use gfx_device_gl::{Resources}; use gfx::{Device, CommandQueue,FrameSync, GraphicsPoolExt, Surface, Swapchain, SwapchainExt, WindowExt}; use gfx::traits::DeviceExt; use graphics::render_thread::{RenderPackage, RenderThread}; type ColorFormat = gfx::for...
{ pub pos: Vector2<f32>, pub scale: Vector2<f32>, pub z_rotation: f32, pub color: [f32; 3], } pub struct BoxRenderer { pso: gfx::PipelineState<Resources, BoxPipeLine::Meta>, graphics_pool: gfx::GraphicsCommandPool<gfx_device_gl::Backend>, } impl BoxRenderer { pub fn new(device: &mut ...
BoxRenderData
identifier_name
box_renderer.rs
use cgmath::{self, Vector2}; use gfx; use gfx_device_gl; use gfx_device_gl::{Resources}; use gfx::{Device, CommandQueue,FrameSync, GraphicsPoolExt, Surface, Swapchain, SwapchainExt, WindowExt}; use gfx::traits::DeviceExt; use graphics::render_thread::{RenderPackage, RenderThread}; type ColorFormat = gfx::for...
pub fn render_boxes(&mut self, boxes_to_render: &Vec<BoxRenderData>, render_package: &mut RenderPackage, view: &gfx::handle::RenderTargetView<gfx_device_gl::Resources, (gfx::format::R8_G8_B8_A8, gfx::format::Unorm)>, rt : &mut RenderThread) { let mut vertex_info = vec![]; let mut index_in...
{ let pso = device.create_pipeline_simple( include_bytes!(concat!( env!("CARGO_MANIFEST_DIR"), "/shaders/box_shader.vs" )), include_bytes!(concat!( env!("CARGO_MANIFEST_DIR"), "/shaders/b...
identifier_body
box_renderer.rs
use cgmath::{self, Vector2}; use gfx; use gfx_device_gl; use gfx_device_gl::{Resources}; use gfx::{Device, CommandQueue,FrameSync, GraphicsPoolExt, Surface, Swapchain, SwapchainExt, WindowExt}; use gfx::traits::DeviceExt; use graphics::render_thread::{RenderPackage, RenderThread}; type ColorFormat = gfx::for...
out: view.clone(), }; { let mut box_encoder = self.graphics_pool.acquire_graphics_encoder(); let _ = box_encoder.update_buffer(&box_data.perp, &[t], 0); box_encoder.clear(&box_data.out, BLACK); box_encoder.draw(&index_buffer, &self.pso, &box_d...
vbuf: vertex_buffer.clone(), perp: constant_buffer,
random_line_split
trie.rs
// [leetcode 208](https://leetcode.com/problems/implement-trie-prefix-tree/) #[derive(Default, Debug)] struct Trie { is_ending: bool, nodes: [Option<Box<Trie>>; 26], } impl Trie { fn new() -> Self { Default::default() } fn insert(&mut self, word: &str)
fn find(&self, word: &str) -> bool { let mut curr = self; for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) { match curr.nodes[i].as_ref() { Some(node) => { curr = node; }, None => { return false; }, } } curr...
{ let mut curr = self; for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) { curr = curr.nodes[i].get_or_insert_with(|| Box::new(Trie::new())); } curr.is_ending = true; }
identifier_body
trie.rs
// [leetcode 208](https://leetcode.com/problems/implement-trie-prefix-tree/) #[derive(Default, Debug)] struct Trie { is_ending: bool, nodes: [Option<Box<Trie>>; 26], } impl Trie { fn new() -> Self { Default::default() } fn insert(&mut self, word: &str) { let mut curr = self; ...
(&self, word: &str) -> bool { let mut curr = self; for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) { match curr.nodes[i].as_ref() { Some(node) => { curr = node; }, None => { return false; }, } } curr.is_ending ...
find
identifier_name
trie.rs
// [leetcode 208](https://leetcode.com/problems/implement-trie-prefix-tree/) #[derive(Default, Debug)] struct Trie { is_ending: bool, nodes: [Option<Box<Trie>>; 26], } impl Trie { fn new() -> Self { Default::default() } fn insert(&mut self, word: &str) { let mut curr = self; ...
, None => { return false; }, } } curr.is_ending } } fn main() { let mut m = Trie::new(); m.insert("hello"); m.insert("she"); println!("{:?}", m); let r = m.search("hello"); println!("{}", r); // true }
{ curr = node; }
conditional_block
trie.rs
// [leetcode 208](https://leetcode.com/problems/implement-trie-prefix-tree/) #[derive(Default, Debug)]
is_ending: bool, nodes: [Option<Box<Trie>>; 26], } impl Trie { fn new() -> Self { Default::default() } fn insert(&mut self, word: &str) { let mut curr = self; for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) { curr = curr.nodes[i].get_or_i...
struct Trie {
random_line_split
font.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/. */ // NOTE: https://www.chromium.org/directwrite-font-proxy has useful // information for an approach that we'll like...
(em: f64) -> f64 { em * 16. } fn au_from_em(em: f64) -> Au { Au::from_f64_px(em_to_px(em)) } fn au_from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } pub struct FontTable { data: Vec<u8>, } impl FontTable { pub fn wrap(data: &[u8]) -> FontTable { FontTable { data: data.to_vec() } } } impl F...
em_to_px
identifier_name
font.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/. */ // NOTE: https://www.chromium.org/directwrite-font-proxy has useful // information for an approach that we'll like...
}
{ self.font_data.identifier.clone() }
identifier_body
font.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/. */ // NOTE: https://www.chromium.org/directwrite-font-proxy has useful // information for an approach that we'll like...
family_name: font.family_name(), face_name: font.face_name(), style, weight, stretch, }) } } #[derive(Debug)] pub struct FontHandle { font_data: Arc<FontTemplateData>, face: FontFace, info: FontInfo, em_size: f32, du_per_em: f3...
FontStretch::ExtraExpanded => FontStretchKeyword::ExtraExpanded, FontStretch::UltraExpanded => FontStretchKeyword::UltraExpanded, }.compute()); Ok(FontInfo {
random_line_split
issue-15919.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 ...
() { let x = [0usize; 0xffff_ffff_ffff_ffff]; }
main
identifier_name
issue-15919.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 ...
}
#[cfg(target_pointer_width = "64")] fn main() { let x = [0usize; 0xffff_ffff_ffff_ffff];
random_line_split
issue-15919.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 ...
#[cfg(target_pointer_width = "64")] fn main() { let x = [0usize; 0xffff_ffff_ffff_ffff]; }
{ let x = [0usize; 0xffff_ffff]; }
identifier_body
helpers.rs
use CreationError; use GlAttributes; use GlProfile; use GlRequest; use PixelFormatRequirements; use ReleaseBehavior; use cocoa::appkit::*; pub fn
<T>(pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&T>) -> Result<Vec<u32>, CreationError> { let profile = match (opengl.version, opengl.version.to_gl_version(), opengl.profile) { // Note: we are not using ranges because of a rust bug that should be fixed here: // https://github.com/...
build_nsattributes
identifier_name
helpers.rs
use CreationError; use GlAttributes; use GlProfile; use GlRequest; use PixelFormatRequirements; use ReleaseBehavior; use cocoa::appkit::*; pub fn build_nsattributes<T>(pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&T>) -> Result<Vec<u32>, CreationError>
(_, Some((3, 0)), _) => NSOpenGLProfileVersionLegacy as u32, (_, Some((3, 1)), _) => NSOpenGLProfileVersionLegacy as u32, (_, Some((3, 2)), _) => NSOpenGLProfileVersion3_2Core as u32, (_, Some((3, _)), Some(GlProfile::Compatibility)) => return Err(CreationError::OpenGlVersionNotSupported...
{ let profile = match (opengl.version, opengl.version.to_gl_version(), opengl.profile) { // Note: we are not using ranges because of a rust bug that should be fixed here: // https://github.com/rust-lang/rust/pull/27050 (GlRequest::Latest, _, Some(GlProfile::Compatibility)) => NSOpenGLProf...
identifier_body
helpers.rs
use CreationError; use GlAttributes; use GlProfile; use GlRequest; use PixelFormatRequirements; use ReleaseBehavior; use cocoa::appkit::*; pub fn build_nsattributes<T>(pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&T>) -> Result<Vec<u32>, CreationError> { let profile = match (opengl.version, opengl...
// color component's bit size. Instead we can only specify the // full color size and hope for the best. Another hiccup is that // `NSOpenGLPFAColorSize` also includes `NSOpenGLPFAAlphaSize`, // so we have to account for that as well. let alpha_depth = pf_reqs.alpha_bits.unwrap_or(8); let color_...
random_line_split
y.rs
#!/usr/bin/env bash #![allow()] /*This line is ignored by bash # This block is ignored by rustc set -e echo "[BUILD] y.rs" 1>&2 rustc $0 -o ${0/.rs/.bin} -g exec ${0/.rs/.bin} $@ */ //! The build system for cg_clif //! //! # Manual compilation //! //! If your system doesn't support shell scripts you can manually compi...
() { eprintln!("Usage:"); eprintln!(" ./y.rs prepare"); eprintln!(" ./y.rs build [--debug] [--sysroot none|clif|llvm] [--target-dir DIR]"); } macro_rules! arg_error { ($($err:tt)*) => {{ eprintln!($($err)*); usage(); std::process::exit(1); }}; } enum Command { Build, } ...
usage
identifier_name
y.rs
#!/usr/bin/env bash #![allow()] /*This line is ignored by bash # This block is ignored by rustc set -e echo "[BUILD] y.rs" 1>&2 rustc $0 -o ${0/.rs/.bin} -g exec ${0/.rs/.bin} $@ */ //! The build system for cg_clif //! //! # Manual compilation //! //! If your system doesn't support shell scripts you can manually compi...
env::set_var("CG_CLIF_DISABLE_INCR_CACHE", "1"); // The target dir is expected in the default location. Guard against the user changing it. env::set_var("CARGO_TARGET_DIR", "target"); let mut args = env::args().skip(1); let command = match args.next().as_deref() { Some("prepare") => { ...
env::set_var("CG_CLIF_DISPLAY_CG_TIME", "1");
random_line_split
lib.rs
// The MIT License (MIT) // // Copyright (c) 2016 Skylor R. Schermer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to...
};
random_line_split
resman.rs
use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::fs::File; use std::path::PathBuf; use digest::Digest; use sha2::Sha256; use routing::EffectId; /// Resource manager. Where to search for various file types (e.g. Effects). /// Uses a 'dumb' implementation - doesn't try to auto-configure pa...
fn slice_to_array32(slice: &[u8]) -> [u8; 32] { let mut ret: [u8; 32] = Default::default(); ret.copy_from_slice(slice); ret }
/// Create a 32-entry array from a slice.
random_line_split
resman.rs
use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::fs::File; use std::path::PathBuf; use digest::Digest; use sha2::Sha256; use routing::EffectId; /// Resource manager. Where to search for various file types (e.g. Effects). /// Uses a 'dumb' implementation - doesn't try to auto-configure pa...
}) // DirEntry -> Path .map(|dir_entry| { dir_entry.path() }); prioritized.chain(all_files) } } impl ResCache { /// Call upon discovery of a file's hash. fn notify_sha256(&mut self, path: PathBuf, sha256: [u8; 32]) { self.sha256_to_path.insert(sha...
{ false }
conditional_block
resman.rs
use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::fs::File; use std::path::PathBuf; use digest::Digest; use sha2::Sha256; use routing::EffectId; /// Resource manager. Where to search for various file types (e.g. Effects). /// Uses a 'dumb' implementation - doesn't try to auto-configure pa...
(&mut self, dir: PathBuf) { self.dirs.push(dir); } /// Returns all definitions of the given effect in the form of an iterator /// over boxed objects implementing io::Read. pub fn find_effect<'a>(&'a self, id: &'a EffectId) -> impl Iterator<Item=(PathBuf, File)> + 'a { self.iter_effect_...
add_dir
identifier_name