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 |
|---|---|---|---|---|
issue-22560.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 ... | { } | identifier_body | |
word_index.rs | #![stable]
//! This module is used to index words and does the heavy lifting of our program.
/// A counted word.
///
/// This struct contains members for storing a word and the number of times it appeared. This
/// struct is intended for use with [`add_word`](fn.add_word.html).
///
/// # Examples
///
/// ```
/// use l... | {
for indexed_word in index.iter_mut() {
if word.to_lowercase() == indexed_word.word {
indexed_word.appeared += 1;
return;
}
}
let new_word = IndexedWord{
word: word.to_lowercase(),
appeared: 1
};
index.push(new_word);
} | identifier_body | |
word_index.rs | #![stable]
//! This module is used to index words and does the heavy lifting of our program.
/// A counted word.
///
/// This struct contains members for storing a word and the number of times it appeared. This
/// struct is intended for use with [`add_word`](fn.add_word.html).
///
/// # Examples
///
/// ```
/// use l... |
}
let new_word = IndexedWord{
word: word.to_lowercase(),
appeared: 1
};
index.push(new_word);
}
| {
indexed_word.appeared += 1;
return;
} | conditional_block |
word_index.rs | #![stable]
//! This module is used to index words and does the heavy lifting of our program.
/// A counted word.
///
/// This struct contains members for storing a word and the number of times it appeared. This
/// struct is intended for use with [`add_word`](fn.add_word.html).
///
/// # Examples
///
/// ```
/// use l... | /// assert_eq!(index[2], word_index::IndexedWord{
/// word: "pfudor".to_string(),
/// appeared: 1
/// });
/// ```
#[stable]
pub fn add_word(word: String, index: &mut Vec<IndexedWord>) {
for indexed_word in index.iter_mut() {
if word.to_lowercase() == indexed_word.word {
indexed_word.app... | /// appeared: 1
/// }); | random_line_split |
word_index.rs | #![stable]
//! This module is used to index words and does the heavy lifting of our program.
/// A counted word.
///
/// This struct contains members for storing a word and the number of times it appeared. This
/// struct is intended for use with [`add_word`](fn.add_word.html).
///
/// # Examples
///
/// ```
/// use l... | {
/// The word that's indexed.
pub word: String,
/// The amount of times this word appeared.
pub appeared: i64
}
/// Add a word to a given index.
///
/// This function prevents duplicates and increments the count of the word appearances
/// automatically. The vector will be modified accordingly.
///
/... | IndexedWord | identifier_name |
constants.rs | use malachite_base::num::basic::traits::{NegativeOne, One, Two, Zero};
use malachite_nz::integer::Integer;
#[test]
fn test_zero() {
let zero = Integer::ZERO;
assert!(zero.is_valid());
assert_eq!(zero, 0);
assert_eq!(zero.to_string(), "0");
}
#[test]
fn test_one() { |
#[test]
fn test_two() {
let two = Integer::TWO;
assert!(two.is_valid());
assert_eq!(two, 2);
assert_eq!(two.to_string(), "2");
}
#[test]
fn test_negative_one() {
let negative_one = Integer::NEGATIVE_ONE;
assert!(negative_one.is_valid());
assert_eq!(negative_one, -1);
assert_eq!(negativ... | let one = Integer::ONE;
assert!(one.is_valid());
assert_eq!(one, 1);
assert_eq!(one.to_string(), "1");
} | random_line_split |
constants.rs | use malachite_base::num::basic::traits::{NegativeOne, One, Two, Zero};
use malachite_nz::integer::Integer;
#[test]
fn test_zero() {
let zero = Integer::ZERO;
assert!(zero.is_valid());
assert_eq!(zero, 0);
assert_eq!(zero.to_string(), "0");
}
#[test]
fn test_one() {
let one = Integer::ONE;
asse... | {
let negative_one = Integer::NEGATIVE_ONE;
assert!(negative_one.is_valid());
assert_eq!(negative_one, -1);
assert_eq!(negative_one.to_string(), "-1");
} | identifier_body | |
constants.rs | use malachite_base::num::basic::traits::{NegativeOne, One, Two, Zero};
use malachite_nz::integer::Integer;
#[test]
fn | () {
let zero = Integer::ZERO;
assert!(zero.is_valid());
assert_eq!(zero, 0);
assert_eq!(zero.to_string(), "0");
}
#[test]
fn test_one() {
let one = Integer::ONE;
assert!(one.is_valid());
assert_eq!(one, 1);
assert_eq!(one.to_string(), "1");
}
#[test]
fn test_two() {
let two = Inte... | test_zero | identifier_name |
level.rs | use super::dump::dump_tree;
use super::node::read_unchecked;
use super::node::write_node;
use super::node::NodeWriteGuard;
use super::prune::*;
use super::search::MutSearchResult;
use super::LevelTree;
use super::NodeCellRef;
use super::*;
use super::{external, BPlusTree};
use itertools::Itertools;
use std::fmt::Debug;... | <KS, PS>(
mut left_most_leaf_guards: Vec<NodeWriteGuard<KS, PS>>,
src_tree: &BPlusTree<KS, PS>,
dest_tree: &dyn LevelTree,
) -> (AlteredNodes, usize)
where
KS: Slice<EntryKey> + Debug +'static,
PS: Slice<NodeCellRef> +'static,
{
let num_keys_moved;
let left_most_id = left_most_leaf_guards.fi... | merge_remove_empty_ext_nodes | identifier_name |
level.rs | use super::dump::dump_tree;
use super::node::read_unchecked;
use super::node::write_node;
use super::node::NodeWriteGuard;
use super::prune::*;
use super::search::MutSearchResult;
use super::LevelTree;
use super::NodeCellRef;
use super::*;
use super::{external, BPlusTree};
use itertools::Itertools;
use std::fmt::Debug;... |
num += 1;
}
(num, non_empty)
}
pub async fn level_merge<KS, PS>(
level: usize,
src_tree: &BPlusTree<KS, PS>,
dest_tree: &dyn LevelTree,
) -> usize
where
KS: Slice<EntryKey> + Debug +'static,
PS: Slice<NodeCellRef> +'static,
{
debug!("Merging LSM tree level {}", level);
let ... | {
break;
} | conditional_block |
level.rs | use super::dump::dump_tree;
use super::node::read_unchecked;
use super::node::write_node;
use super::node::NodeWriteGuard;
use super::prune::*;
use super::search::MutSearchResult;
use super::LevelTree;
use super::NodeCellRef;
use super::*;
use super::{external, BPlusTree};
use itertools::Itertools;
use std::fmt::Debug;... | }
fn merge_remove_empty_ext_nodes<KS, PS>(
mut left_most_leaf_guards: Vec<NodeWriteGuard<KS, PS>>,
src_tree: &BPlusTree<KS, PS>,
dest_tree: &dyn LevelTree,
) -> (AlteredNodes, usize)
where
KS: Slice<EntryKey> + Debug +'static,
PS: Slice<NodeCellRef> +'static,
{
let num_keys_moved;
let left... | {
let search = mut_first::<KS, PS>(node);
match search {
MutSearchResult::External => {
debug!("Processing external level {}", level);
let left_most_leaf_guards = select_ext_nodes(node);
let num_guards = left_most_leaf_guards.len();
let (altered, num_keys)... | identifier_body |
level.rs | use super::dump::dump_tree;
use super::node::read_unchecked;
use super::node::write_node;
use super::node::NodeWriteGuard;
use super::prune::*;
use super::search::MutSearchResult;
use super::LevelTree;
use super::NodeCellRef;
use super::*;
use super::{external, BPlusTree};
use itertools::Itertools;
use std::fmt::Debug;... |
pub const LEVEL_M: usize = 32; // Smaller can be faster but more fragmented
pub const LEVEL_1: usize = LEVEL_M * LEVEL_PAGE_DIFF_MULTIPLIER;
pub const LEVEL_2: usize = LEVEL_1 * LEVEL_PAGE_DIFF_MULTIPLIER;
pub const NUM_LEVELS: usize = 3;
// Select left most leaf nodes and acquire their write guard
fn merge_prune<KS... | random_line_split | |
main.rs | //
// test ownership
fn test0() {
let a1 = ["s1", "s2"];
let a2 = a1; //why move didn't happen here?
println!("iterate a1");
for i in a1.iter() {
println!("{}", i);
}
// let str1 = String::from("hello");
// let str2 = str1; //str1 stored on heap, so move happened here but not copy,... |
fn test4() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
let c1 = Circle { r: 2.0 };
println!(
"the radius of c1={}, the area of c1={}, length of c1={}",
c1.r,
... | }
} | random_line_split |
main.rs | //
// test ownership
fn test0() {
let a1 = ["s1", "s2"];
let a2 = a1; //why move didn't happen here?
println!("iterate a1");
for i in a1.iter() {
println!("{}", i);
}
// let str1 = String::from("hello");
// let str2 = str1; //str1 stored on heap, so move happened here but not copy,... | (&self) {
println!("print self; width={}, height={}", self.width, self.height);
}
}
fn test4() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
let c1 = Circle { r: 2.0 };
... | print | identifier_name |
per_sequence_gc_content.rs | use crate::trust_seq::gc_model::GCModel;
use crate::trust_seq::qc::{QCModule, QCReport, QCResult};
use crate::trust_seq::trust_seq::{TrustSeqConfig, TrustSeqErr};
use crate::trust_seq::utils::Sequence;
use serde_json::map::Map;
use serde_json::value;
use serde_json::value::Value;
use std::collections::hash_map::HashMap... | (sequence: &[u8]) -> &[u8] {
if sequence.len() > 1000 {
let length = (sequence.len() / 1000) * 1000;
return &sequence[..length];
} else if sequence.len() > 100 {
let length = (sequence.len() / 100) * 100;
return &sequence[..length];
} else {
return sequence;
}
}
f... | truncate_sequence | identifier_name |
per_sequence_gc_content.rs | use crate::trust_seq::gc_model::GCModel;
use crate::trust_seq::qc::{QCModule, QCReport, QCResult};
use crate::trust_seq::trust_seq::{TrustSeqConfig, TrustSeqErr};
use crate::trust_seq::utils::Sequence;
use serde_json::map::Map;
use serde_json::value;
use serde_json::value::Value;
use std::collections::hash_map::HashMap... | reports.push(Box::new(PerSequenceGCReport {
status: status,
gc_distribution: self.gc_distribution.to_vec(),
theoretical_distribution: theoretical_distribution.to_vec(),
}));
return Ok(());
}
fn process_sequence(&mut self, seq: &Sequence) -> () {
... | QCResult::Warn
} else {
QCResult::Pass
}; | random_line_split |
per_sequence_gc_content.rs | use crate::trust_seq::gc_model::GCModel;
use crate::trust_seq::qc::{QCModule, QCReport, QCResult};
use crate::trust_seq::trust_seq::{TrustSeqConfig, TrustSeqErr};
use crate::trust_seq::utils::Sequence;
use serde_json::map::Map;
use serde_json::value;
use serde_json::value::Value;
use std::collections::hash_map::HashMap... | ;
reports.push(Box::new(PerSequenceGCReport {
status: status,
gc_distribution: self.gc_distribution.to_vec(),
theoretical_distribution: theoretical_distribution.to_vec(),
}));
return Ok(());
}
fn process_sequence(&mut self, seq: &Sequence) -> () {
... | {
QCResult::Pass
} | conditional_block |
geometry.rs | use std::fmt;
/// This is what the layout engine produces when it's finished.
#[derive(Default, Clone)]
pub struct Geometry {
// Content Box
pub position: Xyz,
pub dimensions: Xyz,
pub border: Spacing,
pub margin: Spacing,
pub padding: Spacing,
}
impl Geometry {
pub fn within_border_box(&... | }
pub fn set_bounding_position_y(&mut self, bounding_pos_y: f64) -> bool {
let content_position_y = bounding_pos_y + self.margin.top + self.border.top + self.padding.top;
let changed = self.position.y!= content_position_y;
self.position.y = content_position_y;
changed
}
}
im... | random_line_split | |
geometry.rs | use std::fmt;
/// This is what the layout engine produces when it's finished.
#[derive(Default, Clone)]
pub struct Geometry {
// Content Box
pub position: Xyz,
pub dimensions: Xyz,
pub border: Spacing,
pub margin: Spacing,
pub padding: Spacing,
}
impl Geometry {
pub fn | (&self, point: &Xy) -> bool {
self.position.x - self.border.left - self.padding.left < point.x &&
self.position.x + self.border.right + self.padding.right + self.dimensions.x > point.x &&
self.position.y - self.border.top - self.padding.top < point.y &&
self.position.y + self.border.bott... | within_border_box | identifier_name |
geometry.rs | use std::fmt;
/// This is what the layout engine produces when it's finished.
#[derive(Default, Clone)]
pub struct Geometry {
// Content Box
pub position: Xyz,
pub dimensions: Xyz,
pub border: Spacing,
pub margin: Spacing,
pub padding: Spacing,
}
impl Geometry {
pub fn within_border_box(&... |
/// [x, y, w, h]
pub fn padding_box(&self) -> [f64;4] {
[
self.position.x - self.padding.left,
self.position.y - self.padding.top,
self.padding.left + self.dimensions.x + self.padding.right,
self.padding.top + self.dimensions.y + self.padding.bottom,
... | {
let padding_box = self.padding_box();
[
padding_box[0] - self.border.left,
padding_box[1] - self.border.top,
padding_box[2] + self.border.left + self.border.right,
padding_box[3] + self.border.top + self.border.bottom,
]
} | identifier_body |
lib.rs | //! This crates defines the type inference engine. | //! this code handles low-level equality and subtyping operations. The
//! type check pass in the compiler is found in the `rustc_typeck` crate.
//!
//! For more information about how rustc works, see the [rustc dev guide].
//!
//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/
//!
//! # Note
//!
//! Thi... | //!
//! - **Type inference.** The type inference code can be found in the `infer` module; | random_line_split |
read_texts.rs | extern crate quick_xml;
fn | () {
use quick_xml::events::Event;
use quick_xml::Reader;
let xml = "<tag1>text1</tag1><tag1>text2</tag1>\
<tag1>text3</tag1><tag1><tag2>text4</tag2></tag1>";
let mut reader = Reader::from_str(xml);
reader.trim_text(true);
let mut txt = Vec::new();
let mut buf = Vec::new();... | main | identifier_name |
read_texts.rs | extern crate quick_xml;
fn main() | );
println!("{:?}", txt);
}
Ok(Event::Eof) => break, // exits the loop when reaching end of file
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (), // There are several other `Event`s we do not consider he... | {
use quick_xml::events::Event;
use quick_xml::Reader;
let xml = "<tag1>text1</tag1><tag1>text2</tag1>\
<tag1>text3</tag1><tag1><tag2>text4</tag2></tag1>";
let mut reader = Reader::from_str(xml);
reader.trim_text(true);
let mut txt = Vec::new();
let mut buf = Vec::new();
... | identifier_body |
read_texts.rs | extern crate quick_xml;
fn main() {
use quick_xml::events::Event;
use quick_xml::Reader;
let xml = "<tag1>text1</tag1><tag1>text2</tag1>\
<tag1>text3</tag1><tag1><tag2>text4</tag2></tag1>";
let mut reader = Reader::from_str(xml);
reader.trim_text(true);
let mut txt = Vec::new(... |
Ok(Event::Eof) => break, // exits the loop when reaching end of file
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (), // There are several other `Event`s we do not consider here
}
buf.clear();
}
}
| {
txt.push(
reader
.read_text(b"tag2", &mut Vec::new())
.expect("Cannot decode text value"),
);
println!("{:?}", txt);
} | conditional_block |
read_texts.rs | extern crate quick_xml;
fn main() {
use quick_xml::events::Event;
use quick_xml::Reader;
let xml = "<tag1>text1</tag1><tag1>text2</tag1>\
<tag1>text3</tag1><tag1><tag2>text4</tag2></tag1>"; |
let mut txt = Vec::new();
let mut buf = Vec::new();
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) if e.name() == b"tag2" => {
txt.push(
reader
.read_text(b"tag2", &mut Vec::new())
.ex... |
let mut reader = Reader::from_str(xml);
reader.trim_text(true); | random_line_split |
lib.rs | #![crate_type = "lib"]
#![crate_name = "comm"]
#![feature(box_syntax, core, alloc, oom, heap_api,
unsafe_no_drop_flag, filling_drop, wait_timeout, wait_timeout_with,
static_mutex, raw, nonzero, drain, num_bits_bytes)]
#![cfg_attr(test, feature(test, scoped))]
#![cfg_attr(test, allow(deprecated))]
... | {
Disconnected,
Full,
Empty,
Deadlock,
}
| Error | identifier_name |
lib.rs | #![crate_type = "lib"]
#![crate_name = "comm"]
#![feature(box_syntax, core, alloc, oom, heap_api,
unsafe_no_drop_flag, filling_drop, wait_timeout, wait_timeout_with,
static_mutex, raw, nonzero, drain, num_bits_bytes)]
#![cfg_attr(test, feature(test, scoped))]
#![cfg_attr(test, allow(deprecated))]
... |
mod sortedvec;
mod marker;
pub mod arc;
pub mod select;
pub mod spsc;
pub mod spmc;
pub mod mpsc;
pub mod mpmc;
/// Errors that can happen during receiving and sending.
///
/// See the individual functions for a list of errors they can return and the specific
/// meaning.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]... | random_line_split | |
test.rs | extern crate pem_parser;
extern crate openssl;
use std::io::prelude::*;
use std::fs::{File};
use std::path::{Path};
use std::process::Command;
use self::openssl::crypto::pkey::{PKey, EncryptionPadding};
const PLAINTEXT_FILE_PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/original_data");
const P... | EncryptionPadding::PKCS1v15 // PKCS is the default padding scheme.
);
let decrypted_data: String = String::from_utf8(decrypted_data).unwrap();
let original_data = read_string(PLAINTEXT_FILE_PATH);
assert_eq!(decrypted_data, original_data);
}
#[test]
/// Assert data encrypted from Rust and decrypted with... | let mut pkey = PKey::new();
pkey.load_priv(&der_private_key);
let decrypted_data: Vec<u8> = pkey.decrypt_with_padding(
&encrypted_data, | random_line_split |
test.rs | extern crate pem_parser;
extern crate openssl;
use std::io::prelude::*;
use std::fs::{File};
use std::path::{Path};
use std::process::Command;
use self::openssl::crypto::pkey::{PKey, EncryptionPadding};
const PLAINTEXT_FILE_PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/original_data");
const P... | <P: AsRef<Path>>(path: P) -> String {
let mut string = String::new();
File::open(path.as_ref()).and_then(|mut f| f.read_to_string(&mut string)).unwrap();
string
}
fn openssl_cli_encrypt(plaintext_file_path: &str, encrypted_file_path: &str, private_key_path: &str) {
let _ = Command::new("openssl")
... | read_string | identifier_name |
test.rs | extern crate pem_parser;
extern crate openssl;
use std::io::prelude::*;
use std::fs::{File};
use std::path::{Path};
use std::process::Command;
use self::openssl::crypto::pkey::{PKey, EncryptionPadding};
const PLAINTEXT_FILE_PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/original_data");
const P... | }
| {
let public_key_pem_file_contents = read_string(PUBLIC_KEY_PATH);
let der_public_key = pem_parser::pem_to_der(&public_key_pem_file_contents);
let mut pkey = PKey::new();
pkey.load_pub(&der_public_key);
let original_data = read_binary_data(PLAINTEXT_FILE_PATH);
let encrypted_data = pkey.encrypt_with_padd... | identifier_body |
ejdb_bson.rs | //! Contains low-level utilities for conversion between Rust and EJDB BSON representations.
//!
//! This module is only public to facilitate direct usage of `ejdb-sys` library, if such
//! need arises. The types provided here are useful for converting Rust BSON values
//! to EJDB ones and vice versa.
//!
//! Types from... |
#[inline]
pub fn from_rust(oid: oid::ObjectId) -> EjdbObjectId {
EjdbObjectId(ejdb_sys::bson_oid_t {
bytes: to_i(oid.bytes()),
})
}
#[inline]
pub fn to_ejdb(self) -> ejdb_sys::bson_oid_t {
self.0
}
#[inline]
pub fn as_raw(&self) -> *const ejdb_sys:... | {
let bytes: [i8; 12];
unsafe {
bytes = (self.0).bytes;
}
oid::ObjectId::with_bytes(to_u(bytes))
} | identifier_body |
ejdb_bson.rs | //! Contains low-level utilities for conversion between Rust and EJDB BSON representations.
//!
//! This module is only public to facilitate direct usage of `ejdb-sys` library, if such
//! need arises. The types provided here are useful for converting Rust BSON values
//! to EJDB ones and vice versa.
//!
//! Types from... | }
}
impl From<oid::ObjectId> for EjdbObjectId {
#[inline]
fn from(oid: oid::ObjectId) -> EjdbObjectId {
EjdbObjectId::from_rust(oid)
}
}
impl Into<ejdb_sys::bson_oid_t> for EjdbObjectId {
#[inline]
fn into(self) -> ejdb_sys::bson_oid_t {
self.to_ejdb()
}
}
impl Into<oid::O... | impl From<ejdb_sys::bson_oid_t> for EjdbObjectId {
#[inline]
fn from(oid: ejdb_sys::bson_oid_t) -> EjdbObjectId {
EjdbObjectId(oid) | random_line_split |
ejdb_bson.rs | //! Contains low-level utilities for conversion between Rust and EJDB BSON representations.
//!
//! This module is only public to facilitate direct usage of `ejdb-sys` library, if such
//! need arises. The types provided here are useful for converting Rust BSON values
//! to EJDB ones and vice versa.
//!
//! Types from... | (&mut self) -> *mut ejdb_sys::bson {
self.0 as *mut _
}
}
impl Drop for EjdbBsonDocument {
fn drop(&mut self) {
unsafe {
ejdb_sys::bson_del(self.0);
}
}
}
#[derive(Copy, Clone)]
pub struct EjdbObjectId(ejdb_sys::bson_oid_t);
impl EjdbObjectId {
#[inline]
pub fn... | as_raw_mut | identifier_name |
ejdb_bson.rs | //! Contains low-level utilities for conversion between Rust and EJDB BSON representations.
//!
//! This module is only public to facilitate direct usage of `ejdb-sys` library, if such
//! need arises. The types provided here are useful for converting Rust BSON values
//! to EJDB ones and vice versa.
//!
//! Types from... |
ejdb_sys::bson_init(bson_ptr);
EjdbBsonDocument::from_ptr(bson_ptr)
}
}
#[inline]
pub unsafe fn from_ptr(ptr: *mut ejdb_sys::bson) -> EjdbBsonDocument {
EjdbBsonDocument(ptr)
}
#[inline]
pub fn from_buffer(buf: &[u8]) -> EjdbBsonDocument {
unsaf... | {
panic!("Cannot allocate new BSON document");
} | conditional_block |
u256.rs | // Copyright Ethereum Classic Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... |
}
impl Sub<U256> for U256 {
type Output = U256;
fn sub(self, other: U256) -> U256 {
let (o, v) = self.underflowing_sub(other);
assert!(!v);
o
}
}
impl Mul<U256> for U256 {
type Output = U256;
fn mul(self, other: U256) -> U256 {
let (o, v) = self.overflowing_mul(o... | {
let (o, v) = self.overflowing_add(other);
assert!(!v);
o
} | identifier_body |
u256.rs | // Copyright Ethereum Classic Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | else {
return l-1;
}
}
}
return l;
}
}
// Froms, Intos and Defaults
impl Default for U256 {
fn default() -> U256 {
U256::zero()
}
}
impl FromStr for U256 {
type Err = ParseHexError;
fn from_str(s: &str) -> Result<U256, Pars... | {
return l
} | conditional_block |
u256.rs | // Copyright Ethereum Classic Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | (self, other: U256) -> U256 {
let (o, v) = self.overflowing_mul(other);
assert!(!v);
o
}
}
impl Div for U256 {
type Output = U256;
fn div(self, other: U256) -> U256 {
let mut sub_copy = self;
let mut shift_copy = other;
let mut ret = [0u32; 8];
let ... | mul | identifier_name |
u256.rs | // Copyright Ethereum Classic Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | }
/// Minimum value of U256.
pub fn min_value() -> U256 {
U256::zero()
}
/// Add two U256 with overflowing. The same as M256::add.
pub fn overflowing_add(mut self, other: U256) -> (U256, bool) {
let U256(ref mut a) = self;
let U256(ref b) = other;
let carry = ad... | random_line_split | |
chacha.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
self.state[15] += 1;
}
}
impl Rng for ChaChaRng {
#[inline]
fn next_u32(&mut self) -> u32 {
if self.index == STATE_WORDS {
self.update();
}
let value = self.buffer[self.index % STATE_WORDS];
self.index += 1;
value
}
}
impl<'a> SeedableRng<... | { return } | conditional_block |
chacha.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
#[cfg(test)]
mod test {
use std::prelude::*;
use core::iter::order;
use {Rng, SeedableRng};
use super::ChaChaRng;
#[test]
fn test_rng_rand_seeded() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
let mut ra: ChaChaRng = SeedableRng::from_seed(s.as_... | {
let mut key : [u32, ..KEY_WORDS] = [0, ..KEY_WORDS];
for word in key.iter_mut() {
*word = other.gen();
}
SeedableRng::from_seed(key.as_slice())
} | identifier_body |
chacha.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <R: Rng>(other: &mut R) -> ChaChaRng {
let mut key : [u32,..KEY_WORDS] = [0,..KEY_WORDS];
for word in key.iter_mut() {
*word = other.gen();
}
SeedableRng::from_seed(key.as_slice())
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
use core::iter::order;
use ... | rand | identifier_name |
chacha.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
self.state[12] = 0;
self.state[13] = 0;
self.state[14] = 0;
self.state[15] = 0;
self.index = STATE_WORDS;
}
/// Refill the internal output buffer (`self.buffer`)
fn update(&mut self) {
core(&mut self.buffer, &self.state);
self.index = 0;
// ... | for i in range(0, KEY_WORDS) {
self.state[4+i] = key[i];
} | random_line_split |
regions-no-variance-from-fn-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // just to induce a variance on 'a
}
trait UseLife01 {
fn refs<'a, H: HasLife<'a>>(&'a self) -> H;
}
trait UseLife02 {
fn refs<'a, T, H: HasType<&'a T>>(&'a self) -> H;
}
pub trait HasType<T>
{
fn dummy(&self, t: T) -> T { panic!() }
}
trait UseLife03<T> {
fn refs<'a, H: HasType<&'a T>>(&'a self)... | { } | identifier_body |
regions-no-variance-from-fn-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a, H: HasLife<'a>>(_s: &'a ()) -> H {
unimplemented!()
}
pub fn top_refs_2<'a, T, H: HasType<&'a T>>(_s: &'a ()) -> H {
unimplemented!()
}
pub fn main() {}
| top_refs_1 | identifier_name |
regions-no-variance-from-fn-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
pub fn main() {} | random_line_split | |
slave.rs | extern crate byteorder;
extern crate encoding;
use self::byteorder::{ ReadBytesExt, LittleEndian};
use std::fs::{File};
use std::io::{Write,Read,Result};
use std::path::Path; | use self::encoding::all::ISO_8859_1;
pub fn run_slave<T : Read>(stream : &mut T, cfg : SyncConfig) -> Result<()>{
loop {
println!("Waiting for a data");
let path_length : u16 = try!(stream.read_u16::<LittleEndian>());
if path_length == 0{
// ignore empty
continue;
... |
use sync::{SyncConfig};
use self::encoding::{Encoding, DecoderTrap}; | random_line_split |
slave.rs | extern crate byteorder;
extern crate encoding;
use self::byteorder::{ ReadBytesExt, LittleEndian};
use std::fs::{File};
use std::io::{Write,Read,Result};
use std::path::Path;
use sync::{SyncConfig};
use self::encoding::{Encoding, DecoderTrap};
use self::encoding::all::ISO_8859_1;
pub fn | <T : Read>(stream : &mut T, cfg : SyncConfig) -> Result<()>{
loop {
println!("Waiting for a data");
let path_length : u16 = try!(stream.read_u16::<LittleEndian>());
if path_length == 0{
// ignore empty
continue;
}
println!("Got the file name size: {}",... | run_slave | identifier_name |
slave.rs | extern crate byteorder;
extern crate encoding;
use self::byteorder::{ ReadBytesExt, LittleEndian};
use std::fs::{File};
use std::io::{Write,Read,Result};
use std::path::Path;
use sync::{SyncConfig};
use self::encoding::{Encoding, DecoderTrap};
use self::encoding::all::ISO_8859_1;
pub fn run_slave<T : Read>(stream ... | println!("Writing data to {}",path);
let mut file = try!(File::create(path));
try!(file.write_all(&data[..]));
}
}
| {
loop {
println!("Waiting for a data");
let path_length : u16 = try!(stream.read_u16::<LittleEndian>());
if path_length == 0{
// ignore empty
continue;
}
println!("Got the file name size: {}", path_length);
let mut path_data = vec![0u8;0];
... | identifier_body |
methods.rs | // TODO: set request's origin to request's client's origin
unimplemented!()
}
// Step 3.
set_default_accept(request.type_, request.destination, &mut request.headers);
// Step 4.
set_default_accept_language(&mut request.headers);
// Step 5.
// TODO: figure out what a Priority o... |
/// [Scheme fetch](https://fetch.spec.whatwg.org#scheme-fetch)
fn scheme_fetch(request: &mut Request,
cache: &mut CorsCache,
target: Target,
done_chan: &mut DoneChannel,
context: &FetchContext)
-> Response {
let url = request.current_url();... | } | random_line_split |
methods.rs | // TODO: set request's origin to request's client's origin
unimplemented!()
}
// Step 3.
set_default_accept(request.type_, request.destination, &mut request.headers);
// Step 4.
set_default_accept_language(&mut request.headers);
// Step 5.
// TODO: figure out what a Priority ob... |
}
}
/// [Scheme fetch](https://fetch.spec.whatwg.org#scheme-fetch)
fn scheme_fetch(request: &mut Request,
cache: &mut CorsCache,
target: Target,
done_chan: &mut DoneChannel,
context: &FetchContext)
-> Response {
let url = request.curre... | {
assert!(*body == ResponseBody::Empty)
} | conditional_block |
methods.rs | // TODO: set request's origin to request's client's origin
unimplemented!()
}
// Step 3.
set_default_accept(request.type_, request.destination, &mut request.headers);
// Step 4.
set_default_accept_language(&mut request.headers);
// Step 5.
// TODO: figure out what a Priority ob... |
/// <https://fetch.spec.whatwg.org/#cors-safelisted-method>
pub fn is_cors_safelisted_method(m: &Method) -> bool {
match *m {
Method::Get | Method::Head | Method::Post => true,
_ => false
}
}
fn is_null_body_status(status: &Option<StatusCode>) -> bool {
match *status {
Some(status... | {
if h.is::<ContentType>() {
match h.value() {
Some(&ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) |
Some(&ContentType(Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _))) |
Some(&ContentType(Mime(TopLevel::Multipart, SubLevel::FormData, _))) => true,
... | identifier_body |
methods.rs | // TODO: set request's origin to request's client's origin
unimplemented!()
}
// Step 3.
set_default_accept(request.type_, request.destination, &mut request.headers);
// Step 4.
set_default_accept_language(&mut request.headers);
// Step 5.
// TODO: figure out what a Priority ob... | (h: &HeaderView) -> bool {
if h.is::<ContentType>() {
match h.value() {
Some(&ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) |
Some(&ContentType(Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _))) |
Some(&ContentType(Mime(TopLevel::Multipart, SubLevel::F... | is_cors_safelisted_request_header | identifier_name |
procsrv.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 ... | (lib_path: &str,
prog: &str,
args: &[~str],
env: ~[(~str, ~str)],
input: Option<~str>) -> Result {
let env = env + target_env(lib_path, prog);
let mut proc = run::Process::new(prog, args, run::ProcessOptions {
env: Some(env.slice(0, env.len())),
dir: ... | run | identifier_name |
procsrv.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 struct Result {status: int, out: ~str, err: ~str}
pub fn run(lib_path: &str,
prog: &str,
args: &[~str],
env: ~[(~str, ~str)],
input: Option<~str>) -> Result {
let env = env + target_env(lib_path, prog);
let mut proc = run::Process::new(prog, args, run::ProcessOp... | random_line_split | |
procsrv.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 ... |
};
if prog.ends_with("rustc.exe") {
env.push((~"RUST_THREADS", ~"1"));
}
return env;
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn target_env(_lib_path: &str, _prog: &str) -> ~[(~str,~str)] {
os::env()
}
pub struct Result {status: int, out: ~st... | { (k,v) } | conditional_block |
exchange.rs | //! This module contains Exchange enum.
use std::fmt::Debug;
use std::convert::Into;
use std::str::FromStr;
use crate::error::*;
use crate::types::*;
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Exchange {
Bitstamp,
Kraken,
Poloniex,
Bittrex,
Gdax,
}
impl Into<String> for Exchange {
... |
}
pub trait ExchangeApi: Debug {
/// Return a Ticker for the Pair specified.
fn ticker(&mut self, pair: Pair) -> Result<Ticker>;
/// Return an Orderbook for the specified Pair.
fn orderbook(&mut self, pair: Pair) -> Result<Orderbook>;
/// Place an order directly to the exchange.
/// Quantity... | {
match input.to_lowercase().as_str() {
"bitstamp" => Ok(Exchange::Bitstamp),
"kraken" => Ok(Exchange::Kraken),
"poloniex" => Ok(Exchange::Poloniex),
"bittrex" => Ok(Exchange::Bittrex),
"gdax" => Ok(Exchange::Gdax),
_ => Err(ErrorKind::Inva... | identifier_body |
exchange.rs | //! This module contains Exchange enum.
use std::fmt::Debug;
use std::convert::Into;
use std::str::FromStr;
|
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Exchange {
Bitstamp,
Kraken,
Poloniex,
Bittrex,
Gdax,
}
impl Into<String> for Exchange {
fn into(self) -> String {
match self {
Exchange::Bitstamp => "Bitstamp".to_string(),
Exchange::Kraken => "Kraken".to_stri... | use crate::error::*;
use crate::types::*;
| random_line_split |
exchange.rs | //! This module contains Exchange enum.
use std::fmt::Debug;
use std::convert::Into;
use std::str::FromStr;
use crate::error::*;
use crate::types::*;
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum | {
Bitstamp,
Kraken,
Poloniex,
Bittrex,
Gdax,
}
impl Into<String> for Exchange {
fn into(self) -> String {
match self {
Exchange::Bitstamp => "Bitstamp".to_string(),
Exchange::Kraken => "Kraken".to_string(),
Exchange::Poloniex => "Poloniex".to_string(... | Exchange | identifier_name |
print_table.rs | //! Directly executes an SQL query and prints the result set to standard out
//!
//! This example also offers an idea, how to set up error handling for your ODBC Application.
extern crate odbc_safe;
use odbc_safe::*;
use std::str::from_utf8;
// Setup error handling
struct LastError(String);
type MyResult<T> = Result<T... |
fn run(env: &Environment<Odbc3>) -> MyResult<()> {
let conn = connect(&env)?;
let result_set = execute_query(&conn)?;
print_fields(result_set)
}
fn connect<V>(env: &Environment<V>) -> MyResult<Connection<impl AutocommitMode>>
where
V: Version,
{
let conn = DataSource::with_parent(env).unwrap();
... | {
let env = Environment::new().unwrap();
let env = env.declare_version_3().unwrap();
match run(&env) {
Ok(()) => (),
Err(LastError(message)) => println!("An error occurred: {}", message),
}
} | identifier_body |
print_table.rs | //! Directly executes an SQL query and prints the result set to standard out
//!
//! This example also offers an idea, how to set up error handling for your ODBC Application.
extern crate odbc_safe;
use odbc_safe::*;
use std::str::from_utf8;
// Setup error handling
struct LastError(String);
type MyResult<T> = Result<T... | (source: D) -> Self {
let mut buffer = [0; 512];
match source.diagnostics(1, &mut buffer) {
ReturnOption::Success(dr) |
ReturnOption::Info(dr) => LastError(
from_utf8(&buffer[0..(dr.text_length as usize)])
.unwrap()
.to_owned(... | from | identifier_name |
print_table.rs | //! Directly executes an SQL query and prints the result set to standard out
//!
//! This example also offers an idea, how to set up error handling for your ODBC Application.
extern crate odbc_safe;
use odbc_safe::*;
use std::str::from_utf8;
// Setup error handling
struct LastError(String);
type MyResult<T> = Result<T... | fn main() {
let env = Environment::new().unwrap();
let env = env.declare_version_3().unwrap();
match run(&env) {
Ok(()) => (),
Err(LastError(message)) => println!("An error occurred: {}", message),
}
}
fn run(env: &Environment<Odbc3>) -> MyResult<()> {
let conn = connect(&env)?;
... | // Actual application | random_line_split |
animate.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 darling::util::IdentList;
use derive_common::cg;
use proc_macro2::TokenStream;
use quote::TokenStreamExt;
use... | (mut input: DeriveInput) -> TokenStream {
let animation_input_attrs = cg::parse_input_attrs::<AnimationInputAttrs>(&input);
let no_bound = animation_input_attrs.no_bound.unwrap_or_default();
let mut where_clause = input.generics.where_clause.take();
for param in input.generics.type_params() {
if... | derive | identifier_name |
animate.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 darling::util::IdentList;
use derive_common::cg;
use proc_macro2::TokenStream;
use quote::TokenStreamExt;
use... | fn derive_variant_arm(
variant: &VariantInfo,
where_clause: &mut Option<WhereClause>,
) -> Result<TokenStream, ()> {
let variant_attrs = cg::parse_variant_attrs_from_ast::<AnimationVariantAttrs>(&variant.ast());
if variant_attrs.error {
return Err(());
}
let (this_pattern, this_info) = c... | }
}
}
}
| random_line_split |
animate.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 darling::util::IdentList;
use derive_common::cg;
use proc_macro2::TokenStream;
use quote::TokenStreamExt;
use... | else {
match_body.append_all(quote! { _ => Err(()) });
}
}
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
quote! {
impl #impl_generics crate::values::animated::Animate for #name #ty_generics #where_clause {
... | {
match_body.append_all(quote! {
(this, other) => #fallback(this, other, procedure)
});
} | conditional_block |
animate.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 darling::util::IdentList;
use derive_common::cg;
use proc_macro2::TokenStream;
use quote::TokenStreamExt;
use... | quote! {
if #this!= #other {
return Err(());
}
let #result = std::clone::Clone::clone(#this);
}
} else {
quote! {
let #result =
crate::values::animated::Animate::animate(#t... | {
let variant_attrs = cg::parse_variant_attrs_from_ast::<AnimationVariantAttrs>(&variant.ast());
if variant_attrs.error {
return Err(());
}
let (this_pattern, this_info) = cg::ref_pattern(&variant, "this");
let (other_pattern, other_info) = cg::ref_pattern(&variant, "other");
let (result... | identifier_body |
error.rs | //! Messaging primitives for server errors.
use std::borrow::Cow;
use std::io::{self, Write};
use nom::IResult;
/// Error reported by the server and sent to the client.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorResponse<'a> {
message: Cow<'a, str>,
}
impl<'a> ErrorResponse<'a> {
/// Create a ne... |
/// Message describing the error that occured.
pub fn message(&self) -> &str {
&*self.message
}
/// Create an owned version of the ErrorResponse.
pub fn to_owned(&self) -> ErrorResponse<'static> {
ErrorResponse { message: Cow::Owned((*self.message).to_owned()) }
}
}
| {
try!(writer.write_all(self.message.as_bytes()));
Ok(())
} | identifier_body |
error.rs | //! Messaging primitives for server errors.
use std::borrow::Cow;
use std::io::{self, Write};
use nom::IResult;
/// Error reported by the server and sent to the client.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorResponse<'a> {
message: Cow<'a, str>,
}
impl<'a> ErrorResponse<'a> {
/// Create a ne... | (bytes: &'a [u8]) -> IResult<&'a [u8], ErrorResponse<'a>> {
map!(bytes, take_str!(bytes.len()), |m| ErrorResponse::new(m))
}
/// Write the ErrorResponse to the given writer.
pub fn write_bytes<W>(&self, mut writer: W) -> io::Result<()>
where W: Write
{
try!(writer.write_all(self... | from_bytes | identifier_name |
error.rs | //! Messaging primitives for server errors.
use std::borrow::Cow;
use std::io::{self, Write}; | use nom::IResult;
/// Error reported by the server and sent to the client.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorResponse<'a> {
message: Cow<'a, str>,
}
impl<'a> ErrorResponse<'a> {
/// Create a new ErrorResponse.
pub fn new(message: &'a str) -> ErrorResponse<'a> {
ErrorResponse {... | random_line_split | |
sudoku.rs | #[macro_use]
extern crate kanren;
use kanren::core::{State, Unifier, Var, VarStore, VarRetrieve};
use kanren::iter::StateIter;
use kanren::list::List;
use kanren::list::{Pair, Nil};
use std::io::Read;
use std::fmt::{Formatter, Debug};
use kanren::finitedomain::Fd;
use kanren::constraints::AllDiffConstraint;
fn main()... |
for (i, mut state) in get_fds(state, orig_list).into_iter().enumerate().take(100) {
//let reifier = Reifier::new(&state);
println!("solution {}:", i);
display_list(&mut state, orig_list);
println!("");
//println!("state: {:?}\n", state);
}
}
| {
let items: Vec<_> = i.into_iter().map(|x| UnderscoreWriter(x)).collect();
for chunk in items.chunks(9) {
println!("{:?}", chunk);
}
} | identifier_body |
sudoku.rs | #[macro_use]
extern crate kanren;
use kanren::core::{State, Unifier, Var, VarStore, VarRetrieve};
use kanren::iter::StateIter;
use kanren::list::List;
use kanren::list::{Pair, Nil};
use std::io::Read;
use std::fmt::{Formatter, Debug};
use kanren::finitedomain::Fd;
use kanren::constraints::AllDiffConstraint;
fn main()... | else { None })
.into_iter()
}).collect();
println!("Input: ");
display_output(puzzle.iter().map(|x| *x));
println!("");
assert!(puzzle.len() == 81);
let xy = (0..9).flat_map(|y| (0..9).map(move |x| (x,y)));
for ((x, y), &puz) in xy.zip(puzzle.iter()) {
fresh!(sta... |
let puzzle: Vec<Option<u8>> = puzstr.chars().flat_map(|x| {
(if x.is_numeric() { Some(Some((x as u32 - '0' as u32) as u8)) }
else if x == '_' { Some(None) } | random_line_split |
sudoku.rs | #[macro_use]
extern crate kanren;
use kanren::core::{State, Unifier, Var, VarStore, VarRetrieve};
use kanren::iter::StateIter;
use kanren::list::List;
use kanren::list::{Pair, Nil};
use std::io::Read;
use std::fmt::{Formatter, Debug};
use kanren::finitedomain::Fd;
use kanren::constraints::AllDiffConstraint;
fn main()... | (state: State, list: Var<List<Fd>>) -> StateIter {
//conde!(state, {
//state.unify(list, Nil);
//single(state)
//}, {
//fresh!(state, head, tail);
//state.unify(list, Pair(head, tail));
//}
::kanren::core::assign_all_values(state)
}
... | get_fds | identifier_name |
generate.rs | use fact_table::FactTable;
use program::Program;
use rand;
use std::cmp;
use std::collections::hash_map::{Entry, HashMap};
use std::fmt;
use truth_value::TruthValue;
use types::{Clause, Constant, Literal, Predicate, Term, TermIndex};
pub struct Generator<R>
where R: rand::Rng
{
rng: R,
max_predicate: Predi... |
}
| {
let rng = XorShiftRng::from_seed([0xde, 0xad, 0xbe, 0xef]);
let (facts, program, _) = program::<()>(r#"
a(0).
a(1).
a(X) :- b(X)
"#)
.unwrap()
.0;
let mut generator = Generator::new(rng, &facts, &program);
println!("genera... | identifier_body |
generate.rs | use fact_table::FactTable;
use program::Program;
use rand;
use std::cmp;
use std::collections::hash_map::{Entry, HashMap};
use std::fmt;
use truth_value::TruthValue;
use types::{Clause, Constant, Literal, Predicate, Term, TermIndex};
pub struct Generator<R>
where R: rand::Rng
{
rng: R,
max_predicate: Predi... |
num_remaining_output_terms -= 1;
}
let literal = Literal::new_from_vec(predicate, terms);
body.push(literal);
}
let clause = Clause::new_from_vec(head, body);
return clause;
}
}
impl<R> fmt::Debug for Generator<R>
where R: rand::Rng
{... | {
if self.rng.gen_weighted_bool(3) {
// With 1/3 probability, output a constant.
terms.push(Term::Constant(self.gen_constant(predicate, term_index)));
} else {
// Might want to increase the number of variable... | conditional_block |
generate.rs | use fact_table::FactTable;
use program::Program;
use rand;
use std::cmp;
use std::collections::hash_map::{Entry, HashMap};
use std::fmt;
use truth_value::TruthValue;
use types::{Clause, Constant, Literal, Predicate, Term, TermIndex};
pub struct Generator<R>
where R: rand::Rng
{
rng: R,
max_predicate: Predi... | (&mut self, max_new_predicate_terms: usize) -> (Literal, usize) {
let predicate = self.gen_predicate();
let num_terms = self.get_num_terms(predicate, max_new_predicate_terms);
let num_output_variables = if self.rng.gen_weighted_bool(8) {
// With 1/8 probability, select a random numbe... | gen_head | identifier_name |
generate.rs | use fact_table::FactTable;
use program::Program;
use rand;
use std::cmp;
use std::collections::hash_map::{Entry, HashMap};
use std::fmt;
use truth_value::TruthValue;
use types::{Clause, Constant, Literal, Predicate, Term, TermIndex};
pub struct Generator<R>
where R: rand::Rng
{
rng: R,
max_predicate: Predi... | self.max_constant)
}
}
#[cfg(test)]
mod tests {
use super::Generator;
use parser::program;
use rand::SeedableRng;
use rand::XorShiftRng;
#[test]
fn can_generate_a_clause() {
let rng = XorShiftRng::from_seed([0xde, 0xad, 0xbe, 0xef]);
let (facts, program, _) =... | self.num_terms, | random_line_split |
webglframebuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLFr... | (renderer: IpcSender<CanvasMsg>, id: u32) -> WebGLFramebuffer {
WebGLFramebuffer {
webgl_object: WebGLObject::new_inherited(),
id: id,
is_deleted: Cell::new(false),
renderer: renderer,
}
}
pub fn maybe_new(global: GlobalRef, renderer: IpcSender<Ca... | new_inherited | identifier_name |
webglframebuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLFr... |
}
}
| {
self.is_deleted.set(true);
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteFramebuffer(self.id))).unwrap();
} | conditional_block |
webglframebuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLFr... |
fn delete(self) {
if!self.is_deleted.get() {
self.is_deleted.set(true);
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteFramebuffer(self.id))).unwrap();
}
}
}
| {
let cmd = CanvasWebGLMsg::BindFramebuffer(target, WebGLFramebufferBindingRequest::Explicit(self.id));
self.renderer.send(CanvasMsg::WebGL(cmd)).unwrap();
} | identifier_body |
webglframebuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLFr... |
pub trait WebGLFramebufferHelpers {
fn id(self) -> u32;
fn bind(self, target: u32);
fn delete(self);
}
impl<'a> WebGLFramebufferHelpers for &'a WebGLFramebuffer {
fn id(self) -> u32 {
self.id
}
fn bind(self, target: u32) {
let cmd = CanvasWebGLMsg::BindFramebuffer(target, WebG... | reflect_dom_object(box WebGLFramebuffer::new_inherited(renderer, id), global, WebGLFramebufferBinding::Wrap)
}
} | random_line_split |
atomic_store_rel.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_store_rel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_store_rel_rel<T>(dst: *mut T, val: T);
struct A<T> {
v: UnsafeCell<T>
}
unsafe ... | #[test]
fn atomic_store_rel_test1() {
atomic_store_rel_test!( 68, 500 );
}
} | random_line_split | |
atomic_store_rel.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_store_rel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_store_rel_rel<T>(dst: *mut T, val: T);
struct | <T> {
v: UnsafeCell<T>
}
unsafe impl Sync for A<T> {}
impl<T> A<T> {
fn new(v: T) -> A<T> {
A { v: UnsafeCell::<T>::new(v) }
}
}
type T = usize;
macro_rules! atomic_store_rel_test {
($init:expr, $value:expr) => ({
let value: T = $init;
let a: A<T> = A::<T>::new(value);
... | A | identifier_name |
atomic_store_rel.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_store_rel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_store_rel_rel<T>(dst: *mut T, val: T);
struct A<T> {
v: UnsafeCell<T>
}
unsafe ... |
}
| {
atomic_store_rel_test!( 68, 500 );
} | identifier_body |
asm-in-out-operand.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... | () {}
| main | identifier_name |
asm-in-out-operand.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... | {} | identifier_body | |
asm-in-out-operand.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | assert_eq!(x, 47);
assert_eq!(y, 47);
let mut x = x + 1;
assert_eq!(x, 48);
unsafe {
// Assignment to mutable.
// Early clobber "&":
// Forbids the use of a single register by both operands.
asm!("shr $$2, $1; add $1, $0" : "+&r"(x) : "r"(x) : "cc");
}
asser... | random_line_split | |
common.rs | // Copyright 2012-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-MI... | pub const tag_item_method_tps: uint = 0x79;
pub const tag_item_method_fty: uint = 0x7a;
pub const tag_mod_child: uint = 0x7b;
pub const tag_misc_info: uint = 0x108; // top-level only
pub const tag_misc_info_crate_items: uint = 0x7c;
pub const tag_item_method_provided_source: uint = 0x7d;
pub const tag_item_impl_vtabl... | pub const tag_item_unnamed_field: uint = 0x77;
pub const tag_items_data_item_visibility: uint = 0x78;
| random_line_split |
common.rs | // Copyright 2012-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-MI... | { // Reserves 0x50 -- 0x6f
tag_ast = 0x50,
tag_tree = 0x51,
tag_id_range = 0x52,
tag_table = 0x53,
// GAP 0x54, 0x55
tag_table_def = 0x56,
tag_table_node_type = 0x57,
tag_table_item_subst = 0x58,
tag_table_freevars = 0x59,
tag_table_tcache = 0x5a,
tag_table_param_defs = 0... | astencode_tag | identifier_name |
issue-61076.rs | // edition:2018
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
struct T;
struct Tuple(i32);
struct Struct {
a: i32
}
impl Struct {
fn method(&self) {}
}
impl Future for Struct {
type Output = Struct;
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::O... |
}
impl Future for T {
type Output = Result<(), ()>;
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Pending
}
}
async fn foo() -> Result<(), ()> {
Ok(())
}
async fn bar() -> Result<(), ()> {
foo()?; //~ ERROR the `?` operator can only be applied to value... | { Poll::Pending } | identifier_body |
issue-61076.rs | // edition:2018
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
struct T;
struct Tuple(i32);
struct Struct {
a: i32
}
impl Struct {
fn method(&self) {}
}
impl Future for Struct {
type Output = Struct;
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::O... | let _: i32 = tuple().0; //~ ERROR no field `0`
//~^ HELP consider `await`ing on the `Future`
//~| NOTE field not available in `impl Future`
let _: i32 = struct_().a; //~ ERROR no field `a`
//~^ HELP consider `await`ing on the `Future`
//~| NOTE field not available in `impl Future`
struct_(... | //~| NOTE in this expansion of desugaring of operator `?`
//~| NOTE in this expansion of desugaring of operator `?`
//~| NOTE in this expansion of desugaring of operator `?`
| random_line_split |
issue-61076.rs | // edition:2018
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
struct T;
struct Tuple(i32);
struct Struct {
a: i32
}
impl Struct {
fn method(&self) {}
}
impl Future for Struct {
type Output = Struct;
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::O... | () {
match tuple() { //~ HELP consider `await`ing on the `Future`
Tuple(_) => {} //~ ERROR mismatched types
//~^ NOTE expected opaque type, found struct `Tuple`
//~| NOTE expected opaque type `impl Future<Output = Tuple>`
}
}
fn main() {}
| match_ | identifier_name |
angle.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/. */
//! Computed angles.
use num_traits::Zero;
use std::f64::consts::PI;
use std::fmt::{self, Write};
use std::ops::A... | <W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.degrees().to_css(dest)?;
dest.write_str("deg")
}
}
const RAD_PER_DEG: f64 = PI / 180.0;
impl Angle {
/// Creates a computed `Angle` value from a radian amount.
pub fn from_radians(radians: CSSFloat) -... | to_css | identifier_name |
angle.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/. */
//! Computed angles.
use num_traits::Zero;
use std::f64::consts::PI;
use std::fmt::{self, Write};
use std::ops::A... |
}
| {
// Use the formula for calculating the distance between angles defined in SVG:
// https://www.w3.org/TR/SVG/animate.html#complexDistances
self.radians64()
.compute_squared_distance(&other.radians64())
} | identifier_body |
angle.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/. */
//! Computed angles.
use num_traits::Zero;
use std::f64::consts::PI;
use std::fmt::{self, Write};
use std::ops::A... | }
}
impl Add for Angle {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
Angle(self.0 + rhs.0)
}
}
impl Zero for Angle {
#[inline]
fn zero() -> Self {
Angle(0.0)
}
#[inline]
fn is_zero(&self) -> bool {
self.0 == 0.
}
}
impl Compute... | /// Return the value in degrees.
#[inline]
pub fn degrees(&self) -> CSSFloat {
self.0 | random_line_split |
connection.rs | use std::{
fmt::Display,
io::{self, BufRead, BufReader, Write},
net::ToSocketAddrs,
time::Duration,
};
use super::{ClientCodec, NetworkStream, TlsParameters};
use crate::{
address::Envelope,
transport::smtp::{
authentication::{Credentials, Mechanism},
commands::*,
error,... |
mail_options.push(MailParameter::SmtpUtfEight);
}
// Check for non-ascii content in message
if!email.is_ascii() {
if!self.server_info().supports_feature(Extension::EightBitMime) {
return Err(error::client(
"Message contains non-ascii ... | {
// don't try to send non-ascii addresses (per RFC)
return Err(error::client(
"Envelope contains non-ascii chars but server does not support SMTPUTF8",
));
} | conditional_block |
connection.rs | use std::{
fmt::Display,
io::{self, BufRead, BufReader, Write},
net::ToSocketAddrs,
time::Duration,
};
use super::{ClientCodec, NetworkStream, TlsParameters};
use crate::{
address::Envelope,
transport::smtp::{
authentication::{Credentials, Mechanism},
commands::*,
error,... | (&mut self, duration: Option<Duration>) -> io::Result<()> {
self.stream.get_mut().set_read_timeout(duration)?;
self.stream.get_mut().set_write_timeout(duration)
}
/// Checks if the server is connected using the NOOP SMTP command
pub fn test_connected(&mut self) -> bool {
self.comman... | set_timeout | identifier_name |
connection.rs | use std::{
fmt::Display,
io::{self, BufRead, BufReader, Write},
net::ToSocketAddrs,
time::Duration,
};
use super::{ClientCodec, NetworkStream, TlsParameters};
use crate::{
address::Envelope,
transport::smtp::{
authentication::{Credentials, Mechanism},
commands::*,
error,... |
/// Sets the underlying stream
pub fn set_stream(&mut self, stream: NetworkStream) {
self.stream = BufReader::new(stream);
}
/// Tells if the underlying stream is currently encrypted
pub fn is_encrypted(&self) -> bool {
self.stream.get_ref().is_encrypted()
}
/// Set timeou... | self.panic = true;
let _ = self.command(Quit);
}
} | random_line_split |
connection.rs | use std::{
fmt::Display,
io::{self, BufRead, BufReader, Write},
net::ToSocketAddrs,
time::Duration,
};
use super::{ClientCodec, NetworkStream, TlsParameters};
use crate::{
address::Envelope,
transport::smtp::{
authentication::{Credentials, Mechanism},
commands::*,
error,... | }
}
}
Err(error::response("incomplete response"))
}
}
| {
let mut buffer = String::with_capacity(100);
while self.stream.read_line(&mut buffer).map_err(error::network)? > 0 {
#[cfg(feature = "tracing")]
tracing::debug!("<< {}", escape_crlf(&buffer));
match parse_response(&buffer) {
Ok((_remaining, response... | identifier_body |
smoke.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 ... | #[test]
fn trylock_works() {
let m = Arc::new(ReentrantMutex::new(()));
let m2 = m.clone();
let _lock = m.try_lock().unwrap();
let _lock2 = m.try_lock().unwrap();
thread::spawn(move || {
let lock = m2.try_lock();
assert!(lock.is_err());
}).join().unwrap();
let _lock3 = m.try_... | drop(lock);
child.join().unwrap();
}
| random_line_split |
smoke.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 ... |
pub struct Answer<'a>(pub ReentrantMutexGuard<'a, RefCell<u32>>);
impl<'a> Drop for Answer<'a> {
fn drop(&mut self) {
*self.0.borrow_mut() = 42;
}
}
#[test]
fn poison_works() {
let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
let mc = m.clone();
let result = thread::spawn(move ||{
... | {
let m = Arc::new(ReentrantMutex::new(()));
let m2 = m.clone();
let _lock = m.try_lock().unwrap();
let _lock2 = m.try_lock().unwrap();
thread::spawn(move || {
let lock = m2.try_lock();
assert!(lock.is_err());
}).join().unwrap();
let _lock3 = m.try_lock().unwrap();
} | identifier_body |
smoke.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
let mc = m.clone();
let result = thread::spawn(move ||{
let lock = mc.lock().unwrap();
*lock.borrow_mut() = 1;
let lock2 = mc.lock().unwrap();
*lock.borrow_mut() = 2;
let _answer = Answer(lock2);
pri... | poison_works | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.