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 |
|---|---|---|---|---|
abstractworkerglobalscope.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::abstractworker::WorkerScriptMsg;
use crate::dom::bindings::conversions::DerivedFrom;
use crate::d... | fn clone(&self) -> Box<dyn ScriptChan + Send> {
Box::new(WorkerThreadWorkerChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
})
}
}
impl ScriptPort for Receiver<DedicatedWorkerScriptMsg> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
let com... | self.sender.send(msg).map_err(|_| ())
}
| random_line_split |
abstractworkerglobalscope.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::abstractworker::WorkerScriptMsg;
use crate::dom::bindings::conversions::DerivedFrom;
use crate::d... | // Once the WorkerGlobalScope's closing flag is set to true,
// the event loop's task queues must discard any further tasks
// that would be added to them
// (tasks already on the queue are unaffected except where otherwise specified).
while!scope.is_closing() {
// Batch all events that are ... | {
let scope = worker_scope.upcast::<WorkerGlobalScope>();
let timer_event_port = worker_scope.timer_event_port();
let devtools_port = match scope.from_devtools_sender() {
Some(_) => Some(scope.from_devtools_receiver()),
None => None,
};
let task_queue = worker_scope.task_queue();
... | identifier_body |
connection.rs | use std::fmt::{self, Display};
use std::str::FromStr;
use unicase::UniCase;
pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader};
const KEEP_ALIVE: UniCase<&'static str> = UniCase("keep-alive");
const CLOSE: UniCase<&'static str> = UniCase("close");
/// Values that can be in the `Connection` header.
... |
fn parse_option(header: Vec<u8>) -> Connection {
let val = vec![header];
let connection: Connection = Header::parse_header(&val[..]).unwrap();
connection
}
#[test]
fn test_parse() {
assert_eq!(Connection::close(),parse_option(b"close".to_vec()));
assert_eq!(Conn... | use header::Header;
use unicase::UniCase; | random_line_split |
connection.rs | use std::fmt::{self, Display};
use std::str::FromStr;
use unicase::UniCase;
pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader};
const KEEP_ALIVE: UniCase<&'static str> = UniCase("keep-alive");
const CLOSE: UniCase<&'static str> = UniCase("close");
/// Values that can be in the `Connection` header.
... | () {
assert_eq!(Connection::close(),parse_option(b"close".to_vec()));
assert_eq!(Connection::keep_alive(),parse_option(b"keep-alive".to_vec()));
assert_eq!(Connection::keep_alive(),parse_option(b"Keep-Alive".to_vec()));
assert_eq!(Connection(vec![ConnectionHeader(UniCase("upgrade".to_own... | test_parse | identifier_name |
connection.rs | use std::fmt::{self, Display};
use std::str::FromStr;
use unicase::UniCase;
pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader};
const KEEP_ALIVE: UniCase<&'static str> = UniCase("keep-alive");
const CLOSE: UniCase<&'static str> = UniCase("close");
/// Values that can be in the `Connection` header.
... |
}
impl Display for ConnectionOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match *self {
KeepAlive => "keep-alive",
Close => "close",
ConnectionHeader(UniCase(ref s)) => s.as_ref()
})
}
}
header! {
#[doc="`Connection` heade... | {
if UniCase(s) == KEEP_ALIVE {
Ok(KeepAlive)
} else if UniCase(s) == CLOSE {
Ok(Close)
} else {
Ok(ConnectionHeader(UniCase(s.to_owned())))
}
} | identifier_body |
tree_layout.rs | use std::fmt::{Debug, Display};
use std::num::Float;
use std::rc::Rc;
use tree::Tree;
use tree::Tree::{Node, Tip};
// Tree layout algorithm based on the following paper:
// "FUNCTIONAL PEARLS - Drawing Trees by Andrew J. Kennedy (1996)"
// (http://research.microsoft.com/en-us/um/people/akenn/fun/DrawingTrees.pdf)
pu... | (es: Vec<Extent>, acc: Extent) -> Vec<f64> {
match es.first() {
Some(e) => {
let x = fit(acc.clone(), e.clone());
let mut r = aux(es.tail().to_vec(), merge_extent(acc.clone(), move_extent(e.clone().to_vec(), x)));
r.insert(0, x);
r
... | aux | identifier_name |
tree_layout.rs | use std::fmt::{Debug, Display};
use std::num::Float;
use std::rc::Rc;
use tree::Tree;
use tree::Tree::{Node, Tip};
// Tree layout algorithm based on the following paper:
// "FUNCTIONAL PEARLS - Drawing Trees by Andrew J. Kennedy (1996)"
// (http://research.microsoft.com/en-us/um/people/akenn/fun/DrawingTrees.pdf)
pu... |
fn fit_list_left(es: Vec<Extent>) -> Vec<f64> {
fn aux(es: Vec<Extent>, acc: Extent) -> Vec<f64> {
match es.first() {
Some(e) => {
let x = fit(acc.clone(), e.clone());
let mut r = aux(es.tail().to_vec(), merge_extent(acc.clone(), move_extent(e.clone().to_vec(), ... | {
fn flip_extent(e: Extent) -> Extent {
e.iter().map(|&x| {
let (p, q) = x;
(-q, -p)
}).collect()
}
fit_list_left(
es.iter().rev().map(|e| flip_extent((*e).clone())).collect()).iter()
.map(|&f| -f).rev().collect()
} | identifier_body |
tree_layout.rs | use std::fmt::{Debug, Display};
use std::num::Float;
use std::rc::Rc;
use tree::Tree;
use tree::Tree::{Node, Tip};
// Tree layout algorithm based on the following paper:
// "FUNCTIONAL PEARLS - Drawing Trees by Andrew J. Kennedy (1996)"
// (http://research.microsoft.com/en-us/um/people/akenn/fun/DrawingTrees.pdf)
pu... | fit_list_right(es.clone()).iter())
.map(|x| mean(*x.0, *x.1)).collect()
}
fn fit_list_right(es: Vec<Extent>) -> Vec<f64> {
fn flip_extent(e: Extent) -> Extent {
e.iter().map(|&x| {
let (p, q) = x;
(-q, -p)
}).collect()
}
fit_list_left(
es.iter... | fn mean(x: f64, y: f64) -> f64 {
(x + y) / 2.0
}
fit_list_left(es.clone()).iter().zip( | random_line_split |
signature.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (&self) -> bool {
H256::from_slice(self.s()) <= "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0".into()
}
/// Check if each component of the signature is in range.
pub fn is_valid(&self) -> bool {
self.v() <= 1 &&
H256::from_slice(self.r()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03... | is_low_s | identifier_name |
signature.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | assert!(verify_address(&keypair.address(), &signature, &message).unwrap());
}
} | random_line_split | |
signature.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
#[cfg(test)]
mod tests {
use std::str::FromStr;
use {Generator, Random, Message};
use super::{sign, verify_public, verify_address, recover, Signature};
#[test]
fn vrs_conversion() {
// given
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret()... | {
let context = &SECP256K1;
let rsig = RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let pubkey = context.recover(&SecpMessage::from_slice(&message[..])?, &rsig)?;
let serialized = pubkey.serialize_vec(context, false);
let mut public = Public::defaul... | identifier_body |
by-value-non-immediate-argument.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (a: (int, uint, f64, f64)) {
zzz(); // #break
}
struct Newtype(f64, f64, int, uint);
fn new_type(a: Newtype) {
zzz(); // #break
}
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken int... | tup | identifier_name |
by-value-non-immediate-argument.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
fn tup(a: (int, uint, f64, f64)) {
zzz(); // #break
}
struct Newtype(f64, f64, int, uint);
fn new_type(a: Newtype) {
zzz(); // #break
}
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be t... | {
zzz(); // #break
} | identifier_body |
by-value-non-immediate-argument.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print s
// lldb-check:[...]$0 = Struct { a: 1, b: 2.5 }
// lldb-command:continue
// lldb-command:print x
// lldb-check:[...]$1 = Struct { a: 3, b: 4.5 }
// lldb-command:print y
/... | random_line_split | |
lib.rs | ', the appropriate prefix and suffix will be
/// added based on the compilation target.
///
/// This function will exit the process with `EXIT_FAILURE` if any stage of
/// compilation or linking fails.
///
/// # Example
/// ```no_run
/// extern crate ispc_compile;
///
/// ispc_compile::compile_library("foo", &["src/foo... | () -> Config {
// Query the ISPC compiler version. This also acts as a check that we can
// find the ISPC compiler when we need it later.
let cmd_output = Command::new("ispc")
.arg("--version")
.output()
.expect("Failed to find ISPC compiler in PATH");
if... | new | identifier_name |
lib.rs | ', the appropriate prefix and suffix will be
/// added based on the compilation target.
///
/// This function will exit the process with `EXIT_FAILURE` if any stage of
/// compilation or linking fails.
///
/// # Example
/// ```no_run
/// extern crate ispc_compile;
///
/// ispc_compile::compile_library("foo", &["src/foo... |
if | {
ispc_args.push(String::from("--instrument"));
} | conditional_block |
lib.rs | pub mod opt;
use std::collections::BTreeSet;
use std::env;
use std::fmt::Display;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
use regex::Regex;
use semver::{BuildMetadata, Prerelease, Version};
pub use opt::{Addressing, Archite... | extern crate gcc;
extern crate libc;
extern crate regex;
extern crate semver;
| random_line_split | |
lib.rs | .arg("--version")
.output()
.expect("Failed to find ISPC compiler in PATH");
if!cmd_output.status.success() {
exit_failure!("Failed to get ISPC version, is it in your PATH?");
}
let ver_string = String::from_utf8_lossy(&cmd_output.stdout);
// The ISPC v... | {
self.debug
.unwrap_or_else(|| env::var("DEBUG").map(|x| x == "true").unwrap())
} | identifier_body | |
str_match.rs | /// Decompose the string pattern
pub fn decompose(rule: &str) -> Vec<String> {
let mut res = vec![String::new()];
let mut escape = false;
for c in rule.chars() {
let l = res.len();
if escape {
res[l - 1].push(c);
escape = false;
} else if c == '\\' {
... | }
res
}
/// Check if a pattern matches a given string
pub fn str_match(rule: &str, other: &str) -> bool {
let mut pos = 0;
for i in decompose(rule) {
match (&other[pos..]).find(&i) {
Some(n) => pos = n,
None => return false,
}
}
true
} | } | random_line_split |
str_match.rs | /// Decompose the string pattern
pub fn decompose(rule: &str) -> Vec<String> |
/// Check if a pattern matches a given string
pub fn str_match(rule: &str, other: &str) -> bool {
let mut pos = 0;
for i in decompose(rule) {
match (&other[pos..]).find(&i) {
Some(n) => pos = n,
None => return false,
}
}
true
}
| {
let mut res = vec![String::new()];
let mut escape = false;
for c in rule.chars() {
let l = res.len();
if escape {
res[l - 1].push(c);
escape = false;
} else if c == '\\' {
escape = true;
} else if c == '*' {
res.push(String::n... | identifier_body |
str_match.rs | /// Decompose the string pattern
pub fn decompose(rule: &str) -> Vec<String> {
let mut res = vec![String::new()];
let mut escape = false;
for c in rule.chars() {
let l = res.len();
if escape {
res[l - 1].push(c);
escape = false;
} else if c == '\\' {
... | (rule: &str, other: &str) -> bool {
let mut pos = 0;
for i in decompose(rule) {
match (&other[pos..]).find(&i) {
Some(n) => pos = n,
None => return false,
}
}
true
}
| str_match | identifier_name |
read.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 ... |
fn next_u64(&mut self) -> u64 {
// see above for explanation.
let mut buf = [0; 8];
fill(&mut self.reader, &mut buf).unwrap();
unsafe { *(buf.as_ptr() as *const u64) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
fill(&mut self.reader... | {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
let mut buf = [0; 4];
fill(&mut self.reader, &mut buf).unwrap();
unsafe { *(buf.as_ptr(... | identifier_body |
read.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 = [1u8, 2, 3, 4, 5, 6, 7, 8];
let mut w = [0u8; 8];
let mut rng = ReadRng::new(&v[..]);
rng.fill_bytes(&mut w);
assert!(v == w);
}
#[test]
#[should_panic]
#[cfg_attr(target_env = "msvc", ignore)]
fn test_reader_rng_insufficient_bytes() {
... | test_reader_rng_fill_bytes | identifier_name |
read.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 ... | Ok(())
}
#[cfg(test)]
mod test {
use super::ReadRng;
use Rng;
#[test]
fn test_reader_rng_u64() {
// transmute from the target to avoid endianness concerns.
let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1,
0 , 0, 0, 0, 0, 0, 0, 2,
0, 0, 0, 0, 0, 0, ... | 0 => return Err(io::Error::new(io::ErrorKind::Other,
"end of file reached")),
n => buf = &mut mem::replace(&mut buf, &mut [])[n..],
}
} | random_line_split |
client.rs | /// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base url for requests via this Client library.
static DEFAULT_BASE_URL: &'static str = "https://api.github.com/";
/// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base upload url for requests via this Client library.
static... | /// `user_agent` represents the value given
/// under the User-Agent key as part of
/// the header of each request.
pub user_agent: String,
/// The base url for non-upload requests.
pub base_url: String,
/// The base url for upload requests.
pub upload_url: String,
}
impl Client {
/... | /// and for th sake of parallel processing, you should try to keep it immutable.
pub struct Client { | random_line_split |
client.rs | /// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base url for requests via this Client library.
static DEFAULT_BASE_URL: &'static str = "https://api.github.com/";
/// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base upload url for requests via this Client library.
static... | (user: &str) -> Client {
Client::custom(user, DEFAULT_BASE_URL, DEFAULT_UPLOAD_BASE_URL)
}
}
| new | identifier_name |
client.rs | /// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base url for requests via this Client library.
static DEFAULT_BASE_URL: &'static str = "https://api.github.com/";
/// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base upload url for requests via this Client library.
static... |
/// Construct a `Client` using the default URLs as defined by GitHub.
pub fn new(user: &str) -> Client {
Client::custom(user, DEFAULT_BASE_URL, DEFAULT_UPLOAD_BASE_URL)
}
}
| {
Client {
user_agent: user.to_string(),
base_url: base_url.to_string(),
upload_url: upload_url.to_string(),
}
} | identifier_body |
snapshot.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::db_vector::PanicDBVector;
use crate::engine::PanicEngine;
use engine_traits::{
IterOptions, Iterable, Iterator, Peekable, ReadOptions, Result, SeekKey, Snapshot,
};
use std::ops::Deref;
#[derive(Clone, Debug)]
pub struct PanicSnapshot;
... |
fn valid(&self) -> Result<bool> {
panic!()
}
}
| {
panic!()
} | identifier_body |
snapshot.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::db_vector::PanicDBVector;
use crate::engine::PanicEngine;
use engine_traits::{
IterOptions, Iterable, Iterator, Peekable, ReadOptions, Result, SeekKey, Snapshot,
};
use std::ops::Deref;
#[derive(Clone, Debug)]
pub struct PanicSnapshot;
... | (&self) -> &[u8] {
panic!()
}
fn value(&self) -> &[u8] {
panic!()
}
fn valid(&self) -> Result<bool> {
panic!()
}
}
| key | identifier_name |
snapshot.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::db_vector::PanicDBVector;
use crate::engine::PanicEngine;
use engine_traits::{
IterOptions, Iterable, Iterator, Peekable, ReadOptions, Result, SeekKey, Snapshot,
};
use std::ops::Deref;
#[derive(Clone, Debug)]
pub struct PanicSnapshot;
... | panic!()
}
} | random_line_split | |
tuples.rs | use AsMutLua;
use AsLua;
use Push;
use PushGuard;
use LuaRead;
macro_rules! tuple_impl {
($ty:ident) => (
impl<LU, $ty> Push<LU> for ($ty,) where LU: AsMutLua, $ty: Push<LU> {
fn push_to_lua(self, lua: LU) -> PushGuard<LU> {
self.0.push_to_lua(lua)
}
}
... | fn lua_read_at_position(mut lua: LU, index: i32) -> Result<($first, $($other),+), LU> {
let mut i = index;
let $first: $first = match LuaRead::lua_read_at_position(&mut lua, i) {
Ok(v) => v,
Err(_) => return Err(lua)
};... | LuaRead<LU> for ($first, $($other),+) where LU: AsLua
{ | random_line_split |
ice-3969.rs | // https://github.com/rust-lang/rust-clippy/issues/3969
// used to crash: error: internal compiler error:
// src/librustc_traits/normalize_erasing_regions.rs:43: could not fully normalize `<i32 as
// std::iter::Iterator>::Item test from rustc./ui/trivial-bounds/trivial-bounds-inconsistent.rs
// Check that tautalogical... | where
str: Sized;
fn unsized_local()
where
for<'a> Dst<dyn A + 'a>: Sized,
{
let x: Dst<dyn A> = *(Box::new(Dst { x: 1 }) as Box<Dst<dyn A>>);
}
fn return_str() -> str
where
str: Sized,
{
*"Sized".to_string().into_boxed_str()
}
fn use_op(s: String) -> String
where
String: ::std::ops::Neg<Outp... | }
struct TwoStrs(str, str) | random_line_split |
ice-3969.rs | // https://github.com/rust-lang/rust-clippy/issues/3969
// used to crash: error: internal compiler error:
// src/librustc_traits/normalize_erasing_regions.rs:43: could not fully normalize `<i32 as
// std::iter::Iterator>::Item test from rustc./ui/trivial-bounds/trivial-bounds-inconsistent.rs
// Check that tautalogical... | () {}
| main | identifier_name |
ice-3969.rs | // https://github.com/rust-lang/rust-clippy/issues/3969
// used to crash: error: internal compiler error:
// src/librustc_traits/normalize_erasing_regions.rs:43: could not fully normalize `<i32 as
// std::iter::Iterator>::Item test from rustc./ui/trivial-bounds/trivial-bounds-inconsistent.rs
// Check that tautalogical... |
fn return_str() -> str
where
str: Sized,
{
*"Sized".to_string().into_boxed_str()
}
fn use_op(s: String) -> String
where
String: ::std::ops::Neg<Output = String>,
{
-s
}
fn use_for()
where
i32: Iterator,
{
for _ in 2i32 {}
}
fn main() {}
| {
let x: Dst<dyn A> = *(Box::new(Dst { x: 1 }) as Box<Dst<dyn A>>);
} | identifier_body |
tok.rs | use std::str::FromStr;
#[derive(Debug)]
pub enum Tok {
Num(i32),
LParen,
RParen,
Minus,
Plus,
Times,
Div,
Comma,
}
// simplest and stupidest possible tokenizer
pub fn tokenize(s: &str) -> Vec<(usize, Tok, usize)> {
let mut tokens = vec![];
let mut chars = s.chars();
let mut... | <C,F>(c0: char, chars: &mut C, f: F) -> (String, Option<char>)
where C: Iterator<Item=char>, F: Fn(char) -> bool
{
let mut buf = String::new();
buf.push(c0);
while let Some(c) = chars.next() {
if!f(c) {
return (buf, Some(c));
}
buf.push(c);
}
return (buf, ... | take_while | identifier_name |
tok.rs | use std::str::FromStr;
#[derive(Debug)]
pub enum Tok {
Num(i32),
LParen,
RParen,
Minus,
Plus,
Times,
Div,
Comma,
}
// simplest and stupidest possible tokenizer
pub fn tokenize(s: &str) -> Vec<(usize, Tok, usize)> {
let mut tokens = vec![];
let mut chars = s.chars();
let mut... |
buf.push(c);
}
return (buf, None);
} | if !f(c) {
return (buf, Some(c));
} | random_line_split |
mpsc_queue.rs | // Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of con... | () {
let q: Queue<Box<_>> = Queue::new();
q.push(box 1);
q.push(box 2);
}
#[test]
fn test() {
let nthreads = 8;
let nmsgs = 1000;
let q = Queue::new();
match q.pop() {
Empty => {}
Inconsistent | Data(..) => panic!(),
}
... | test_full | identifier_name |
mpsc_queue.rs | // Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of con... | Empty,
/// The queue is in an inconsistent state. Popping data should succeed, but
/// some pushers have yet to make enough progress in order allow a pop to
/// succeed. It is recommended that a pop() occur "in the near future" in
/// order to see if the sender has made progress or not
Inconsist... | Data(T),
/// The queue is empty | random_line_split |
mod.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 ... | reason = "module just underwent fairly large reorganization and the dust \
still needs to settle")]
pub use self::c_str::CString;
pub use self::c_str::c_str_to_bytes;
pub use self::c_str::c_str_to_bytes_with_nul;
pub use self::os_str::OsString;
pub use self::os_str::OsStr;
mod c_str... | //! Utilities related to FFI bindings.
#![unstable(feature = "std_misc", | random_line_split |
octree.rs | use shapes::bbox::BBox;
use na::{Vector3};
use sceneobject::SceneObject;
use std::sync::Arc;
use std::fmt;
use ray::Ray;
use intersection::{RawIntersection, Intersection};
use ordered_float::OrderedFloat;
use shapes::geometry::Geometry;
#[derive(Clone)]
pub struct Octree<T: Geometry>{
root: OctreeNode,
items: ... |
fn closest_intersection(&self, r: &Ray, max:f64, min:f64) -> Option<(usize, RawIntersection)> {
return match self.root.naive_intersection(r, max, min) {
Some(opts) => self.items_intersection(r,max, min, opts),
None => None
}
}
// Iterate through potential items. Sh... | {
match self.closest_intersection(r, max, min) {
Some(tupl) => {
return Some((self.items[tupl.0].clone(), tupl.1))
},
None => None
}
} | identifier_body |
octree.rs | use shapes::bbox::BBox;
use na::{Vector3};
use sceneobject::SceneObject;
use std::sync::Arc;
use std::fmt;
use ray::Ray;
use intersection::{RawIntersection, Intersection};
use ordered_float::OrderedFloat;
use shapes::geometry::Geometry;
#[derive(Clone)]
pub struct Octree<T: Geometry>{
root: OctreeNode,
items: ... | if rd0 < 0. {
ro0 = self.bounds.size()[0] - ro0;
rd0 = - rd0;
a |= 4 ; //bitwise OR (latest bits are XYZ)
}
if rd1 < 0. {
ro1 = self.bounds.size()[1] - ro1;
rd1 = - rd1;
a |= 2 ;
}
if rd2 < 0. {
... |
// fixes for rays with negative direction | random_line_split |
octree.rs | use shapes::bbox::BBox;
use na::{Vector3};
use sceneobject::SceneObject;
use std::sync::Arc;
use std::fmt;
use ray::Ray;
use intersection::{RawIntersection, Intersection};
use ordered_float::OrderedFloat;
use shapes::geometry::Geometry;
#[derive(Clone)]
pub struct Octree<T: Geometry>{
root: OctreeNode,
items: ... | (&self, r: &Ray, max:f64, min:f64) -> Option<RawIntersection> {
return match self.closest_intersection(r, max, min) {
Some(tupl) => Some(tupl.1),
None => None
}
}
pub fn intersection(&self, r: &Ray, max:f64, min:f64) -> Option<(Arc<T>, RawIntersection)> {
match ... | raw_intersection | identifier_name |
block-arg.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 ... | ;
assert!(w);
}
| { false } | conditional_block |
block-arg.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 v = ~[-1f, 0f, 1f, 2f, 3f];
// Statement form does not require parentheses:
for v.iter().advance |i| {
info!("%?", *i);
}
// Usable at all:
let mut any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than assignments:
... | main | identifier_name |
block-arg.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 ... | for v.iter().advance |i| {
info!("%?", *i);
}
// Usable at all:
let mut any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than assignments:
any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
//... |
// Statement form does not require parentheses: | random_line_split |
block-arg.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 ... |
// Usable at all:
let mut any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than assignments:
any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than unary operations:
let abs_v = do ... | {
let v = ~[-1f, 0f, 1f, 2f, 3f];
// Statement form does not require parentheses:
for v.iter().advance |i| {
info!("%?", *i);
} | identifier_body |
const-big-enum.rs | // run-pass
enum Foo {
Bar(u32),
Baz,
Quux(u64, u16)
}
static X: Foo = Foo::Baz;
pub fn main() {
match X { | Foo::Bar(s) => assert_eq!(s, 2654435769),
_ => panic!()
}
match Z {
Foo::Quux(d,h) => {
assert_eq!(d, 0x123456789abcdef0);
assert_eq!(h, 0x1234);
}
_ => panic!()
}
}
static Y: Foo = Foo::Bar(2654435769);
static Z: Foo = Foo::Quux(0x123456789ab... | Foo::Baz => {}
_ => panic!()
}
match Y { | random_line_split |
const-big-enum.rs | // run-pass
enum | {
Bar(u32),
Baz,
Quux(u64, u16)
}
static X: Foo = Foo::Baz;
pub fn main() {
match X {
Foo::Baz => {}
_ => panic!()
}
match Y {
Foo::Bar(s) => assert_eq!(s, 2654435769),
_ => panic!()
}
match Z {
Foo::Quux(d,h) => {
assert_eq!(d, 0x12... | Foo | identifier_name |
trait-coercion-generic-bad.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 ... | () {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let s: Box<Trait<isize>> = Box::new(Struct { person: "Fred" });
//~^ ERROR the trait `Trait<isize>` is not implemented for the type `Struct`
s.f(1);
}
| main | identifier_name |
trait-coercion-generic-bad.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 | struct Struct {
person: &'static str
}
trait Trait<T> {
fn f(&self, x: T);
}
impl Trait<&'static str> for Struct {
fn f(&self, x: &'static str) {
println!("Hello, {}!", x);
}
}
fn main() {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let s: Box<Trait<isize>>... | // <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.
| random_line_split |
settings.rs | use crate::render::object::BodyColor;
use std::fs::File;
use std::path::PathBuf;
#[derive(Deserialize)]
pub struct Car {
pub id: String,
pub color: BodyColor,
pub slots: Vec<String>,
pub pos: Option<(i32, i32)>,
}
#[derive(Copy, Clone, Deserialize)]
pub enum View {
Flat,
Perspective,
}
#[der... | File::open(path)
.unwrap_or_else(|e| panic!("Unable to open the settings file: {:?}.\nPlease copy '{}' to '{}' and adjust 'data_path'",
e, TEMPLATE, PATH))
.read_to_string(&mut string)
.unwrap();
let set: Settings = match ron::de::from_str(&string) {
... | use std::io::Read;
const TEMPLATE: &str = "config/settings.template.ron";
const PATH: &str = "config/settings.ron";
let mut string = String::new(); | random_line_split |
settings.rs | use crate::render::object::BodyColor;
use std::fs::File;
use std::path::PathBuf;
#[derive(Deserialize)]
pub struct Car {
pub id: String,
pub color: BodyColor,
pub slots: Vec<String>,
pub pos: Option<(i32, i32)>,
}
#[derive(Copy, Clone, Deserialize)]
pub enum View {
Flat,
Perspective,
}
#[der... | {
pub color: [f32; 4],
pub depth: f32,
}
#[derive(Clone, Deserialize)]
pub struct Render {
pub wgpu_trace_path: String,
pub light: Light,
pub terrain: Terrain,
pub water: Water,
pub fog: Fog,
pub debug: DebugRender,
}
#[derive(Deserialize)]
pub struct Settings {
pub data_path: Pat... | Fog | identifier_name |
cholesky.rs | #[cfg(feature = "serde-serialize")]
use serde::{Deserialize, Serialize};
use num::One;
use simba::scalar::ComplexField;
use crate::allocator::Allocator;
use crate::base::{DefaultAllocator, Matrix, MatrixMN, MatrixN, SquareMatrix, Vector};
use crate::constraint::{SameNumberOfRows, ShapeConstraint};
use crate::dimensio... | /// Returns `None` if the input matrix is not definite-positive. The input matrix is assumed
/// to be symmetric and only the lower-triangular part is read.
pub fn cholesky(self) -> Option<Cholesky<N, D>> {
Cholesky::new(self.into_owned())
}
} | /// | random_line_split |
cholesky.rs | #[cfg(feature = "serde-serialize")]
use serde::{Deserialize, Serialize};
use num::One;
use simba::scalar::ComplexField;
use crate::allocator::Allocator;
use crate::base::{DefaultAllocator, Matrix, MatrixMN, MatrixN, SquareMatrix, Vector};
use crate::constraint::{SameNumberOfRows, ShapeConstraint};
use crate::dimensio... |
// The diagonal element is either zero or its square root could not
// be taken (e.g. for negative real numbers).
return None;
}
Some(Cholesky { chol: matrix })
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition with its strictly
... | {
if let Some(denom) = diag.try_sqrt() {
unsafe {
*matrix.get_unchecked_mut((j, j)) = denom;
}
let mut col = matrix.slice_range_mut(j + 1.., j);
col /= denom;
continue;
... | conditional_block |
cholesky.rs | #[cfg(feature = "serde-serialize")]
use serde::{Deserialize, Serialize};
use num::One;
use simba::scalar::ComplexField;
use crate::allocator::Allocator;
use crate::base::{DefaultAllocator, Matrix, MatrixMN, MatrixN, SquareMatrix, Vector};
use crate::constraint::{SameNumberOfRows, ShapeConstraint};
use crate::dimensio... | (&self) -> &MatrixN<N, D> {
&self.chol
}
/// Solves the system `self * x = b` where `self` is the decomposed matrix and `x` the unknown.
///
/// The result is stored on `b`.
pub fn solve_mut<R2: Dim, C2: Dim, S2>(&self, b: &mut Matrix<N, R2, C2, S2>)
where
S2: StorageMut<N, R2, ... | l_dirty | identifier_name |
cholesky.rs | #[cfg(feature = "serde-serialize")]
use serde::{Deserialize, Serialize};
use num::One;
use simba::scalar::ComplexField;
use crate::allocator::Allocator;
use crate::base::{DefaultAllocator, Matrix, MatrixMN, MatrixN, SquareMatrix, Vector};
use crate::constraint::{SameNumberOfRows, ShapeConstraint};
use crate::dimensio... |
/// Computes the inverse of the decomposed matrix.
pub fn inverse(&self) -> MatrixN<N, D> {
let shape = self.chol.data.shape();
let mut res = MatrixN::identity_generic(shape.0, shape.1);
self.solve_mut(&mut res);
res
}
/// Given the Cholesky decomposition of a matrix ... | {
let mut res = b.clone_owned();
self.solve_mut(&mut res);
res
} | identifier_body |
auracite_web.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate auracite;
extern crate rocket;
use auracite::{web, lodestone};
use auracite::env::load_var;
use rocket::config::Config;
fn main() {
rocket::custom(config(), true)
.mount("/", routes![web::root::web_root, web::assets::static_asset])
.mount(... | () -> Config {
use rocket::config::*;
let env = Environment::active().unwrap();
let mut config = Config::build(env);
config = config.address("0.0.0.0");
let port = load_var("PORT", "8080");
if let Some(port) = port.parse().ok() {
config = config.port(port);
}
config.finalize()... | config | identifier_name |
auracite_web.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate auracite;
extern crate rocket;
use auracite::{web, lodestone};
use auracite::env::load_var;
use rocket::config::Config;
fn main() |
fn config() -> Config {
use rocket::config::*;
let env = Environment::active().unwrap();
let mut config = Config::build(env);
config = config.address("0.0.0.0");
let port = load_var("PORT", "8080");
if let Some(port) = port.parse().ok() {
config = config.port(port);
}
config... | {
rocket::custom(config(), true)
.mount("/", routes![web::root::web_root, web::assets::static_asset])
.mount("/lodestone", routes![lodestone::rss, lodestone::jsonfeed])
.catch(errors![web::core::not_found])
.launch();
} | identifier_body |
auracite_web.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate auracite;
extern crate rocket;
use auracite::{web, lodestone};
use auracite::env::load_var;
use rocket::config::Config;
fn main() {
rocket::custom(config(), true)
.mount("/", routes![web::root::web_root, web::assets::static_asset])
.mount(... |
config.finalize().unwrap()
}
| {
config = config.port(port);
} | conditional_block |
auracite_web.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate auracite;
extern crate rocket; |
fn main() {
rocket::custom(config(), true)
.mount("/", routes![web::root::web_root, web::assets::static_asset])
.mount("/lodestone", routes![lodestone::rss, lodestone::jsonfeed])
.catch(errors![web::core::not_found])
.launch();
}
fn config() -> Config {
use rocket::config::*;
... |
use auracite::{web, lodestone};
use auracite::env::load_var;
use rocket::config::Config; | random_line_split |
react_flight_codegen_test.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<569f1efa26994d3ed3c24325d2914203>>
*/
mod react_flight_codegen; | fn flight_invalid() {
let input = include_str!("react_flight_codegen/fixtures/flight.invalid.graphql");
let expected = include_str!("react_flight_codegen/fixtures/flight.invalid.expected");
test_fixture(transform_fixture, "flight.invalid.graphql", "react_flight_codegen/fixtures/flight.invalid.expected", inp... |
use react_flight_codegen::transform_fixture;
use fixture_tests::test_fixture;
#[test] | random_line_split |
react_flight_codegen_test.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<569f1efa26994d3ed3c24325d2914203>>
*/
mod react_flight_codegen;
use react_flight_codegen::transform_... | () {
let input = include_str!("react_flight_codegen/fixtures/flight-props.graphql");
let expected = include_str!("react_flight_codegen/fixtures/flight-props.expected");
test_fixture(transform_fixture, "flight-props.graphql", "react_flight_codegen/fixtures/flight-props.expected", input, expected);
}
| flight_props | identifier_name |
react_flight_codegen_test.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<569f1efa26994d3ed3c24325d2914203>>
*/
mod react_flight_codegen;
use react_flight_codegen::transform_... |
#[test]
fn flight_props() {
let input = include_str!("react_flight_codegen/fixtures/flight-props.graphql");
let expected = include_str!("react_flight_codegen/fixtures/flight-props.expected");
test_fixture(transform_fixture, "flight-props.graphql", "react_flight_codegen/fixtures/flight-props.expected", inp... | {
let input = include_str!("react_flight_codegen/fixtures/flight.invalid.graphql");
let expected = include_str!("react_flight_codegen/fixtures/flight.invalid.expected");
test_fixture(transform_fixture, "flight.invalid.graphql", "react_flight_codegen/fixtures/flight.invalid.expected", input, expected);
} | identifier_body |
htmloptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::CharacterDataBinding::Chara... | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptionElement {
HTMLOptionElement {
htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,... | new_inherited | identifier_name |
htmloptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::CharacterDataBinding::Chara... |
}
impl HTMLOptionElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptionElement {
HTMLOptionElement {
htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, prefix, document)
}
}
#[allow(unrooted... | {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId))
} | identifier_body |
htmloptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::CharacterDataBinding::Chara... | let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_bool_attribute(&atom!("disabled"), disabled)
}
// http://www.whatwg.org/html/#dom-option-text
fn Text(self) -> DOMString {
let node: JSRef<Node> = NodeCast::from_ref(self);
let mut content = String::new();
... |
// http://www.whatwg.org/html/#dom-option-disabled
fn SetDisabled(self, disabled: bool) { | random_line_split |
decode.rs | extern crate byteorder;
use std::env;
use std::fs::File;
use decode::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian};
use common::Voxel;
static FILE_VER: u8 = 1;
pub fn parse_voxel(file: &mut File) -> Vec<Vec<Voxel>> {
let sig = file.read_uint::<BigEndian>(3).unwrap();
if sig!= 0x525654 {
... | if sig!= 0x565054 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
let frame_count = file.read_u8().unwrap();
let color_count = file.read_u8().unwrap();
let mut frames: Vec<Vec<(u8, u8, u8)>> = Vec::new();
for frame_id in 0..frame_count {
if file.read_u8().... | pub fn parse_pallete(file: &mut File) -> Vec<Vec<(u8, u8, u8)>> {
let sig = file.read_u8().unwrap(); | random_line_split |
decode.rs | extern crate byteorder;
use std::env;
use std::fs::File;
use decode::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian};
use common::Voxel;
static FILE_VER: u8 = 1;
pub fn parse_voxel(file: &mut File) -> Vec<Vec<Voxel>> {
let sig = file.read_uint::<BigEndian>(3).unwrap();
if sig!= 0x525654 {
... |
let voxel_count = file.read_u32::<BigEndian>().unwrap();
let mut frame: Vec<Voxel> = Vec::new();
for voxel_id in 0..voxel_count {
let x = file.read_i8().unwrap();
let y = file.read_i8().unwrap();
let z = file.read_i8().unwrap();
let mut color: (... | {
panic!("ERROR: FILE CORRUPTED: {}", frame_tag);
} | conditional_block |
decode.rs | extern crate byteorder;
use std::env;
use std::fs::File;
use decode::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian};
use common::Voxel;
static FILE_VER: u8 = 1;
pub fn parse_voxel(file: &mut File) -> Vec<Vec<Voxel>> {
let sig = file.read_uint::<BigEndian>(3).unwrap();
if sig!= 0x525654 {
... | (file: &mut File) -> Vec<Vec<(u8, u8, u8)>> {
let sig = file.read_u8().unwrap();
if sig!= 0x565054 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
let frame_count = file.read_u8().unwrap();
let color_count = file.read_u8().unwrap();
let mut frames: Vec<Vec<(u8, u8,... | parse_pallete | identifier_name |
decode.rs | extern crate byteorder;
use std::env;
use std::fs::File;
use decode::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian};
use common::Voxel;
static FILE_VER: u8 = 1;
pub fn parse_voxel(file: &mut File) -> Vec<Vec<Voxel>> | }
let voxel_count = file.read_u32::<BigEndian>().unwrap();
let mut frame: Vec<Voxel> = Vec::new();
for voxel_id in 0..voxel_count {
let x = file.read_i8().unwrap();
let y = file.read_i8().unwrap();
let z = file.read_i8().unwrap();
let mut... | {
let sig = file.read_uint::<BigEndian>(3).unwrap();
if sig != 0x525654 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
if ver > FILE_VER {
panic!("ERROR: FILE VERSION IS GREATER THAN PROGRAM VERSION");
}
let frame_count = file.read_u8().unwrap();
le... | identifier_body |
problem-048.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
#![feature(test)]
extern crate test;
/// Compute n^p mod b
fn modular_pow(n: u64, p: u64, b: u64) -> u64 {
let mut pow = n % b;
for _ in 1..p {
pow = (pow * (n % b)) % b;
}
pow
}
pub fn ... |
}
| {
b.iter(|| solution());
} | identifier_body |
problem-048.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
#![feature(test)]
extern crate test;
/// Compute n^p mod b
fn modular_pow(n: u64, p: u64, b: u64) -> u64 {
let mut pow = n % b;
for _ in 1..p {
pow = (pow * (n % b)) % b;
}
pow
}
pub fn ... | #[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
assert_eq!(9110846700, solution());
}
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
} | random_line_split | |
problem-048.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
#![feature(test)]
extern crate test;
/// Compute n^p mod b
fn modular_pow(n: u64, p: u64, b: u64) -> u64 {
let mut pow = n % b;
for _ in 1..p {
pow = (pow * (n % b)) % b;
}
pow
}
pub fn | () -> u64 {
const BASE: u64 = 10000000000;
let mut sum = 0;
for n in 1..1001 {
sum += modular_pow(n, n, BASE);
}
sum % BASE
}
fn main() {
println!("The sum is {}", solution());
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
a... | solution | identifier_name |
gobject.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013, 2014 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Softw... | unsafe impl wrap::Wrapper for Object {
type Raw = ffi::GObject;
}
pub mod cast {
use grust::object;
pub trait AsObject {
fn as_object(&self) -> &super::Object;
}
impl<T> AsObject for T where T: object::Upcast<super::Object> {
#[inline]
fn as_object(&self) -> &super::Objec... | random_line_split | |
gobject.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013, 2014 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Softw... | (&self) -> &super::Object { self.upcast() }
}
}
unsafe impl object::ObjectType for Object {
fn get_type() -> GType {
unsafe {
GType::from_raw(ffi::g_object_get_type())
}
}
}
| as_object | identifier_name |
gobject.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013, 2014 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Softw... |
}
}
unsafe impl object::ObjectType for Object {
fn get_type() -> GType {
unsafe {
GType::from_raw(ffi::g_object_get_type())
}
}
}
| { self.upcast() } | identifier_body |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
return false;
}
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn | (n: u32) {}
// 8.1
// (http://rustbyexample.com/fn/methods.html)
struct Point {
x: f64,
y: f64,
}
impl Point {
fn origin() -> Point { // static method
Point { x: 0.0, y: 0.0 }
}
fn new(x: f64, y: f64) -> Point { // static method
Point... | void_return2 | identifier_name |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
return false;
}
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn void_return2(n: u32) {}
// 8... | std::mem::drop(movable);
};
consume();
// error: use of moved value: `consume` [E0382]
// consume();
// 8.2.2
// (http://rustbyexample.com/fn/closures/input_parameters.html)
// FnOnce: takes captures by value (T)
fn apply<F>(f: F) where F: FnOnce() {
f()
}
// Fn... | random_line_split | |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 |
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn void_return2(n: u32) {}
// 8.1
// (http://rustbyexample.com/fn/methods.html)
struct Point {
x: f64,
y: f64,
}
impl Point {
fn origin() -> Point { // static method
Point { x: 0.0, y: 0.0 }
... | {
return false;
} | conditional_block |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
return false;
}
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn void_return2(n: u32) {}
// 8... |
let closure1 = |i: i32| -> i32 { i + 1 };
let closure2 = |i| i + 1;
let i = 1;
println!("function: {}", function(i));
println!("closure1: {}", closure1(i));
println!("closure2: {}", closure2(i));
let one = || 1;
println!("closure returning one: {}", one());
// 8.2.1
// (http:/... | { i + 1 } | identifier_body |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue:... | (&self) -> Vec<u8> {
match *self {
ValueString::Data(ref data) => data.clone(),
ValueString::Integer(ref int) => format!("{}", int).into_bytes(),
}
}
pub fn strlen(&self) -> usize {
match *self {
ValueString::Data(ref data) => data.len(),
... | to_vec | identifier_name |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue:... |
}
}
return None;
}
fn to_f64(newvalue: &Vec<u8>) -> Option<f64> {
if newvalue.len() > 0 && newvalue.len() < 32 { // ought to be enough!
if newvalue[0] as char!= '0' && newvalue[0] as char!='' {
if let Ok(utf8) = from_utf8(&*newvalue) {
if let Ok(f) = utf8.parse:... | {
if let Ok(i) = utf8.parse::<i64>() {
return Some(i);
}
} | conditional_block |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue:... |
pub fn to_vec(&self) -> Vec<u8> {
match *self {
ValueString::Data(ref data) => data.clone(),
ValueString::Integer(ref int) => format!("{}", int).into_bytes(),
}
}
pub fn strlen(&self) -> usize {
match *self {
ValueString::Data(ref data) => data.... | {
match to_i64(&newvalue) {
Some(i) => ValueString::Integer(i),
None => ValueString::Data(newvalue),
}
} | identifier_body |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue:... | #[test]
fn dump_string() {
let mut v = vec![];
ValueString::Data(b"hello world".to_vec()).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\x0bhello world\x07\x00");
}
} | }
| random_line_split |
local_data_priv.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 ... |
&LocalStorage(ref mut map_ptr, ref mut at_exit) => {
assert!((*map_ptr).is_null());
let map: TaskLocalMap = @mut ~[];
*map_ptr = cast::transmute(map);
let at_exit_fn: ~fn(*libc::c_void) = |p|cleanup_task_local_map(p);
*at_exit = Some(at_exit_fn);
... | {
assert!(map_ptr.is_not_null());
let map = cast::transmute(map_ptr);
let nonmut = cast::transmute::<TaskLocalMap,
@~[Option<TaskLocalElement>]>(map);
cast::bump_box_refcount(nonmut);
return map;
} | conditional_block |
local_data_priv.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T:'static>(key: LocalDataKey<T>) -> *libc::c_void {
// Keys are closures, which are (fnptr,envptr) pairs. Use fnptr.
// Use reinterpret_cast -- transmute would leak (forget) the closure.
let pair: (*libc::c_void, *libc::c_void) = cast::transmute_copy(&key);
pair.first()
}
// If returning Some(..), ret... | key_to_key_value | identifier_name |
local_data_priv.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 ... | assert!(!map_ptr.is_null());
// Get and keep the single reference that was created at the
// beginning.
let _map: TaskLocalMap = cast::transmute(map_ptr);
// All local_data will be destroyed along with the map.
}
}
// Gets the map from the runtime. Lazily initialises if not ... | unsafe { | random_line_split |
local_data_priv.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 unsafe fn local_set<T:'static>(
handle: Handle, key: LocalDataKey<T>, data: @T) {
let map = get_local_map(handle);
// Store key+data as *voids. Data is invisibly referenced once; key isn't.
let keyval = key_to_key_value(key);
// We keep the data in two forms: one as an unsafe pointer, so we c... | {
local_get_helper(handle, key, false)
} | identifier_body |
type-infer-generalize-ty-var.rs | // Copyright 2016 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) -> &(MyShow +'static) {
static x: usize = 42;
&x
}
}
impl Get<usize> for Wrap<U> {
fn get(&self) -> &usize {
static x: usize = 55;
&x
}
}
trait MyShow { fn dummy(&self) { } }
impl<'a> MyShow for &'a (MyShow + 'a) { }
impl MyShow for usize { }
fn constrain<'a>(rc: Re... | get | identifier_name |
type-infer-generalize-ty-var.rs | // Copyright 2016 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 ... | static x: usize = 42;
&x
}
}
impl Get<usize> for Wrap<U> {
fn get(&self) -> &usize {
static x: usize = 55;
&x
}
}
trait MyShow { fn dummy(&self) { } }
impl<'a> MyShow for &'a (MyShow + 'a) { }
impl MyShow for usize { }
fn constrain<'a>(rc: RefCell<&'a (MyShow + 'a)>) { }
f... | fn get(&self) -> &(MyShow + 'static) { | random_line_split |
primitives_scale.rs | extern crate rand;
extern crate kiss3d;
extern crate nalgebra as na;
use rand::random;
use na::{Vec3, Translation, RotationWithTranslation};
use kiss3d::window::Window;
use kiss3d::light::Light;
fn main() {
let mut window = Window::new("Kiss3d: primitives_scale");
// NOTE: scaling is not possible.
for i ... | sp.set_color(random(), random(), random());
co.set_color(random(), random(), random());
cy.set_color(random(), random(), random());
ca.set_color(random(), random(), random());
}
window.set_light(Light::StickToCamera);
while window.render() {
// XXX: applying this to... | ca.append_translation(&Vec3::new(offset, 0.0, 0.0));
cu.set_color(random(), random(), random()); | random_line_split |
primitives_scale.rs | extern crate rand;
extern crate kiss3d;
extern crate nalgebra as na;
use rand::random;
use na::{Vec3, Translation, RotationWithTranslation};
use kiss3d::window::Window;
use kiss3d::light::Light;
fn main() | ca.append_translation(&Vec3::new(offset, 0.0, 0.0));
cu.set_color(random(), random(), random());
sp.set_color(random(), random(), random());
co.set_color(random(), random(), random());
cy.set_color(random(), random(), random());
ca.set_color(random(), random(), random())... | {
let mut window = Window::new("Kiss3d: primitives_scale");
// NOTE: scaling is not possible.
for i in 0usize .. 11 {
let dim: f32 = random::<f32>() / 2.0;
let dim2 = dim / 2.0;
let offset = i as f32 * 1.0 - 5.0;
let mut cu = window.add_cube(dim2, dim2, dim2);
let ... | identifier_body |
primitives_scale.rs | extern crate rand;
extern crate kiss3d;
extern crate nalgebra as na;
use rand::random;
use na::{Vec3, Translation, RotationWithTranslation};
use kiss3d::window::Window;
use kiss3d::light::Light;
fn | () {
let mut window = Window::new("Kiss3d: primitives_scale");
// NOTE: scaling is not possible.
for i in 0usize.. 11 {
let dim: f32 = random::<f32>() / 2.0;
let dim2 = dim / 2.0;
let offset = i as f32 * 1.0 - 5.0;
let mut cu = window.add_cube(dim2, dim2, dim2);
le... | main | identifier_name |
context.rs | //! Manage OpenGL context and window.
use std::string::ToString;
use std::rc::Rc;
use std::ops::Deref;
use std::cell::{UnsafeCell, RefCell, RefMut, Ref};
use glium::{Display, DisplayBuild};
use glium::glutin::WindowBuilder;
pub use glium::{Frame, Surface, SwapBuffersError, DrawError};
/// Just a reference of `Contex... | }
} | random_line_split | |
context.rs | //! Manage OpenGL context and window.
use std::string::ToString;
use std::rc::Rc;
use std::ops::Deref;
use std::cell::{UnsafeCell, RefCell, RefMut, Ref};
use glium::{Display, DisplayBuild};
use glium::glutin::WindowBuilder;
pub use glium::{Frame, Surface, SwapBuffersError, DrawError};
/// Just a reference of `Contex... | (&self) -> Ref<Frame> {
unsafe {
let cell = self.get_cell();
if cell.is_none() {
panic!("Frame not exist.")
}
cell.as_ref().unwrap().borrow()
}
}
/// Get frame mutable reference.
/// # Panics
/// Panic if something is borro... | get_frame | identifier_name |
context.rs | //! Manage OpenGL context and window.
use std::string::ToString;
use std::rc::Rc;
use std::ops::Deref;
use std::cell::{UnsafeCell, RefCell, RefMut, Ref};
use glium::{Display, DisplayBuild};
use glium::glutin::WindowBuilder;
pub use glium::{Frame, Surface, SwapBuffersError, DrawError};
/// Just a reference of `Contex... |
}
}
/// Get frame immutable reference.
/// # Panics
/// Panic if frame not created or something is mutable borrowing the frame.
pub fn get_frame(&self) -> Ref<Frame> {
unsafe {
let cell = self.get_cell();
if cell.is_none() {
panic!("Frame no... | {
let mut frame = self.display.draw();
frame.clear_color_and_depth(self.clear_color, 1.0);
*cell = Some(RefCell::new(frame));
} | conditional_block |
context.rs | //! Manage OpenGL context and window.
use std::string::ToString;
use std::rc::Rc;
use std::ops::Deref;
use std::cell::{UnsafeCell, RefCell, RefMut, Ref};
use glium::{Display, DisplayBuild};
use glium::glutin::WindowBuilder;
pub use glium::{Frame, Surface, SwapBuffersError, DrawError};
/// Just a reference of `Contex... |
}
impl Deref for Gfx {
type Target = Context;
fn deref(&self) -> &Context {
&*self.0
}
}
/// Context handle object.
///
/// Manage `glium::Display` context and current frame.
pub struct Context {
pub display: Display,
frame: UnsafeCell<Option<RefCell<Frame>>>,
clear_color: (f32, f3... | {
Gfx(Rc::new(ctx))
} | identifier_body |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use crate::dom::bindings:... | LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
if let Some((js_backtrace, rust_backtrace)) = backtrace.borrow_mut().take() {
if let Some(stack) = js_backtrace {
eprintln!("JS backtrace:\n{}", stack);
}
eprintln!("Rust backtrace:\n{}", ... | );
#[cfg(feature = "js_backtrace")]
{ | random_line_split |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use crate::dom::bindings:... | {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo> {... | ErrorInfo | identifier_name |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use crate::dom::bindings:... |
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| ErrorInfo {
... | {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.