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 |
|---|---|---|---|---|
socks4.rs | //! Socks4a Protocol Definition
//!
//! <http://ftp.icm.edu.pl/packages/socks/socks4/SOCKS4.protocol>
#![allow(dead_code)]
use std::{
fmt,
io::{self, ErrorKind},
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
};
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, BytesMut};
use thiserror::Error;
use t... | }
/// Writes to buffer
pub fn write_to_buf<B: BufMut>(&self, buf: &mut B) {
let HandshakeResponse { ref cd } = *self;
buf.put_slice(&[
// VN: Result Code's version, must be 0
0x00,
// CD: Result Code
cd.as_u8(),
// DSTPORT: Ignore... | w.write_all(&buf).await | random_line_split |
text_mark.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use TextBuffer;
use ffi;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct TextMark(Object<ffi::GtkTextMark>);
match fn {
get_type => || ffi::gtk_text_mark_get_type(),
}
}
impl TextMark {
... | (&self) -> Option<String> {
unsafe {
from_glib_none(ffi::gtk_text_mark_get_name(self.to_glib_none().0))
}
}
fn get_visible(&self) -> bool {
unsafe {
from_glib(ffi::gtk_text_mark_get_visible(self.to_glib_none().0))
}
}
fn set_visible(&self, settin... | get_name | identifier_name |
text_mark.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use TextBuffer;
use ffi;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct TextMark(Object<ffi::GtkTextMark>);
match fn {
get_type => || ffi::gtk_text_mark_get_type(),
}
}
impl TextMark {
... | }
}
fn get_name(&self) -> Option<String> {
unsafe {
from_glib_none(ffi::gtk_text_mark_get_name(self.to_glib_none().0))
}
}
fn get_visible(&self) -> bool {
unsafe {
from_glib(ffi::gtk_text_mark_get_visible(self.to_glib_none().0))
}
}
... | random_line_split | |
text_mark.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use TextBuffer;
use ffi;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct TextMark(Object<ffi::GtkTextMark>);
match fn {
get_type => || ffi::gtk_text_mark_get_type(),
}
}
impl TextMark {
... |
fn get_name(&self) -> Option<String> {
unsafe {
from_glib_none(ffi::gtk_text_mark_get_name(self.to_glib_none().0))
}
}
fn get_visible(&self) -> bool {
unsafe {
from_glib(ffi::gtk_text_mark_get_visible(self.to_glib_none().0))
}
}
fn set_visi... | {
unsafe {
from_glib(ffi::gtk_text_mark_get_left_gravity(self.to_glib_none().0))
}
} | identifier_body |
gamma.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let mut f = FisherF::new(2.0, 32.0);
let mut rng = ::test::rng();
for _ in range(0u, 1000) {
f.sample(&mut rng);
f.ind_sample(&mut rng);
}
}
#[test]
fn test_t() {
let mut t = StudentT::new(11.0);
let mut rng = ::test::rng();
fo... | fn test_f() { | random_line_split |
gamma.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | entT {
assert!(n > 0.0, "StudentT::new called with `n <= 0`");
StudentT {
chi: ChiSquared::new(n),
dof: n
}
}
}
impl Sample<f64> for StudentT {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for StudentT {
... | tud | identifier_name |
gamma.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | mma = Gamma::new(0.1, 1.0);
let mut rng = ::test::weak_rng();
b.iter(|| {
for _ in range(0, ::RAND_BENCH_N) {
gamma.ind_sample(&mut rng);
}
});
b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N;
}
}
| identifier_body | |
gamma.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let v = v_cbrt * v_cbrt * v_cbrt;
let Open01(u) = rng.gen::<Open01<f64>>();
let x_sqr = x * x;
if u < 1.0 - 0.0331 * x_sqr * x_sqr ||
u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) {
return self.d * v * self.scale
}
}
... | ^3 <= 0 iff a <= 0
continue
}
| conditional_block |
mod.rs | // This file is part of Rubik.
// Copyright Peter Beard, licensed under the GPLv3. See LICENSE for details.
//
//! Algorithms for solving Rubik's cubes
use super::cube::{Cube, Move};
/// Trait for things that can solve Rubik's cubes
pub trait Solver {
/// Calculate a sequence of moves that puts the cube in the sol... |
}
/// Solver that uses a simple iterative deepening algorithm
///
/// This algorithm is very slow and probably won't halt in a reasonable time for
/// most cubes
///
/// # Example
/// ```
/// use rubik::cube::Cube;
/// use rubik::solver::IDSolver;
///
/// let mut c = Cube::new();
/// let mut ids = IDSolver::new();
/... | {
vec![]
} | identifier_body |
mod.rs | // This file is part of Rubik.
// Copyright Peter Beard, licensed under the GPLv3. See LICENSE for details.
//
//! Algorithms for solving Rubik's cubes
use super::cube::{Cube, Move};
/// Trait for things that can solve Rubik's cubes
pub trait Solver {
/// Calculate a sequence of moves that puts the cube in the sol... |
if let Some(ms) = dbsearch(&s, maxdepth - 1) {
moves.append(&mut ms.clone());
break;
} else {
moves.pop();
}
}
if moves.len() > 0 {
Some(moves)
} else {
None
}
}
| {
break;
} | conditional_block |
mod.rs | // This file is part of Rubik.
// Copyright Peter Beard, licensed under the GPLv3. See LICENSE for details.
//
//! Algorithms for solving Rubik's cubes
use super::cube::{Cube, Move};
/// Trait for things that can solve Rubik's cubes
pub trait Solver {
/// Calculate a sequence of moves that puts the cube in the sol... |
impl IDSolver {
/// Create a new solver with the default maximum depth of 26
/// (all cubes are solveable in at most 26 moves)
pub fn new() -> IDSolver {
IDSolver {
max_depth: 26u8,
}
}
/// Create a solver with the given maximum depth (max number of moves)
pub fn wi... | /// assert!(c.is_solved());
/// ```
pub struct IDSolver {
max_depth: u8,
} | random_line_split |
mod.rs | // This file is part of Rubik.
// Copyright Peter Beard, licensed under the GPLv3. See LICENSE for details.
//
//! Algorithms for solving Rubik's cubes
use super::cube::{Cube, Move};
/// Trait for things that can solve Rubik's cubes
pub trait Solver {
/// Calculate a sequence of moves that puts the cube in the sol... | () -> NullSolver {
NullSolver
}
}
impl Solver for NullSolver {
fn find_solution(&mut self, _: &Cube) -> Vec<Move> {
vec![]
}
}
/// Solver that uses a simple iterative deepening algorithm
///
/// This algorithm is very slow and probably won't halt in a reasonable time for
/// most cubes
//... | new | identifier_name |
lib.rs | //! # Elektra
//! Safe bindings for [libelektra](https://www.libelektra.org).
//!
//! See the [project's readme](https://master.libelektra.org/src/bindings/rust) for an introduction and examples.
//!
//! The crate consists of three major parts.
//!
//! - The [keys](key/index.html) that encapsulate name, value and metai... | pub mod kdb;
pub use self::key::{BinaryKey, StringKey, MetaIter, NameIter, KeyNameInvalidError, KeyNameReadOnlyError, KeyNotFoundError, CopyOption};
pub use self::keybuilder::KeyBuilder;
pub use self::readable::ReadableKey;
pub use self::readonly::ReadOnly;
pub use self::writeable::WriteableKey;
pub use self::keyset::... | /// Trait to write values to a key.
pub mod writeable;
pub mod keyset; | random_line_split |
lib.rs | //! # Iron CMS
//! CMS based on Iron Framework for **Rust**.
#[macro_use] extern crate iron;
#[macro_use] extern crate router;
#[macro_use] extern crate maplit;
#[macro_use] extern crate diesel;
extern crate handlebars_iron as hbs;
extern crate handlebars;
extern crate rustc_serialize;
extern crate staticfile;
extern c... | {
// Init router
let mut routes = Router::new();
// Add routes
frontend::add_routes(&mut routes);
admin::add_routes(&mut routes);
// Add static router
let mut mount = Mount::new();
mount
.mount("/", routes)
.mount("/assets/", Static::new(Path::new("static")));
// .... | identifier_body | |
lib.rs | //! # Iron CMS
//! CMS based on Iron Framework for **Rust**.
#[macro_use] extern crate iron;
#[macro_use] extern crate router;
#[macro_use] extern crate maplit;
#[macro_use] extern crate diesel;
extern crate handlebars_iron as hbs;
extern crate handlebars;
extern crate rustc_serialize;
extern crate staticfile;
extern c... | /// // Start applocation and other actions
/// // Iron::new(chain).http("localhost:3000").unwrap();
/// }
/// ```
pub fn routes() -> Mount {
// Init router
let mut routes = Router::new();
// Add routes
frontend::add_routes(&mut routes);
admin::add_routes(&mut routes);
// Add static route... | /// chain.link_after(iron_cms::middleware::template_render(paths));
/// // Add error-404 handler
/// chain.link_after(iron_cms::middleware::Error404); | random_line_split |
lib.rs | //! # Iron CMS
//! CMS based on Iron Framework for **Rust**.
#[macro_use] extern crate iron;
#[macro_use] extern crate router;
#[macro_use] extern crate maplit;
#[macro_use] extern crate diesel;
extern crate handlebars_iron as hbs;
extern crate handlebars;
extern crate rustc_serialize;
extern crate staticfile;
extern c... | () -> Mount {
// Init router
let mut routes = Router::new();
// Add routes
frontend::add_routes(&mut routes);
admin::add_routes(&mut routes);
// Add static router
let mut mount = Mount::new();
mount
.mount("/", routes)
.mount("/assets/", Static::new(Path::new("static")));... | routes | identifier_name |
harfbuzz.rs | get_glyph_infos(buffer, &mut glyph_count);
let glyph_count = glyph_count as int;
assert!(glyph_infos.is_not_null());
let mut pos_count = 0;
let pos_infos = hb_buffer_get_glyph_positions(buffer, &mut pos_count);
let pos_count = pos_count as int;
ass... | (font: &mut Font) -> Shaper {
unsafe {
// Indirection for Rust Issue #6248, dynamic freeze scope artifically extended
let font_ptr = font as *mut Font;
let hb_face: *mut hb_face_t = hb_face_create_for_tables(get_font_table_func,
... | new | identifier_name |
harfbuzz.rs | _get_glyph_infos(buffer, &mut glyph_count);
let glyph_count = glyph_count as int;
assert!(glyph_infos.is_not_null());
let mut pos_count = 0;
let pos_infos = hb_buffer_get_glyph_positions(buffer, &mut pos_count);
let pos_count = pos_count as int;
as... | // processed.
while glyph_span.begin() < glyph_count {
// start by looking at just one glyph.
glyph_span.extend_by(1);
debug!("Processing glyph at idx={}", glyph_span.begin());
let char_byte_start = glyph_data.byte_offset_of_glyph(glyph_span.begin());
... | let mut y_pos = Au(0);
// main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars.
// in cases with complex glyph-character assocations, 2+ glyphs and 1+ chars can be | random_line_split |
harfbuzz.rs | get_glyph_infos(buffer, &mut glyph_count);
let glyph_count = glyph_count as int;
assert!(glyph_infos.is_not_null());
let mut pos_count = 0;
let pos_infos = hb_buffer_get_glyph_positions(buffer, &mut pos_count);
let pos_count = pos_count as int;
ass... | loop {
let range = text.char_range_at(i as uint);
drop(range.ch);
i = range.next as int;
if i >= covered_byte_span.end() { break; }
char_idx = char_idx + CharIndex(1);
glyphs.add_nongl... | {
// collect all glyphs to be assigned to the first character.
let mut datas = vec!();
for glyph_i in glyph_span.each_index() {
let shape = glyph_data.get_entry_for_glyph(glyph_i, &mut y_pos);
datas.push(GlyphData::new(shape.codepo... | conditional_block |
dispatcher.rs | /*
Copyright 2017 Jinjing Wang
This file is part of mtcp.
mtcp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mtcp is distributed in the... | }
}
}
_ => {}
}
}
}
// fn skip_tun_incoming(connection: Connection) -> bool {
// let tun_ip: IpAddr = IpAddr::from_str("10.0.0.1").unwrap();
// let source_ip = connection.source.ip();
// let destination_ip = connection.destination.ip... | {
while let Ok(Some(received)) = tun_in_receiver.recv() {
match parse_packet(&received) {
Some(Packet::UDP(udp)) => {
// debug!("Dispatch UDP: {:#?}", udp.connection);
match udp_sender {
None => {}
Some(ref sender) => {
... | identifier_body |
dispatcher.rs | /*
Copyright 2017 Jinjing Wang
This file is part of mtcp.
mtcp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mtcp is distributed in the... |
(
tun_in_receiver: TunReceiver,
udp_sender: Option<mpsc::Sender<UDP>>,
tcp_sender: Option<mpsc::Sender<TCP>>,
)
{
while let Ok(Some(received)) = tun_in_receiver.recv() {
match parse_packet(&received) {
Some(Packet::UDP(udp)) => {
// debug!("Dispa... | dispatch | identifier_name |
dispatcher.rs | /*
Copyright 2017 Jinjing Wang
This file is part of mtcp.
mtcp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mtcp is distributed in the... | }
}
Some(Packet::TCP(tcp)) => {
// debug!("Dispatch TCP: {:#?}", tcp.connection);
match tcp_sender {
None => {}
Some(ref sender) => {
let _ = sender.send(tcp);
}
... | random_line_split | |
identity.rs | use std::ops::{Mul, MulAssign, Add, AddAssign, Div, DivAssign};
use std::marker::PhantomData;
use std::cmp::{PartialOrd, Ordering};
use std::fmt;
use num::{Num, Zero, One};
use num_complex::Complex;
use approx::ApproxEq;
use general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup,
... |
}
impl<O: Operator> ApproxEq for Id<O> {
type Epsilon = Id<O>;
#[inline]
fn default_epsilon() -> Self::Epsilon {
Id::new()
}
#[inline]
fn default_max_relative() -> Self::Epsilon {
Id::new()
}
#[inline]
fn default_max_ulps() -> u32 {
0
}
#[inline]... | {
Id::new()
} | identifier_body |
identity.rs | use std::ops::{Mul, MulAssign, Add, AddAssign, Div, DivAssign};
use std::marker::PhantomData;
use std::cmp::{PartialOrd, Ordering};
use std::fmt;
use num::{Num, Zero, One};
use num_complex::Complex;
use approx::ApproxEq;
use general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup,
... | (&self, _: &Self, _: Self::Epsilon, _: Self::Epsilon) -> bool {
true
}
#[inline]
fn ulps_eq(&self, _: &Self, _: Self::Epsilon, _: u32) -> bool {
true
}
}
/*
*
* Algebraic structures.
*
*/
impl Mul<Id> for Id {
type Output = Id;
fn mul(self, _: Id) -> Id {
self
... | relative_eq | identifier_name |
identity.rs | use std::ops::{Mul, MulAssign, Add, AddAssign, Div, DivAssign};
use std::marker::PhantomData;
use std::cmp::{PartialOrd, Ordering};
use std::fmt;
use num::{Num, Zero, One};
use num_complex::Complex;
use approx::ApproxEq;
use general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup,
... | // no-op
}
}
impl<O: Operator> AbstractMagma<O> for Id<O> {
#[inline]
fn operate(&self, _: &Self) -> Id<O> {
Id::new()
}
}
impl<O: Operator> Inverse<O> for Id<O> {
#[inline]
fn inverse(&self) -> Self {
Id::new()
}
#[inline]
fn inverse_mut(&mut self) {
... |
impl AddAssign<Id> for Id {
fn add_assign(&mut self, _: Id) { | random_line_split |
125.rs | /// Quickest to just calculate sequences of squares less than the specified
/// limit and determine if they are palindromic.
///
/// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8.
use std::collections::HashSet;
fn is_palindrome(n: u64) -> bool {
let mut nn = n;
if n % 10 == 0 {
... | () {
let mut seen = HashSet::new();
let mut total_sum = 0_u64;
// Compute sequences from the specified start point
'outer: for n in 1..100_000 {
let mut sum = n * n;
for i in (n+1).. {
// sequence must be at least length two
sum += i * i;
if sum >= 1... | main | identifier_name |
125.rs | /// Quickest to just calculate sequences of squares less than the specified
/// limit and determine if they are palindromic.
///
/// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8.
use std::collections::HashSet;
fn is_palindrome(n: u64) -> bool {
let mut nn = n;
if n % 10 == 0 {
... |
}
}
println!("{}", total_sum);
}
| {
total_sum += sum;
seen.insert(sum);
} | conditional_block |
125.rs | /// Quickest to just calculate sequences of squares less than the specified
/// limit and determine if they are palindromic.
///
/// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8.
use std::collections::HashSet;
fn is_palindrome(n: u64) -> bool {
let mut nn = n;
if n % 10 == 0 {
... | let mut seen = HashSet::new();
let mut total_sum = 0_u64;
// Compute sequences from the specified start point
'outer: for n in 1..100_000 {
let mut sum = n * n;
for i in (n+1).. {
// sequence must be at least length two
sum += i * i;
if sum >= 100_00... | // Minor problem with something here
fn main() { | random_line_split |
125.rs | /// Quickest to just calculate sequences of squares less than the specified
/// limit and determine if they are palindromic.
///
/// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8.
use std::collections::HashSet;
fn is_palindrome(n: u64) -> bool |
// Minor problem with something here
fn main() {
let mut seen = HashSet::new();
let mut total_sum = 0_u64;
// Compute sequences from the specified start point
'outer: for n in 1..100_000 {
let mut sum = n * n;
for i in (n+1).. {
// sequence must be at least length two
... | {
let mut nn = n;
if n % 10 == 0 {
false
} else {
let mut r = 0;
while r < nn {
r = 10 * r + nn % 10;
nn /= 10;
}
nn == r || nn == r / 10
}
} | identifier_body |
decoding.rs | use serde::de::DeserializeOwned;
use crate::algorithms::AlgorithmFamily;
use crate::crypto::verify;
use crate::errors::{new_error, ErrorKind, Result};
use crate::header::Header;
#[cfg(feature = "use_pem")]
use crate::pem::decoder::PemEncodedKey;
use crate::serialization::{b64_decode, DecodedJwtPartClaims};
use crate::... | <T> {
/// The decoded JWT header
pub header: Header,
/// The decoded JWT claims
pub claims: T,
}
/// Takes the result of a rsplit and ensure we only get 2 parts
/// Errors if we don't
macro_rules! expect_two {
($iter:expr) => {{
let mut i = $iter;
match (i.next(), i.next(), i.next()... | TokenData | identifier_name |
decoding.rs | use serde::de::DeserializeOwned;
use crate::algorithms::AlgorithmFamily;
use crate::crypto::verify;
use crate::errors::{new_error, ErrorKind, Result};
use crate::header::Header;
#[cfg(feature = "use_pem")]
use crate::pem::decoder::PemEncodedKey;
use crate::serialization::{b64_decode, DecodedJwtPartClaims};
use crate::... | /// let token_message = decode::<Claims>(&token, &DecodingKey::from_secret("secret".as_ref()), &Validation::new(Algorithm::HS256));
/// ```
pub fn decode<T: DeserializeOwned>(
token: &str,
key: &DecodingKey,
validation: &Validation,
) -> Result<TokenData<T>> {
match verify_signature(token, key, validati... | /// let token = "a.jwt.token".to_string();
/// // Claims is a struct that implements Deserialize | random_line_split |
decoding.rs | use serde::de::DeserializeOwned;
use crate::algorithms::AlgorithmFamily;
use crate::crypto::verify;
use crate::errors::{new_error, ErrorKind, Result};
use crate::header::Header;
#[cfg(feature = "use_pem")]
use crate::pem::decoder::PemEncodedKey;
use crate::serialization::{b64_decode, DecodedJwtPartClaims};
use crate::... |
}
/// Verify signature of a JWT, and return header object and raw payload
///
/// If the token or its signature is invalid, it will return an error.
fn verify_signature<'a>(
token: &'a str,
key: &DecodingKey,
validation: &Validation,
) -> Result<(Header, &'a str)> {
if validation.validate_signature &&... | {
match &self.kind {
DecodingKeyKind::SecretOrDer(b) => b,
DecodingKeyKind::RsaModulusExponent { .. } => unreachable!(),
}
} | identifier_body |
trait-with-bounds-default.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> T { self.get_ref().clone() }
}
pub fn main() {
assert_eq!(3.do_get2(), (3, 3));
assert_eq!(Some(~"hi").do_get2(), (~"hi", ~"hi"));
}
| do_get | identifier_name |
trait-with-bounds-default.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl<T: Clone> Getter<T> for Option<T> {
fn do_get(&self) -> T { self.get_ref().clone() }
}
pub fn main() {
assert_eq!(3.do_get2(), (3, 3));
assert_eq!(Some(~"hi").do_get2(), (~"hi", ~"hi"));
}
| { *self } | identifier_body |
trait-with-bounds-default.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
assert_eq!(3.do_get2(), (3, 3));
assert_eq!(Some(~"hi").do_get2(), (~"hi", ~"hi"));
} | }
impl<T: Clone> Getter<T> for Option<T> {
fn do_get(&self) -> T { self.get_ref().clone() }
} | random_line_split |
pass-by-copy.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | use std::gc::{GC, Gc};
fn magic(x: A) { println!("{:?}", x); }
fn magic2(x: Gc<int>) { println!("{:?}", x); }
struct A { a: Gc<int> }
pub fn main() {
let a = A {a: box(GC) 10};
let b = box(GC) 10;
magic(a); magic(A {a: box(GC) 20});
magic2(b); magic2(box(GC) 20);
} | random_line_split | |
pass-by-copy.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 a = A {a: box(GC) 10};
let b = box(GC) 10;
magic(a); magic(A {a: box(GC) 20});
magic2(b); magic2(box(GC) 20);
} | identifier_body | |
pass-by-copy.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 ... | (x: A) { println!("{:?}", x); }
fn magic2(x: Gc<int>) { println!("{:?}", x); }
struct A { a: Gc<int> }
pub fn main() {
let a = A {a: box(GC) 10};
let b = box(GC) 10;
magic(a); magic(A {a: box(GC) 20});
magic2(b); magic2(box(GC) 20);
}
| magic | identifier_name |
lib.rs | extern crate bazel_protos;
extern crate bytes;
extern crate digest;
extern crate hashing;
extern crate protobuf;
extern crate sha2;
use bytes::Bytes;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
pub mod data;
pub mod file;
pub fn owned_string_vec(args: &[&str]) -> Vec<String> {
a... |
pub fn as_bytes(str: &str) -> Bytes {
Bytes::from(str.as_bytes())
}
pub fn make_file(path: &Path, contents: &[u8], mode: u32) {
let mut file = std::fs::File::create(&path).unwrap();
file.write(contents).unwrap();
let mut permissions = std::fs::metadata(path).unwrap().permissions();
permissions.set_mode(mod... | {
Vec::from(str.as_bytes())
} | identifier_body |
lib.rs | extern crate bazel_protos;
extern crate bytes;
extern crate digest;
extern crate hashing;
extern crate protobuf;
extern crate sha2;
use bytes::Bytes;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
pub mod data; | pub fn owned_string_vec(args: &[&str]) -> Vec<String> {
args.into_iter().map(|s| s.to_string()).collect()
}
pub fn as_byte_owned_vec(str: &str) -> Vec<u8> {
Vec::from(str.as_bytes())
}
pub fn as_bytes(str: &str) -> Bytes {
Bytes::from(str.as_bytes())
}
pub fn make_file(path: &Path, contents: &[u8], mode: u32) ... | pub mod file;
| random_line_split |
lib.rs | extern crate bazel_protos;
extern crate bytes;
extern crate digest;
extern crate hashing;
extern crate protobuf;
extern crate sha2;
use bytes::Bytes;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
pub mod data;
pub mod file;
pub fn owned_string_vec(args: &[&str]) -> Vec<String> {
a... | (str: &str) -> Bytes {
Bytes::from(str.as_bytes())
}
pub fn make_file(path: &Path, contents: &[u8], mode: u32) {
let mut file = std::fs::File::create(&path).unwrap();
file.write(contents).unwrap();
let mut permissions = std::fs::metadata(path).unwrap().permissions();
permissions.set_mode(mode);
file.set_pe... | as_bytes | identifier_name |
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs | struct Solution;
impl Solution {
pub fn min_array(numbers: Vec<i32>) -> i32 {
// 使用二分法
let (mut left, mut right) = (0, numbers.len() - 1);
while left < right {
let mid = (left + right) / 2;
// 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。
// 如果 mid ... | fn test_min_array4() {
assert_eq!(Solution::min_array(vec![3, 3, 1, 3]), 1);
}
} | }
#[test] | random_line_split |
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs | struct Solution;
impl Solution {
pub fn min_array(numbers: Vec<i32>) -> i32 {
// 使用二分法
let (mut left, mut right) = (0, numbers.len() - 1);
while left < right {
let mid = (left + right) / 2;
// 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。
// 如果 mid ... | y4() {
assert_eq!(Solution::min_array(vec![3, 3, 1, 3]), 1);
}
}
| 1);
}
#[test]
fn test_min_arra | conditional_block |
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs | struct | ;
impl Solution {
pub fn min_array(numbers: Vec<i32>) -> i32 {
// 使用二分法
let (mut left, mut right) = (0, numbers.len() - 1);
while left < right {
let mid = (left + right) / 2;
// 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。
// 如果 mid 比 left 小,说明最小值在... | Solution | identifier_name |
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs | struct Solution;
impl Solution {
pub fn min_array(numbers: Vec<i32>) -> i32 {
// 使用二分法
let (mut left, mut right) = (0, numbers.len() - 1);
while left < right {
let mid = (left + right) / 2;
// 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。
// 如果 mid ... | 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/. */
use geom::{Point2D, Rect, Size2D};
use std::mem;
use std::string;
use std::rc::Rc;
use std::cell::RefCell;
use ser... | use platform::font_context::FontContextHandle;
use platform::font::{FontHandle, FontTable};
use text::glyph::{GlyphStore, GlyphId};
use text::shaping::ShaperMethods;
use text::{Shaper, TextRun};
use font_template::FontTemplateDescriptor;
use platform::font_template::FontTemplateData;
// FontHandle encapsulates access ... | use sync::Arc;
use servo_util::geometry::Au; | 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/. */
use geom::{Point2D, Rect, Size2D};
use std::mem;
use std::string;
use std::rc::Rc;
use std::cell::RefCell;
use ser... | (advance: Au, ascent: Au, descent: Au) -> RunMetrics {
let bounds = Rect(Point2D(Au(0), -ascent),
Size2D(advance, ascent + descent));
// TODO(Issue #125): support loose and tight bounding boxes; using the
// ascent+descent and advance is sometimes too generous and
... | new | identifier_name |
tests.rs | use std::cmp::Ordering;
use super::print_item::compare_names;
use super::{AllTypes, Buffer};
#[test]
fn test_compare_names() | assert_eq!(compare_names("u32", "u16"), Ordering::Greater);
assert_eq!(compare_names("u8_to_f64", "u16_to_f64"), Ordering::Less);
assert_eq!(compare_names("u32_to_f64", "u16_to_f64"), Ordering::Greater);
assert_eq!(compare_names("u16_to_f64", "u16_to_f64"), Ordering::Equal);
assert_eq!(compare_names... | {
for &(a, b) in &[
("hello", "world"),
("", "world"),
("123", "hello"),
("123", ""),
("123test", "123"),
("hello", ""),
("hello", "hello"),
("hello123", "hello123"),
("hello123", "hello12"),
("hello12", "hello123"),
("hello01ab... | identifier_body |
tests.rs | use std::cmp::Ordering;
use super::print_item::compare_names;
use super::{AllTypes, Buffer};
#[test]
fn test_compare_names() {
for &(a, b) in &[
("hello", "world"),
("", "world"),
("123", "hello"),
("123", ""),
("123test", "123"),
("hello", ""),
("hello", "h... | () {
// Regression test for #82477
let all_types = AllTypes::new();
let mut buffer = Buffer::new();
all_types.print(&mut buffer);
assert_eq!(1, buffer.into_inner().matches("List of all items").count());
}
| test_all_types_prints_header_once | identifier_name |
tests.rs | use std::cmp::Ordering;
use super::print_item::compare_names;
use super::{AllTypes, Buffer};
#[test]
fn test_compare_names() {
for &(a, b) in &[
("hello", "world"),
("", "world"),
("123", "hello"),
("123", ""),
("123test", "123"),
("hello", ""),
("hello", "h... | ("hello01abc", "hello01xyz"),
("hello0abc", "hello0"),
("hello0", "hello0abc"),
("01", "1"),
] {
assert_eq!(compare_names(a, b), a.cmp(b), "{:?} - {:?}", a, b);
}
assert_eq!(compare_names("u8", "u16"), Ordering::Less);
assert_eq!(compare_names("u32", "u16"), Order... | ("hello123", "hello12"),
("hello12", "hello123"), | random_line_split |
rt-set-exit-status.rs | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern... | // 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. | random_line_split | |
rt-set-exit-status.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... | {
error!("whatever");
// 101 is the code the runtime uses on thread panic and the value
// compiletest expects run-fail tests to return.
env::set_exit_status(101);
} | identifier_body | |
rt-set-exit-status.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... | () {
error!("whatever");
// 101 is the code the runtime uses on thread panic and the value
// compiletest expects run-fail tests to return.
env::set_exit_status(101);
}
| main | identifier_name |
main.rs | use std::thread;
fn test1() {
let v = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("Here's a vector: {:?}", v);
});
handle.join().unwrap();
}
use std::sync::mpsc;
fn test2() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("[sen... | () {
println!("main; -enter");
test5();
println!("main; -exit");
}
| main | identifier_name |
main.rs | use std::thread;
fn test1() {
let v = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("Here's a vector: {:?}", v);
});
handle.join().unwrap();
}
use std::sync::mpsc;
fn test2() |
// use std::sync::mpsc;
// use std::thread;
use std::time::Duration;
fn test3() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("sub-thread"),
... | {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("[sender say]> hi");
println!("[sender] before send: {}", val);
tx.send(val).unwrap();
// println!("[sender] before send: {}", val); //value borrowed here after move
});
let received = rx.r... | identifier_body |
main.rs | use std::thread;
fn test1() {
let v = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("Here's a vector: {:?}", v);
});
handle.join().unwrap();
}
use std::sync::mpsc;
fn test2() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("[sen... | thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {}", received);
}
}
use std::sync::{Arc, Mutex};
fn test5() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counte... | for val in vals {
tx.send(val).unwrap(); | random_line_split |
day_6.rs | use std::borrow::Cow;
use std::iter::Peekable;
use std::num::ParseFloatError;
use std::str::Chars;
pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> {
let mut iter = src.chars().peekable();
parse_expression(&mut iter)
}
fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, Parse... | }
ret
}
fn parse_num(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> {
let mut num = String::new();
loop {
match iter.peek().cloned() {
Some('+') | Some('×') | Some('÷') | Some(')') | None => break,
Some('-') if!num.is_empty() => break,
Some('(') ... | ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret / num))
}
_ => break
} | random_line_split |
day_6.rs | use std::borrow::Cow;
use std::iter::Peekable;
use std::num::ParseFloatError;
use std::str::Chars;
pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> {
let mut iter = src.chars().peekable();
parse_expression(&mut iter)
}
fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, Parse... | ter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> {
let mut num = String::new();
loop {
match iter.peek().cloned() {
Some('+') | Some('×') | Some('÷') | Some(')') | None => break,
Some('-') if!num.is_empty() => break,
Some('(') => {
iter.next(... | rse_num(i | identifier_name |
day_6.rs | use std::borrow::Cow;
use std::iter::Peekable;
use std::num::ParseFloatError;
use std::str::Chars;
pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> {
let mut iter = src.chars().peekable();
parse_expression(&mut iter)
}
fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, Parse... |
Some('÷') => {
iter.next();
ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret / num))
}
_ => break
}
}
ret
}
fn parse_num(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> {
let mut num = String::new();
... |
iter.next();
ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret * num))
}, | conditional_block |
day_6.rs | use std::borrow::Cow;
use std::iter::Peekable;
use std::num::ParseFloatError;
use std::str::Chars;
pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> |
fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> {
let mut ret = parse_term(iter.by_ref());
loop {
match iter.peek().cloned() {
Some('+') => {
iter.next();
ret = ret.and_then(|ret| parse_term(iter.by_ref()).map(|num| ret + num)... | {
let mut iter = src.chars().peekable();
parse_expression(&mut iter)
} | identifier_body |
common.rs | //! This module contains various infrastructure that is common across all assembler backends
use proc_macro2::{Span, TokenTree};
use quote::ToTokens;
use quote::quote;
use syn::spanned::Spanned;
use syn::parse;
use syn::Token;
use crate::parse_helpers::{ParseOpt, eat_pseudo_keyword};
use crate::serialize;
/// Enum re... | (value: u16) -> Stmt {
Stmt::Const(u64::from(value), Size::WORD)
}
pub fn u32(value: u32) -> Stmt {
Stmt::Const(u64::from(value), Size::DWORD)
}
pub fn u64(value: u64) -> Stmt {
Stmt::Const(value, Size::QWORD)
}
}
// Makes a None-delimited TokenTree item out of anything t... | u16 | identifier_name |
common.rs | //! This module contains various infrastructure that is common across all assembler backends
use proc_macro2::{Span, TokenTree};
use quote::ToTokens;
use quote::quote;
use syn::spanned::Spanned;
use syn::parse;
use syn::Token;
use crate::parse_helpers::{ParseOpt, eat_pseudo_keyword};
use crate::serialize;
/// Enum re... | }
}
/**
* Jump types
*/
#[derive(Debug, Clone)]
pub struct Jump {
pub kind: JumpKind,
pub offset: Option<syn::Expr>
}
#[derive(Debug, Clone)]
pub enum JumpKind {
// note: these symbol choices try to avoid stuff that is a valid starting symbol for parse_expr
// in order to allow the full range o... | Size::QWORD => "i64",
Size::PWORD => "i80",
Size::OWORD => "i128",
Size::HWORD => "i256"
}, Span::mixed_site()) | random_line_split |
vector.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... | <'a, T: 'a>(&'a [u8], usize, PhantomData<T>);
impl<'a, T: 'a> Vector<'a, T> {
#[inline(always)]
pub fn new(buf: &'a [u8], loc: usize) -> Self {
Vector {
0: buf,
1: loc,
2: PhantomData,
}
}
#[inline(always)]
pub fn len(&self) -> usize {
re... | Vector | identifier_name |
vector.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<'a> Follow<'a> for &'a str {
type Inner = &'a str;
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize;
let slice = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len];
let s = unsafe { from_utf8_unchecked(... | {
let sz = size_of::<T>();
let buf = &buf[loc..loc + sz];
let ptr = buf.as_ptr() as *const T;
unsafe { &*ptr }
} | identifier_body |
vector.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... | use primitives::*;
#[derive(Debug)]
pub struct Vector<'a, T: 'a>(&'a [u8], usize, PhantomData<T>);
impl<'a, T: 'a> Vector<'a, T> {
#[inline(always)]
pub fn new(buf: &'a [u8], loc: usize) -> Self {
Vector {
0: buf,
1: loc,
2: PhantomData,
}
}
#[inlin... |
use endian_scalar::{EndianScalar, read_scalar};
use follow::Follow; | random_line_split |
numbers.rs | //! Functions operating on numbers.
use std::sync::Mutex;
use rand::{StdRng, Rng, SeedableRng};
use lisp::LispObject;
use remacs_sys::{EmacsInt, INTMASK};
use remacs_macros::lisp_fn;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT is a floating point ... | #[lisp_fn]
fn numberp(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_number())
}
/// Return t if OBJECT is a number or a marker (editor pointer).
#[lisp_fn]
fn number_or_marker_p(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_number() || object.is_marker())
}
/// Retu... | fn natnump(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_natnum())
}
/// Return t if OBJECT is a number (floating point or integer). | random_line_split |
numbers.rs | //! Functions operating on numbers.
use std::sync::Mutex;
use rand::{StdRng, Rng, SeedableRng};
use lisp::LispObject;
use remacs_sys::{EmacsInt, INTMASK};
use remacs_macros::lisp_fn;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT is a floating point ... | (object: LispObject) -> LispObject {
LispObject::from_bool(object.is_float())
}
/// Return t if OBJECT is an integer.
#[lisp_fn]
fn integerp(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_integer())
}
/// Return t if OBJECT is an integer or a marker (editor pointer).
#[lisp_fn]
fn integer... | floatp | identifier_name |
numbers.rs | //! Functions operating on numbers.
use std::sync::Mutex;
use rand::{StdRng, Rng, SeedableRng};
use lisp::LispObject;
use remacs_sys::{EmacsInt, INTMASK};
use remacs_macros::lisp_fn;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT is a floating point ... | } else {
LispObject::from_fixnum_truncated(rng.gen())
}
}
| {
let mut rng = RNG.lock().unwrap();
if limit == LispObject::constant_t() {
*rng = StdRng::new().unwrap();
} else if let Some(s) = limit.as_string() {
let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect();
rng.reseed(&values);
}
if let Some(limit) = lim... | identifier_body |
numbers.rs | //! Functions operating on numbers.
use std::sync::Mutex;
use rand::{StdRng, Rng, SeedableRng};
use lisp::LispObject;
use remacs_sys::{EmacsInt, INTMASK};
use remacs_macros::lisp_fn;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT is a floating point ... |
}
| {
LispObject::from_fixnum_truncated(rng.gen())
} | conditional_block |
imp.rs | // Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, ... | "Decoder/Video",
"CDG decoder",
"Guillaume Desmottes <guillaume.desmottes@collabora.com>",
);
let sink_caps = gst::Caps::new_simple("video/x-cdg", &[("parsed", &true)]);
let sink_pad_template = gst::PadTemplate::new(
"sink",
gst::PadDi... | "CDG decoder", | random_line_split |
imp.rs | // Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, ... | (&self, element: &Self::Type) -> bool {
gst_debug!(CAT, obj: element, "flushing, reset CDG interpreter");
let mut cdg_inter = self.cdg_inter.lock().unwrap();
cdg_inter.reset(false);
true
}
}
| flush | identifier_name |
imp.rs | // Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, ... | &[
("format", &gst_video::VideoFormat::Rgba.to_str()),
("width", &(CDG_WIDTH as i32)),
("height", &(CDG_HEIGHT as i32)),
("framerate", &gst::Fraction::new(0, 1)),
],
);
let src_pad_template = gst::PadTemplate::new(
... | {
klass.set_metadata(
"CDG decoder",
"Decoder/Video",
"CDG decoder",
"Guillaume Desmottes <guillaume.desmottes@collabora.com>",
);
let sink_caps = gst::Caps::new_simple("video/x-cdg", &[("parsed", &true)]);
let sink_pad_template = gst::Pad... | identifier_body |
url.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMe... |
}
// https://url.spec.whatwg.org/#dom-url-searchparams
fn SearchParams(&self) -> DomRoot<URLSearchParams> {
self.search_params
.or_init(|| URLSearchParams::new(&self.global(), Some(self)))
}
// https://url.spec.whatwg.org/#dom-url-href
fn Stringifier(&self) -> DOMString {
... | {
search_params.set_list(self.query_pairs());
} | conditional_block |
url.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMe... | Err(error) => {
// Step 2.2.
return Err(Error::Type(format!("could not parse base: {}", error)));
},
}
}
};
// Step 3.
let parsed_url = match ServoUrl::parse_with_base(parsed_base.... | {
match ServoUrl::parse(&base.0) {
Ok(base) => Some(base), | random_line_split |
url.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMe... | (&self, value: USVString) {
UrlHelper::SetHost(&mut self.url.borrow_mut(), value);
}
// https://url.spec.whatwg.org/#dom-url-hostname
fn Hostname(&self) -> USVString {
UrlHelper::Hostname(&self.url.borrow())
}
// https://url.spec.whatwg.org/#dom-url-hostname
fn SetHostname(&sel... | SetHost | identifier_name |
url.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMe... |
pub fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<URL> {
reflect_dom_object(Box::new(URL::new_inherited(url)), global, URLBinding::Wrap)
}
pub fn query_pairs(&self) -> Vec<(String, String)> {
self.url
.borrow()
.as_url()
.query_pairs()
... | {
URL {
reflector_: Reflector::new(),
url: DomRefCell::new(url),
search_params: Default::default(),
}
} | identifier_body |
mod.rs | //! Generators for file formats that can be derived from the intercom
//! libraries.
use std::collections::HashMap;
use intercom::type_system::TypeSystemName;
use intercom::typelib::{Interface, TypeInfo, TypeLib};
/// A common error type for all the generators.
#[derive(Fail, Debug)]
pub enum GeneratorError
{
#[... | pub mod idl; |
pub mod cpp; | random_line_split |
mod.rs | //! Generators for file formats that can be derived from the intercom
//! libraries.
use std::collections::HashMap;
use intercom::type_system::TypeSystemName;
use intercom::typelib::{Interface, TypeInfo, TypeLib};
/// A common error type for all the generators.
#[derive(Fail, Debug)]
pub enum GeneratorError
{
#[... | <'a>
{
pub itfs_by_ref: HashMap<String, &'a Interface>,
pub itfs_by_name: HashMap<String, &'a Interface>,
}
impl<'a> LibraryContext<'a>
{
fn try_from(lib: &'a TypeLib) -> Result<LibraryContext<'a>, GeneratorError>
{
let itfs_by_name: HashMap<String, &Interface> = lib
.types
... | LibraryContext | identifier_name |
floatf.rs | //! formatter for %f %F common-notation floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common};
pub struct Floatf {
as_num: f64,
}
impl Floatf {
pu... | (&self, prim: &FormatPrimitive, field: FormatField) -> String {
primitive_to_str_common(prim, &field)
}
}
| primitive_to_str | identifier_name |
floatf.rs | //! formatter for %f %F common-notation floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common};
pub struct Floatf {
as_num: f64,
}
impl Floatf {
pu... |
}
| {
primitive_to_str_common(prim, &field)
} | identifier_body |
floatf.rs | //! formatter for %f %F common-notation floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common};
pub struct Floatf {
as_num: f64,
}
impl Floatf {
pu... | &str_in[inprefix.offset..],
&analysis,
second_field as usize,
None);
Some(f)
}
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {
... | inprefix,
None,
Some(second_field as usize),
false);
let f = get_primitive_dec(inprefix, | random_line_split |
ihex_writer.rs | //
// Copyright 2016 The c8s Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// All files in the project carrying such notice may not be copied, modified, or
// distributed except according ... |
// Validate the average case yielded the anticipated result.
let ihex_rep = ihex_representation_of_data_ranges(&[range_a, range_b, range_c]);
let expected_ihex_rep = String::new() +
&":0F010000214601360121470136007EFE09D21942\n" +
&":100130003F0156702B5E712B722B732146013421C7\n" +
&":010... | range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21,0x22]);
let mut range_c = DataRange::new(u12![0x200]);
range_c.append(&vec![0x3F]); | random_line_split |
ihex_writer.rs | //
// Copyright 2016 The c8s Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// All files in the project carrying such notice may not be copied, modified, or
// distributed except according ... |
#[test]
#[should_panic]
fn test_ihex_representation_of_data_ranges_panics_when_overlapping() {
// Build an overlapping pair of ranges.
let mut range_a = DataRange::new(u12![0x100]);
range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]);
let mut ra... | {
// Build an uneven set of data ranges.
let mut range_a = DataRange::new(u12![0x100]);
range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19]);
let mut range_b = DataRange::new(u12![0x130]);
range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,... | identifier_body |
ihex_writer.rs | //
// Copyright 2016 The c8s Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// All files in the project carrying such notice may not be copied, modified, or
// distributed except according ... | <'a>(ranges: &'a [DataRange]) -> String {
assert!(data_range::find_overlapping_ranges(ranges).len() == 0);
// All records are collected into a list.
let mut records = Vec::<Record>::new();
for range in ranges.iter() {
// The range will be sub-divded into chunks of up to 16 bytes, so sub-address must be t... | ihex_representation_of_data_ranges | identifier_name |
pmovsxbd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*; | fn pmovsxbd_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 205], OperandSize::Dword)
}
fn pmovsx... | use ::RegScale::*;
| random_line_split |
pmovsxbd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn pmovsxbd_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM1)), operand2: Some(Direc... | () {
run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 246], OperandSize::Qword)
}
fn pmovsxbd_4() {
... | pmovsxbd_3 | identifier_name |
pmovsxbd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn pmovsxbd_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM1)), operand2: Some(Direc... | {
run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Two, 1709813562, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None... | identifier_body | |
13.rs | use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashMap;
fn get_input() -> std::io::Result<String> {
let mut file = File::open("13.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
type Point = (isize, isize);
type Tracks = H... | (input: &str) -> (Tracks, Vec<Cart>) {
input.lines()
.enumerate()
.flat_map(|(j, line)| {
let chars: Vec<char> = line.chars().collect();
chars.iter()
.cloned()
.enumerate()
.filter_map(|(i, c)| {
let (x, y) = (i as isize, j as isize);
let horizonta... | parse | identifier_name |
13.rs | use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashMap;
fn get_input() -> std::io::Result<String> {
let mut file = File::open("13.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
type Point = (isize, isize);
type Tracks = H... | '>' => Some((1, 0)),
'^' => Some((0, -1)),
'v' => Some((0, 1)),
_ => None
};
neighbors
.map(|n| ((x, y), n, cart_direction.map(|d| Cart::new((x, y), d))))
})
.collect::<Vec<_>>()
})
.fold((Tracks::n... | };
let cart_direction = match c {
'<' => Some((-1, 0)), | random_line_split |
lib.rs | Rot180 {Normal, Rotated}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ItemTypesetting(pub DirBehavior, pub Rot180);
impl ItemTypesetting {
fn effective_direction(&self) -> Direction {
match self.1 {
Rot180::Normal => self.0. 0,
Rot180::Rotated => self.0. 0.reverse()
}
}
}
#[derive(Clone, Copy,... | impl Indexed for CoveredGlyph {}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct GSub<'a> {
pub script_list: ScriptList<'a>,
pub feature_list: FeatureList<'a>,
pub lookup_list: LookupList<'a, GSubLookups>
}
impl<'a> GSub<'a> {
fn new(data: &'a[u8]) -> Result<GSub<'a>, CorruptFont<'a>> {
if data.len() < 10 {ret... | veredGlyph;
| identifier_name |
lib.rs | Rot180 {Normal, Rotated}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ItemTypesetting(pub DirBehavior, pub Rot180);
impl ItemTypesetting {
fn effective_direction(&self) -> Direction {
match self.1 {
Rot180::Normal => self.0. 0,
Rot180::Rotated => self.0. 0.reverse()
}
}
}
#[derive(Clone, Copy,... | pub fn features_for(&self, selector: Option<(Tag<Script>, Option<Tag<LangSys>>)>) -> Result<LangSysTable<'a>, CorruptFont<'a>> {
let search = AutoSearch::new(self.num_tables() as usize*6);
if let Some((script, lang_sys_opt)) = selector {
match search.search(0..self.num_tables(), &mut move|&i| Ok(self.tag(Index::... | criptList::new_list(data)}
| identifier_body |
lib.rs | enum Rot180 {Normal, Rotated}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ItemTypesetting(pub DirBehavior, pub Rot180);
impl ItemTypesetting {
fn effective_direction(&self) -> Direction {
match self.1 {
Rot180::Normal => self.0. 0,
Rot180::Rotated => self.0. 0.reverse()
}
}
}
#[derive(Clone, ... | fn new(data: &'a[u8]) -> Result<LookupList<'a, T>, CorruptFont<'a>> {
if data.len() < 2 {return Err(CorruptFont(data, TableTooShort))}
let res = LookupList(data, PhantomData);
if data.len() < res.len() as usize*2+2 {return Err(CorruptFont(data, TableTooShort))}
Ok(res)
}
fn len(&self) -> u16 {read_u16(self.0... | }
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct LookupList<'a, T: LookupContainer<'a>>(&'a[u8], PhantomData<&'static T>);
impl<'a, T: LookupContainer<'a>> LookupList<'a, T> { | random_line_split |
lib.rs | Rot180 {Normal, Rotated}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ItemTypesetting(pub DirBehavior, pub Rot180);
impl ItemTypesetting {
fn effective_direction(&self) -> Direction {
match self.1 {
Rot180::Normal => self.0. 0,
Rot180::Rotated => self.0. 0.reverse()
}
}
}
#[derive(Clone, Copy,... | ),
Err(Ok(i)) => {
let range = &data[i as usize*6..][..6];
if step == 2 {return Ok(None)}
let (first, last, offset) = try!(read_range(range));
Ok(if last >= glyph {
Some(Index::new(glyph-first+offset))
} else {
None
})
},
Err(Err((_, CorruptFont(..)))) => unreachable!()
}
}... | })) | conditional_block |
fmt.rs | #[macro_use] extern crate custom_derive;
#[macro_use] extern crate newtype_derive;
use std::fmt::{self, Binary, Debug, Display, LowerExp, LowerHex, Octal, Pointer,
UpperExp, UpperHex};
macro_rules! impl_fmt {
(impl $tr:ident for $name:ident: $msg:expr) => {
impl $tr for $name {
fn fmt(&sel... | NewtypePointer,
NewtypeUpperExp,
NewtypeUpperHex
)]
struct Wrapper(Dummy);
}
#[test]
fn test_fmt() {
let a = Wrapper(Dummy);
assert_eq!(&*format!("{:b}", a), "binary");
assert_eq!(&*format!("{:?}", a), "debug");
assert_eq!(&*format!("{}", a), "display");
assert_eq!(... | random_line_split | |
fmt.rs | #[macro_use] extern crate custom_derive;
#[macro_use] extern crate newtype_derive;
use std::fmt::{self, Binary, Debug, Display, LowerExp, LowerHex, Octal, Pointer,
UpperExp, UpperHex};
macro_rules! impl_fmt {
(impl $tr:ident for $name:ident: $msg:expr) => {
impl $tr for $name {
fn fmt(&sel... | ;
impl_fmt!(impl Binary for Dummy: "binary");
impl_fmt!(impl Debug for Dummy: "debug");
impl_fmt!(impl Display for Dummy: "display");
impl_fmt!(impl LowerExp for Dummy: "lowerexp");
impl_fmt!(impl LowerHex for Dummy: "lowerhex");
impl_fmt!(impl Octal for Dummy: "octal");
impl_fmt!(impl Pointer for Dummy: "pointer");
i... | Dummy | identifier_name |
sjisprober.rs | use std::ops::Deref;
use std::ops::DerefMut;
use super::enums::MachineState;
use super::mbcharsetprober::MultiByteCharsetProber;
use super::charsetprober::CharsetProber;
use super::enums::ProbingState;
use super::codingstatemachine::CodingStateMachine;
use super::mbcssm::SJIS_SM_MODEL;
use super::chardistribution::SJIS... |
MachineState::ERROR => {
self.base.m_state = ProbingState::NotMe;
break;
}
MachineState::ITS_ME => {
self.base.m_state = ProbingState::FoundIt;
break;
... | {
let char_len = sm.get_current_charlen();
if i == 0 {
self.base.m_last_char[1] = byte_str[0];
self.m_context_analyzer.feed(
&self.base.m_last_char[(2 - char_len) as
... | conditional_block |
sjisprober.rs | use std::ops::Deref;
use std::ops::DerefMut;
use super::enums::MachineState;
use super::mbcharsetprober::MultiByteCharsetProber;
use super::charsetprober::CharsetProber;
use super::enums::ProbingState;
use super::codingstatemachine::CodingStateMachine;
use super::mbcssm::SJIS_SM_MODEL;
use super::chardistribution::SJIS... | }
}
impl<'a> SJISProber<'a> {
pub fn new() -> SJISProber<'a> {
let mut x = SJISProber {
base: MultiByteCharsetProber::new(),
m_context_analyzer: SJISContextAnalysis::new(),
};
x.base.m_coding_sm = Some(CodingStateMachine::new(&SJIS_SM_MODEL));
x.base.m_di... | "Japanese".to_string()
}
fn get_state(&self) -> &ProbingState {
self.base.get_state() | random_line_split |
sjisprober.rs | use std::ops::Deref;
use std::ops::DerefMut;
use super::enums::MachineState;
use super::mbcharsetprober::MultiByteCharsetProber;
use super::charsetprober::CharsetProber;
use super::enums::ProbingState;
use super::codingstatemachine::CodingStateMachine;
use super::mbcssm::SJIS_SM_MODEL;
use super::chardistribution::SJIS... |
}
impl<'a> SJISProber<'a> {
pub fn new() -> SJISProber<'a> {
let mut x = SJISProber {
base: MultiByteCharsetProber::new(),
m_context_analyzer: SJISContextAnalysis::new(),
};
x.base.m_coding_sm = Some(CodingStateMachine::new(&SJIS_SM_MODEL));
x.base.m_distrib... | {
self.base.get_state()
} | identifier_body |
sjisprober.rs | use std::ops::Deref;
use std::ops::DerefMut;
use super::enums::MachineState;
use super::mbcharsetprober::MultiByteCharsetProber;
use super::charsetprober::CharsetProber;
use super::enums::ProbingState;
use super::codingstatemachine::CodingStateMachine;
use super::mbcssm::SJIS_SM_MODEL;
use super::chardistribution::SJIS... | <'a>(&'a mut self) -> &'a mut MultiByteCharsetProber<'x> {
&mut self.base
}
}
impl<'a> CharsetProber for SJISProber<'a> {
fn reset(&mut self) {
self.base.reset();
self.m_context_analyzer.reset();
}
fn feed(&mut self, byte_str: &[u8]) -> &ProbingState {
{
let ... | deref_mut | identifier_name |
lib.rs | //! natural_constants: a collection of constants and helper functions
//!
//! Written by Willi Kappler, Version 0.1 (2017.02.20)
//!
//! Repository: https://github.com/willi-kappler/natural_constants
//!
//! License: MIT
//!
//!
//! # Example:
//!
//! ```
//! extern crate natural_constants; | //!
//! fn main() {
//! let c = speed_of_light_vac;
//! let m0 = 100.0;
//!
//! // Use c in your code:
//! let E = m0 * c * c;
//! }
//! ```
// For clippy
// #![feature(plugin)]
//
// #![plugin(clippy)]
#![allow(non_upper_case_globals)]
#![allow(dead_code)]
pub mod math;
pub mod physics;
pub mod che... | //! use natural_constants::physics::*;
//! | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.