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 |
|---|---|---|---|---|
op.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | {
pub base: ExprNode,
pub name: TString,
pub op_type: FuncType,
pub description: TString,
pub arguments: Array<AttrFieldInfo>,
pub attrs_type_key: TString,
pub attrs_type_index: u32,
pub num_inputs: i32,
pub support_level: i32,
}
| OpNode | identifier_name |
op.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | pub name: TString,
pub op_type: FuncType,
pub description: TString,
pub arguments: Array<AttrFieldInfo>,
pub attrs_type_key: TString,
pub attrs_type_index: u32,
pub num_inputs: i32,
pub support_level: i32,
} | #[type_key = "Op"]
pub struct OpNode {
pub base: ExprNode, | random_line_split |
start.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... |
}
actions
}
}
impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"[Action] [StartRecording] Server #{}",
self.server_id
)
}
}
| {
// Notify all users in the current voice channel
for member in server.channel_voice_members(&self.voice_channel_id) {
actions.push(MessageActions::Send::user_private(
member.id,
format!(
"N... | conditional_block |
start.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... |
}
impl ActionHandler for Action {
fn run(&mut self, bot: &mut Bot, _: &BotConfig, queue: &mut EventQueue) -> ActionGroup {
let mut actions: Vec<Box<ActionHandler>> = Vec::new();
if let Some(server) = bot.get_server(&self.server_id) {
info!("{} Starting audio recording...", self);
... | {
Box::new(Action {
server_id: server_id,
voice_channel_id: voice_channel_id
})
} | identifier_body |
start.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... | f,
"[Action] [StartRecording] Server #{}",
self.server_id
)
}
} |
impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!( | random_line_split |
start.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... | {
server_id: ServerId,
voice_channel_id: ChannelId,
}
impl Action {
pub fn new(
server_id: ServerId,
voice_channel_id: ChannelId
) -> Box<Action> {
Box::new(Action {
server_id: server_id,
voice_channel_id: voice_channel_id
})
}
}
impl Actio... | Action | identifier_name |
next_in_inclusive_range.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::random::variable_range_generator;
use malachite_base::random::EXAMPLE_SEED;
use std::panic::catch_unwind;
fn next_in_inclusive_range_helper<T: PrimitiveUnsigned>(a: T, b: T, expected_values: &[T]) {
let mut range_generator = var... |
#[test]
fn next_in_inclusive_range_fail() {
apply_fn_to_unsigneds!(next_in_inclusive_range_fail_helper);
}
| {
assert_panic!({
let mut range_generator = variable_range_generator(EXAMPLE_SEED);
range_generator.next_in_inclusive_range(T::TWO, T::ONE);
});
} | identifier_body |
next_in_inclusive_range.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::random::variable_range_generator;
use malachite_base::random::EXAMPLE_SEED;
use std::panic::catch_unwind;
fn next_in_inclusive_range_helper<T: PrimitiveUnsigned>(a: T, b: T, expected_values: &[T]) {
let mut range_generator = var... | assert_panic!({
let mut range_generator = variable_range_generator(EXAMPLE_SEED);
range_generator.next_in_inclusive_range(T::TWO, T::ONE);
});
}
#[test]
fn next_in_inclusive_range_fail() {
apply_fn_to_unsigneds!(next_in_inclusive_range_fail_helper);
} | );
}
fn next_in_inclusive_range_fail_helper<T: PrimitiveUnsigned>() { | random_line_split |
next_in_inclusive_range.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::random::variable_range_generator;
use malachite_base::random::EXAMPLE_SEED;
use std::panic::catch_unwind;
fn next_in_inclusive_range_helper<T: PrimitiveUnsigned>(a: T, b: T, expected_values: &[T]) {
let mut range_generator = var... | () {
next_in_inclusive_range_helper::<u8>(5, 5, &[5; 20]);
next_in_inclusive_range_helper::<u16>(
1,
6,
&[2, 6, 4, 2, 3, 5, 6, 2, 3, 6, 5, 1, 6, 1, 3, 6, 3, 1, 5, 1],
);
next_in_inclusive_range_helper::<u32>(
10,
19,
&[11, 17, 15, 14, 16, 14, 12, 18, 11, 1... | test_next_in_inclusive_range | identifier_name |
basic.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
mod examples_util;
use examples_util::*;
use cassandra_sys::*;
use std::ffi::CString;
#[derive(Debug)]
struct Basic {
bln: cass_bool_t,
flt: f32,
dbl: f64,
i32: i32,
i64: i64,
}
fn insert_into_basic(session: &mut CassSessi... |
};
cass_future_free(future);
cass_statement_free(statement);
result
}
}
fn select_from_basic(session: &mut CassSession, key: &str, basic: &mut Basic) -> Result<(), CassError> {
unsafe {
let query = "SELECT * FROM examples.basic WHERE key =?";
let statement = ca... | {
print_error(future);
Err(rc)
} | conditional_block |
basic.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
mod examples_util;
use examples_util::*;
use cassandra_sys::*;
use std::ffi::CString;
#[derive(Debug)]
struct Basic {
bln: cass_bool_t,
flt: f32,
dbl: f64,
i32: i32,
i64: i64,
}
fn insert_into_basic(session: &mut CassSessi... | i64: 0,
};
execute_query(session,
"CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': \
'SimpleStrategy','replication_factor': '1' };")
.unwrap();
execute... | {
unsafe {
let cluster = create_cluster();
let session = &mut *cass_session_new();
let input = &mut Basic {
bln: cass_true,
flt: 0.001f32,
dbl: 0.0002f64,
i32: 1,
i64: 2,
};
match connect_session(session, cluster) ... | identifier_body |
basic.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
mod examples_util;
use examples_util::*;
use cassandra_sys::*;
use std::ffi::CString;
#[derive(Debug)]
struct Basic {
bln: cass_bool_t,
flt: f32,
dbl: f64,
i32: i32,
i64: i64,
}
fn insert_into_basic(session: &mut CassSessi... | (session: &mut CassSession, key: &str, basic: &mut Basic) -> Result<(), CassError> {
unsafe {
let query = "SELECT * FROM examples.basic WHERE key =?";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 1);
cass_statement_bind_string(statement, 0, CString::new(key).unw... | select_from_basic | identifier_name |
basic.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
mod examples_util;
use examples_util::*;
use cassandra_sys::*;
use std::ffi::CString;
#[derive(Debug)]
struct Basic {
bln: cass_bool_t,
flt: f32,
dbl: f64,
i32: i32,
i64: i64,
}
fn insert_into_basic(session: &mut CassSessi... | cass_future_free(future);
result
}
}
pub fn main() {
unsafe {
let cluster = create_cluster();
let session = &mut *cass_session_new();
let input = &mut Basic {
bln: cass_true,
flt: 0.001f32,
dbl: 0.0002f64,
i32: 1,
... | }
rc => Err(rc),
}; | random_line_split |
namednodemap.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::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::code... | (&self, namespace: Option<DOMString>, local_name: DOMString)
-> Fallible<DomRoot<Attr>> {
let ns = namespace_from_domstring(namespace);
self.owner.remove_attribute(&ns, &LocalName::from(local_name))
.ok_or(Error::NotFound)
}
// https://dom.spec.whatwg.org/#dom-n... | RemoveNamedItemNS | identifier_name |
namednodemap.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::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::code... |
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditem
fn GetNamedItem(&self, name: DOMString) -> Option<DomRoot<Attr>> {
self.owner.get_attribute_by_name(name)
}
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditemns
fn GetNamedItemNS(&self, namespace: Option<DOMString>, ... | {
self.owner.attrs().get(index as usize).map(|js| DomRoot::from_ref(&**js))
} | identifier_body |
namednodemap.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | use dom::bindings::error::{Error, Fallible};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString;
use dom::bindings::xmlname::namespace_from_domstring;
use dom::element::Element;
use dom::window::Window;
use dom_struct::dom_struct;
us... |
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding::NamedNodeMapMethods; | random_line_split |
namednodemap.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::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::code... |
}
names
}
}
| {
names.push(DOMString::from(s));
} | conditional_block |
korw.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::KORW, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Direct(K1)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 204, 69, 249], OperandSize::Dword)
}
fn korw_2() {
run... | korw_1 | identifier_name |
korw.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn korw_1() |
fn korw_2() {
run_test(&Instruction { mnemonic: Mnemonic::KORW, operand1: Some(Direct(K7)), operand2: Some(Direct(K3)), operand3: Some(Direct(K2)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 228, 69, 250], OperandSize::Qword)
}
| {
run_test(&Instruction { mnemonic: Mnemonic::KORW, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Direct(K1)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 204, 69, 249], OperandSize::Dword)
} | identifier_body |
korw.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn korw_1() { |
fn korw_2() {
run_test(&Instruction { mnemonic: Mnemonic::KORW, operand1: Some(Direct(K7)), operand2: Some(Direct(K3)), operand3: Some(Direct(K2)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 228, 69, 250], OperandSize::Qword)
} | run_test(&Instruction { mnemonic: Mnemonic::KORW, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Direct(K1)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 204, 69, 249], OperandSize::Dword)
} | random_line_split |
pw_serializer.rs | use super::PlayerId;
use super::pw_rules::{PlanetWars, Planet, Expedition};
use super::pw_protocol as proto;
/// Serialize given gamestate
pub fn serialize(state: &PlanetWars) -> proto::State {
serialize_rotated(state, 0)
}
/// Serialize given gamestate with player numbers rotated by given offset.
pub fn seriali... | (&self, exp: &Expedition) -> proto::Expedition {
proto::Expedition {
id: exp.id,
owner: self.player_num(exp.fleet.owner.unwrap()),
ship_count: exp.fleet.ship_count,
origin: self.state.planets[exp.origin].name.clone(),
destination: self.state.planets[ex... | serialize_expedition | identifier_name |
pw_serializer.rs | use super::PlayerId;
use super::pw_rules::{PlanetWars, Planet, Expedition};
use super::pw_protocol as proto;
/// Serialize given gamestate
pub fn serialize(state: &PlanetWars) -> proto::State |
/// Serialize given gamestate with player numbers rotated by given offset.
pub fn serialize_rotated(state: &PlanetWars, offset: usize) -> proto::State {
let serializer = Serializer::new(state, offset);
serializer.serialize_state()
}
struct Serializer<'a> {
state: &'a PlanetWars,
player_num_offset: us... | {
serialize_rotated(state, 0)
} | identifier_body |
pw_serializer.rs | use super::PlayerId;
use super::pw_rules::{PlanetWars, Planet, Expedition};
use super::pw_protocol as proto;
/// Serialize given gamestate
pub fn serialize(state: &PlanetWars) -> proto::State {
serialize_rotated(state, 0)
}
/// Serialize given gamestate with player numbers rotated by given offset.
pub fn seriali... | origin: self.state.planets[exp.origin].name.clone(),
destination: self.state.planets[exp.target].name.clone(),
turns_remaining: exp.turns_remaining,
}
}
} | random_line_split | |
lib.rs | //! The `libopenreil` crate aims to provide an okay wrapper around openreil-sys.
extern crate openreil_sys;
extern crate libc;
use openreil_sys::root::{reil_addr_t, reil_inst_t, reil_t, reil_arch_t, reil_inst_print,
reil_inst_handler_t, reil_init, reil_close, reil_translate,
... |
fn third_operand(&self) -> Option<reil_arg_t> {
match self.c.type_ {
reil_type_t::A_NONE => None,
_ => Some(self.c)
}
}
fn opcode(&self) -> reil_op_t {
self.op
}
fn mnemonic(&self) -> Option<String> {
let raw_info = self.raw_info;
l... | {
match self.b.type_ {
reil_type_t::A_NONE => None,
_ => Some(self.b)
}
} | identifier_body |
lib.rs | //! The `libopenreil` crate aims to provide an okay wrapper around openreil-sys.
extern crate openreil_sys;
extern crate libc;
use openreil_sys::root::{reil_addr_t, reil_inst_t, reil_t, reil_arch_t, reil_inst_print,
reil_inst_handler_t, reil_init, reil_close, reil_translate,
... | (&mut self, data: &mut [u8], start_address: u32) {
unsafe {
reil_translate(
self.reil_handle,
start_address as reil_addr_t,
data.as_mut_ptr(),
data.len() as libc::c_int,
);
}
}
/// Translate a single instruc... | translate | identifier_name |
lib.rs | //! The `libopenreil` crate aims to provide an okay wrapper around openreil-sys.
extern crate openreil_sys;
extern crate libc;
use openreil_sys::root::{reil_addr_t, reil_inst_t, reil_t, reil_arch_t, reil_inst_print,
reil_inst_handler_t, reil_init, reil_close, reil_translate,
... | pub fn new(
arch: ReilArch,
handler: Option<ReilInstHandler<T>>,
context: &'a mut T,
) -> Option<Self> {
let arch = match arch {
ReilArch::X86 => reil_arch_t::ARCH_X86,
ReilArch::ARM => reil_arch_t::ARCH_ARM,
};
let handler: reil_inst_handl... | /// Construct a new disassembler object
/// The handler function can be used to process the resulting REIL instructions
/// The `context` gets handed to the callback function | random_line_split |
lib.rs | //! The `libopenreil` crate aims to provide an okay wrapper around openreil-sys.
extern crate openreil_sys;
extern crate libc;
use openreil_sys::root::{reil_addr_t, reil_inst_t, reil_t, reil_arch_t, reil_inst_print,
reil_inst_handler_t, reil_init, reil_close, reil_translate,
... |
let byte = *mnem.offset(i) as u8;
mnem_bytes.push(byte);
}
mnem_bytes.push(''as u8);
for i in 0.. {
if *op.offset(i) == 0 { break }
let byte = *op.offset(i) as u8;
mnem_bytes.push(byte);
}
... | { break } | conditional_block |
value.rs | use crate::data::{FloatType, IntegerType};
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
/// The different types of value that are used in the zed virtual machine.
#[derive(Debug)]
pub enum Value {
/// The `nil` value
Nil,
... | 0x08 => string.push_str("\\b"),
0x1b => string.push_str("\\e"),
0x0c => string.push_str("\\f"),
0x0a => string.push_str("\\n"),
0x0d => string.push_str("\\r"),
0x09 => string.push_str("\\t"),
0x0b => string.push_str("\\v"),
0x5c => string.push_str("\\\\"),... | match ch as u32 {
0x20 => string.push(' '),
0x00 => string.push_str("\\0"),
0x07 => string.push_str("\\a"), | random_line_split |
value.rs | use crate::data::{FloatType, IntegerType};
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
/// The different types of value that are used in the zed virtual machine.
#[derive(Debug)]
pub enum Value {
/// The `nil` value
Nil,
... | (&self, f: &mut Formatter) -> FmtResult {
use Value::*;
match self {
Nil => f.pad("nil"),
Boolean(true) => f.pad("true"),
Boolean(false) => f.pad("false"),
Integer(v) => Display::fmt(v, f),
Float(v) => Debug::fmt(v, f),
String(v) => f.pad(&escape_string(v)),
}
}
}
fn e... | fmt | identifier_name |
value.rs | use crate::data::{FloatType, IntegerType};
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
/// The different types of value that are used in the zed virtual machine.
#[derive(Debug)]
pub enum Value {
/// The `nil` value
Nil,
... |
}
impl PartialEq for Value {
fn eq(&self, other: &Value) -> bool {
use Value::*;
match (self, other) {
(Nil, Nil) => true,
(Boolean(a), Boolean(b)) => a == b,
(Integer(a), Integer(b)) => a == b,
(Float(a), Float(b)) => a.to_bits() == b.to_bits(),
(String(a), String(b)) => a == ... | {
use Value::*;
match self {
Nil => Nil,
Boolean(v) => Boolean(*v),
Integer(v) => Integer(*v),
Float(v) => Float(*v),
String(v) => String(v.clone()),
}
} | identifier_body |
scheduler.rs | use alloc::linked_list::LinkedList;
use alloc::arc::Arc;
use super::bottom_half;
use super::bottom_half::BottomHalfManager;
use super::task::{TID_BOTTOMHALFD, TID_SYSTEMIDLE};
use super::task::{Task, TaskContext, TaskPriority, TaskStatus};
use kernel::kget;
use memory::MemoryManager;
const THREAD_QUANTUM: usize = 1... | (&mut self) {
self.need_resched = true;
}
/// Update `last_resched` to now and reset the `need_resched` flag
fn update_last_resched(&mut self) {
let clock = unsafe { &mut *kget().clock.get() };
self.last_resched = clock.now();
self.need_resched = false;
}
/// Find t... | set_need_resched | identifier_name |
scheduler.rs | use alloc::linked_list::LinkedList;
use alloc::arc::Arc;
use super::bottom_half;
use super::bottom_half::BottomHalfManager;
use super::task::{TID_BOTTOMHALFD, TID_SYSTEMIDLE};
use super::task::{Task, TaskContext, TaskPriority, TaskStatus};
use kernel::kget;
use memory::MemoryManager;
const THREAD_QUANTUM: usize = 1... | }
}
// Theres definitely nothing higer priority!
self.next_task(TaskPriority::NORMAL).unwrap()
}
};
let mut old_task = self.active_task.take().unwrap();
// Swap the contexts
// Copy the active context to s... | if t.get_priority() == TaskPriority::IRQ && t.get_status() == TaskStatus::READY
{
return; | random_line_split |
scheduler.rs | use alloc::linked_list::LinkedList;
use alloc::arc::Arc;
use super::bottom_half;
use super::bottom_half::BottomHalfManager;
use super::task::{TID_BOTTOMHALFD, TID_SYSTEMIDLE};
use super::task::{Task, TaskContext, TaskPriority, TaskStatus};
use kernel::kget;
use memory::MemoryManager;
const THREAD_QUANTUM: usize = 1... | else {
found = true;
break;
}
}
if found {
// Split inactive_tasks, remove the task we found, then re-merge the two lists
let mut remainder = self.inactive_tasks.split_off(i);
let next_task = remainder.pop_front();
... | {
// On to the next, this is not suitable
i += 1;
} | conditional_block |
scheduler.rs | use alloc::linked_list::LinkedList;
use alloc::arc::Arc;
use super::bottom_half;
use super::bottom_half::BottomHalfManager;
use super::task::{TID_BOTTOMHALFD, TID_SYSTEMIDLE};
use super::task::{Task, TaskContext, TaskPriority, TaskStatus};
use kernel::kget;
use memory::MemoryManager;
const THREAD_QUANTUM: usize = 1... |
/// Set the internal 'need_resched' flag to true
pub fn set_need_resched(&mut self) {
self.need_resched = true;
}
/// Update `last_resched` to now and reset the `need_resched` flag
fn update_last_resched(&mut self) {
let clock = unsafe { &mut *kget().clock.get() };
self.la... | {
if let Some(ref mut t) = self.active_task {
if t.id() == id {
t.set_status(status);
return;
}
}
for t in self.inactive_tasks.iter_mut() {
if t.id() == id {
t.set_status(status);
return;
... | identifier_body |
hs256.rs | extern crate crypto;
extern crate jwt;
use std::default::Default;
use crypto::sha2::Sha256;
use jwt::{
Header,
Registered,
Token,
};
fn new_token(user_id: &str, password: &str) -> Option<String> |
fn login(token: &str) -> Option<String> {
let token = Token::<Header, Registered>::parse(token).unwrap();
if token.verify(b"secret_key", Sha256::new()) {
token.claims.sub
} else {
None
}
}
fn main() {
let token = new_token("Michael Yang", "password").unwrap();
let logged_in_... | {
// Dummy auth
if password != "password" {
return None
}
let header: Header = Default::default();
let claims = Registered {
iss: Some("mikkyang.com".into()),
sub: Some(user_id.into()),
..Default::default()
};
let token = Token::new(header, claims);
toke... | identifier_body |
hs256.rs | extern crate crypto;
extern crate jwt;
use std::default::Default;
use crypto::sha2::Sha256;
use jwt::{
Header,
Registered,
Token,
};
fn new_token(user_id: &str, password: &str) -> Option<String> {
// Dummy auth
if password!= "password" {
return None
}
let header: Header = Default:... | (token: &str) -> Option<String> {
let token = Token::<Header, Registered>::parse(token).unwrap();
if token.verify(b"secret_key", Sha256::new()) {
token.claims.sub
} else {
None
}
}
fn main() {
let token = new_token("Michael Yang", "password").unwrap();
let logged_in_user = log... | login | identifier_name |
hs256.rs | extern crate crypto;
extern crate jwt;
use std::default::Default;
use crypto::sha2::Sha256;
use jwt::{
Header,
Registered,
Token,
};
fn new_token(user_id: &str, password: &str) -> Option<String> {
// Dummy auth
if password!= "password" {
return None
}
let header: Header = Default:... |
fn login(token: &str) -> Option<String> {
let token = Token::<Header, Registered>::parse(token).unwrap();
if token.verify(b"secret_key", Sha256::new()) {
token.claims.sub
} else {
None
}
}
fn main() {
let token = new_token("Michael Yang", "password").unwrap();
let logged_in_u... | random_line_split | |
hs256.rs | extern crate crypto;
extern crate jwt;
use std::default::Default;
use crypto::sha2::Sha256;
use jwt::{
Header,
Registered,
Token,
};
fn new_token(user_id: &str, password: &str) -> Option<String> {
// Dummy auth
if password!= "password" {
return None
}
let header: Header = Default:... | else {
None
}
}
fn main() {
let token = new_token("Michael Yang", "password").unwrap();
let logged_in_user = login(&*token).unwrap();
assert_eq!(logged_in_user, "Michael Yang");
}
| {
token.claims.sub
} | conditional_block |
output.rs | use crate::error::LucetcErrorKind;
use crate::function_manifest::{write_function_manifest, FUNCTION_MANIFEST_SYM};
use crate::name::Name;
use crate::stack_probe;
use crate::table::{link_tables, TABLE_SYM};
use crate::traps::write_trap_tables;
use byteorder::{LittleEndian, WriteBytesExt};
use cranelift_codegen::{ir, isa... | /// This outputs a.clif file
pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
use cranelift_codegen::write_function;
let mut buffer = String::new();
for (n, func) in self.funcs.iter() {
buffer.push_str(&format!("; {}\n", n.symbol()));
write_func... | impl CraneliftFuncs {
pub fn new(funcs: HashMap<Name, ir::Function>, isa: Box<dyn isa::TargetIsa>) -> Self {
Self { funcs, isa }
} | random_line_split |
output.rs | use crate::error::LucetcErrorKind;
use crate::function_manifest::{write_function_manifest, FUNCTION_MANIFEST_SYM};
use crate::name::Name;
use crate::stack_probe;
use crate::table::{link_tables, TABLE_SYM};
use crate::traps::write_trap_tables;
use byteorder::{LittleEndian, WriteBytesExt};
use cranelift_codegen::{ir, isa... | {
funcs: HashMap<Name, ir::Function>,
isa: Box<dyn isa::TargetIsa>,
}
impl CraneliftFuncs {
pub fn new(funcs: HashMap<Name, ir::Function>, isa: Box<dyn isa::TargetIsa>) -> Self {
Self { funcs, isa }
}
/// This outputs a.clif file
pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<(... | CraneliftFuncs | identifier_name |
output.rs | use crate::error::LucetcErrorKind;
use crate::function_manifest::{write_function_manifest, FUNCTION_MANIFEST_SYM};
use crate::name::Name;
use crate::stack_probe;
use crate::table::{link_tables, TABLE_SYM};
use crate::traps::write_trap_tables;
use byteorder::{LittleEndian, WriteBytesExt};
use cranelift_codegen::{ir, isa... | LUCET_MODULE_SYM,
Some(TABLE_SYM),
table_manifest_len as u64,
)?;
write_relocated_slice(
obj,
&mut native_data,
LUCET_MODULE_SYM,
Some(FUNCTION_MANIFEST_SYM),
function_manifest_len as u64,
)?;
obj.define(LUCET_MODULE_SYM, native_data.into_... | {
let mut native_data = Cursor::new(Vec::with_capacity(std::mem::size_of::<SerializedModule>()));
obj.declare(LUCET_MODULE_SYM, Decl::data().global())
.context(format!("declaring {}", LUCET_MODULE_SYM))?;
let version =
VersionInfo::current(include_str!(concat!(env!("OUT_DIR"), "/commit_hash... | identifier_body |
suggest-change-mut.rs | #![allow(warnings)]
use std::io::{BufRead, BufReader, Read, Write};
fn issue_81421<T: Read + Write>(mut stream: T) { //~ HELP consider introducing a `where` bound
let initial_message = format!("Hello world");
let mut buffer: Vec<u8> = Vec::new();
let bytes_written = stream.write_all(initial_message.as_byt... | {} | identifier_body | |
suggest-change-mut.rs | #![allow(warnings)]
use std::io::{BufRead, BufReader, Read, Write};
fn issue_81421<T: Read + Write>(mut stream: T) { //~ HELP consider introducing a `where` bound
let initial_message = format!("Hello world");
let mut buffer: Vec<u8> = Vec::new();
let bytes_written = stream.write_all(initial_message.as_byt... | () {}
| main | identifier_name |
suggest-change-mut.rs | #![allow(warnings)]
use std::io::{BufRead, BufReader, Read, Write};
fn issue_81421<T: Read + Write>(mut stream: T) { //~ HELP consider introducing a `where` bound
let initial_message = format!("Hello world");
let mut buffer: Vec<u8> = Vec::new();
let bytes_written = stream.write_all(initial_message.as_byt... | }
fn main() {} | } | random_line_split |
drain.rs | use std::mem;
use pin_project_lite::pin_project;
use tokio::sync::watch;
use super::{task, Future, Pin, Poll};
pub(crate) fn channel() -> (Signal, Watch) {
let (tx, rx) = watch::channel(());
(Signal { tx }, Watch { rx })
}
pub(crate) struct Signal {
tx: watch::Sender<()>,
}
pub(crate) struct Draining(P... | }
impl Future for TestMe {
type Output = ();
fn poll(mut self: Pin<&mut Self>, _: &mut task::Context<'_>) -> Poll<Self::Output> {
self.poll_cnt += 1;
if self.finished {
Poll::Ready(())
} else {
Poll::Pending
}
... | random_line_split | |
drain.rs | use std::mem;
use pin_project_lite::pin_project;
use tokio::sync::watch;
use super::{task, Future, Pin, Poll};
pub(crate) fn channel() -> (Signal, Watch) {
let (tx, rx) = watch::channel(());
(Signal { tx }, Watch { rx })
}
pub(crate) struct Signal {
tx: watch::Sender<()>,
}
pub(crate) struct Draining(P... | else {
Poll::Pending
}
}
}
#[test]
fn watch() {
let mut mock = tokio_test::task::spawn(());
mock.enter(|cx, _| {
let (tx, rx) = channel();
let fut = TestMe {
draining: false,
finished: false,
... | {
Poll::Ready(())
} | conditional_block |
drain.rs | use std::mem;
use pin_project_lite::pin_project;
use tokio::sync::watch;
use super::{task, Future, Pin, Poll};
pub(crate) fn channel() -> (Signal, Watch) {
let (tx, rx) = watch::channel(());
(Signal { tx }, Watch { rx })
}
pub(crate) struct Signal {
tx: watch::Sender<()>,
}
pub(crate) struct Draining(P... | <F> {
Watch(F),
Draining,
}
impl Signal {
pub(crate) fn drain(self) -> Draining {
let _ = self.tx.send(());
Draining(Box::pin(async move { self.tx.closed().await }))
}
}
impl Future for Draining {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) ... | State | identifier_name |
main.rs | fn main() {
// associating types with the trait.
// helps to avoid everything related with original trait
// to be generic over associated types.
trait Graph {
type Node;
type Edge;
fn has_edge(&self, &Self::Node, &Self::Node) -> bool;
fn edges(&self, &Self::Node) ->Vec<Self::Edge>;... |
fn edges(&self, _n: &Node) -> Vec<Edge> { Vec::new() }
}
// providing actual assoc types for trait objects:
let graph = MyGraph;
let _obj = Box::new(graph) as Box<Graph<Node=Node, Edge=Edge>>;
}
| { true } | identifier_body |
main.rs | fn main() {
// associating types with the trait.
// helps to avoid everything related with original trait
// to be generic over associated types.
trait Graph {
type Node;
type Edge; | fn edges(&self, &Self::Node) ->Vec<Self::Edge>;
}
#[allow(dead_code)]
fn distance<G: Graph>( _graph: &G, _start: &G::Node, _end: &G::Node ) -> u32 {
unimplemented!();
}
// implementing associated types:
struct Node;
struct Edge;
#[allow(dead_code)]
struct MyGraph;
i... |
fn has_edge(&self, &Self::Node, &Self::Node) -> bool; | random_line_split |
main.rs | fn main() {
// associating types with the trait.
// helps to avoid everything related with original trait
// to be generic over associated types.
trait Graph {
type Node;
type Edge;
fn has_edge(&self, &Self::Node, &Self::Node) -> bool;
fn edges(&self, &Self::Node) ->Vec<Self::Edge>;... | <G: Graph>( _graph: &G, _start: &G::Node, _end: &G::Node ) -> u32 {
unimplemented!();
}
// implementing associated types:
struct Node;
struct Edge;
#[allow(dead_code)]
struct MyGraph;
impl Graph for MyGraph {
type Node = Node;
type Edge = Edge;
fn has_edge( &self, _n1... | distance | identifier_name |
lib.rs | //! # How to use serde with rust-protobuf
//!
//! rust-protobuf 3 no longer directly supports serde.
//!
//! Practically, serde is needed mostly to be able to serialize and deserialize JSON,
//! and **rust-protobuf supports JSON directly**, and more correctly according to
//! official protobuf to JSON mapping. For that... | where
R: serde::de::Error,
{
Ok(Some(EnumOrUnknown::from_i32(v)))
}
fn visit_unit<R>(self) -> Result<Self::Value, R>
where
R: serde::de::Error,
{
Ok(None)
}
}
d.deserialize_any(DeserializeEnumVisitor(Phanto... | }
}
fn visit_i32<R>(self, v: i32) -> Result<Self::Value, R> | random_line_split |
lib.rs | //! # How to use serde with rust-protobuf
//!
//! rust-protobuf 3 no longer directly supports serde.
//!
//! Practically, serde is needed mostly to be able to serialize and deserialize JSON,
//! and **rust-protobuf supports JSON directly**, and more correctly according to
//! official protobuf to JSON mapping. For that... |
fn visit_i32<R>(self, v: i32) -> Result<Self::Value, R>
where
R: serde::de::Error,
{
Ok(Some(EnumOrUnknown::from_i32(v)))
}
fn visit_unit<R>(self) -> Result<Self::Value, R>
where
R: serde::de::Error,
{
Ok(None)
... | {
match E::enum_descriptor_static().value_by_name(v) {
Some(v) => Ok(Some(EnumOrUnknown::from_i32(v.value()))),
None => Err(serde::de::Error::custom(format!(
"unknown enum value: {}",
v
))),
}
} | identifier_body |
lib.rs | //! # How to use serde with rust-protobuf
//!
//! rust-protobuf 3 no longer directly supports serde.
//!
//! Practically, serde is needed mostly to be able to serialize and deserialize JSON,
//! and **rust-protobuf supports JSON directly**, and more correctly according to
//! official protobuf to JSON mapping. For that... | <E: EnumFull>(PhantomData<E>);
impl<'de, E: EnumFull> serde::de::Visitor<'de> for DeserializeEnumVisitor<E> {
type Value = Option<EnumOrUnknown<E>>;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
write!(formatter, "a string, an integer or none")
}
... | DeserializeEnumVisitor | identifier_name |
lib.rs | //! # How to use serde with rust-protobuf
//!
//! rust-protobuf 3 no longer directly supports serde.
//!
//! Practically, serde is needed mostly to be able to serialize and deserialize JSON,
//! and **rust-protobuf supports JSON directly**, and more correctly according to
//! official protobuf to JSON mapping. For that... |
}
fn deserialize_enum_or_unknown<'de, E: EnumFull, D: serde::Deserializer<'de>>(
d: D,
) -> Result<Option<EnumOrUnknown<E>>, D::Error> {
struct DeserializeEnumVisitor<E: EnumFull>(PhantomData<E>);
impl<'de, E: EnumFull> serde::de::Visitor<'de> for DeserializeEnumVisitor<E> {
type Value = Option<E... | {
s.serialize_unit()
} | conditional_block |
main.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 ... | all_errors.insert(err_code, info);
}
}
Ok(all_errors)
}
/// Output an HTML page for the errors in `err_map` to `output_path`.
fn render_error_page(err_map: &ErrorMetadataMap, output_path: &Path) -> Result<(), Box<Error>> {
let mut output_file = try!(File::create(output_path));
try... |
let some_errors: ErrorMetadataMap = try!(json::decode(&metadata_str));
for (err_code, info) in some_errors { | random_line_split |
main.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 ... |
}
| {
panic!("{}", e.description());
} | conditional_block |
main.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 ... | () {
if let Err(e) = main_with_result() {
panic!("{}", e.description());
}
}
| main | identifier_name |
main.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 ... |
fn main() {
if let Err(e) = main_with_result() {
panic!("{}", e.description());
}
}
| {
let metadata_dir = get_metadata_dir();
let err_map = try!(load_all_errors(&metadata_dir));
try!(render_error_page(&err_map, Path::new("doc/error-index.html")));
Ok(())
} | identifier_body |
specialization-cross-crate-no-gate.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. | // except according to those terms.
// run-pass
// Test that specialization works even if only the upstream crate enables it
// aux-build:specialization_cross_crate.rs
extern crate specialization_cross_crate;
use specialization_cross_crate::*;
fn main() {
assert!(0u8.foo() == "generic Clone");
assert!(ve... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
specialization-cross-crate-no-gate.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 ... | () {
assert!(0u8.foo() == "generic Clone");
assert!(vec![0u8].foo() == "generic Vec");
assert!(vec![0i32].foo() == "Vec<i32>");
assert!(0i32.foo() == "i32");
assert!(String::new().foo() == "String");
assert!(((), 0).foo() == "generic pair");
assert!(((), ()).foo() == "generic uniform pair");... | main | identifier_name |
specialization-cross-crate-no-gate.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 ... | {
assert!(0u8.foo() == "generic Clone");
assert!(vec![0u8].foo() == "generic Vec");
assert!(vec![0i32].foo() == "Vec<i32>");
assert!(0i32.foo() == "i32");
assert!(String::new().foo() == "String");
assert!(((), 0).foo() == "generic pair");
assert!(((), ()).foo() == "generic uniform pair");
... | identifier_body | |
pir.rs | extern crate rand;
extern crate pung;
use std::mem;
use pung::pir::pir_client::PirClient;
use pung::pir::pir_server::PirServer;
use pung::db::PungTuple;
use rand::Rng;
macro_rules! get_size {
($d_type:ty) => (mem::size_of::<$d_type>() as u64);
}
#[test]
fn | () {
let num = 6;
let alpha = 1;
let d = 1;
let mut collection: Vec<PungTuple> = Vec::new();
let mut rng = rand::thread_rng();
for _ in 0..num {
let mut x: [u8; 286] = [0; 286];
rng.fill_bytes(&mut x);
let pt = PungTuple::new(&x);
collection.push(pt);
}
... | pir_decode | identifier_name |
pir.rs | extern crate rand;
extern crate pung;
use std::mem;
use pung::pir::pir_client::PirClient;
use pung::pir::pir_server::PirServer; |
macro_rules! get_size {
($d_type:ty) => (mem::size_of::<$d_type>() as u64);
}
#[test]
fn pir_decode() {
let num = 6;
let alpha = 1;
let d = 1;
let mut collection: Vec<PungTuple> = Vec::new();
let mut rng = rand::thread_rng();
for _ in 0..num {
let mut x: [u8; 286] = [0; 286];
... | use pung::db::PungTuple;
use rand::Rng; | random_line_split |
pir.rs | extern crate rand;
extern crate pung;
use std::mem;
use pung::pir::pir_client::PirClient;
use pung::pir::pir_server::PirServer;
use pung::db::PungTuple;
use rand::Rng;
macro_rules! get_size {
($d_type:ty) => (mem::size_of::<$d_type>() as u64);
}
#[test]
fn pir_decode() | let client = PirClient::new(1, 1, alpha, d);
let first = 0;
let last = 1;
let test_num = last - first;
let server = PirServer::new(&collection[first..last], alpha, d);
client.update_params(get_size!(PungTuple), test_num as u64, alpha);
// for i in 0..test_num {
{
let query = cl... | {
let num = 6;
let alpha = 1;
let d = 1;
let mut collection: Vec<PungTuple> = Vec::new();
let mut rng = rand::thread_rng();
for _ in 0..num {
let mut x: [u8; 286] = [0; 286];
rng.fill_bytes(&mut x);
let pt = PungTuple::new(&x);
collection.push(pt);
}
... | identifier_body |
fpe.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) Ben Segall <talchas@gmail.com>
// Copyright (c) edef <edef@edef.eu>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opens... | {
let stack = OsStack::new(0).unwrap();
let mut gen = Generator::new(stack, move |yielder, ()| {
yielder.suspend(1.0 / black_box(0.0));
});
unsafe { feenableexcept(FE_DIVBYZERO); }
println!("{:?}", gen.resume(()));
} | identifier_body | |
fpe.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) Ben Segall <talchas@gmail.com>
// Copyright (c) edef <edef@edef.eu>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opens... | () {
let stack = OsStack::new(0).unwrap();
let mut gen = Generator::new(stack, move |yielder, ()| {
yielder.suspend(1.0 / black_box(0.0));
});
unsafe { feenableexcept(FE_DIVBYZERO); }
println!("{:?}", gen.resume(()));
}
| fpe | identifier_name |
fpe.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) Ben Segall <talchas@gmail.com>
// Copyright (c) edef <edef@edef.eu>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opens... |
#[test]
#[ignore]
fn fpe() {
let stack = OsStack::new(0).unwrap();
let mut gen = Generator::new(stack, move |yielder, ()| {
yielder.suspend(1.0 / black_box(0.0));
});
unsafe { feenableexcept(FE_DIVBYZERO); }
println!("{:?}", gen.resume(()));
} | } | random_line_split |
wire.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// This file was forked from https://github.com/lowRISC/manticore.
//! Wire format traits.
//!
//! This module provides [`FromWire`] and [`ToWire`], a pair of traits si... | (e: io::Error) -> Self {
Self::Io(e)
}
}
/// A type which can be serialized into the Cerberus wire format.
pub trait ToWire: Sized {
/// Serializes `self` into `w`.
fn to_wire<W: Write>(&self, w: W) -> Result<(), ToWireError>;
}
/// A serializerion error.
#[derive(Clone, Copy, Debug)]
pub enum ToW... | from | identifier_name |
wire.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// This file was forked from https://github.com/lowRISC/manticore.
//! Wire format traits.
//!
//! This module provides [`FromWire`] and [`ToWire`], a pair of traits si... |
fn from_str(s: &str) -> Result<Self, $crate::protocol::wire::WireEnumFromStrError> {
use $crate::protocol::wire::WireEnum;
match $name::from_name(s) {
Some(val) => Ok(val),
None => Err($crate::protocol::wire::WireEnumFromStrError),
... | }
impl core::str::FromStr for $name {
type Err = $crate::protocol::wire::WireEnumFromStrError; | random_line_split |
wire.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// This file was forked from https://github.com/lowRISC/manticore.
//! Wire format traits.
//!
//! This module provides [`FromWire`] and [`ToWire`], a pair of traits si... |
}
| {
use crate::protocol::wire::*;
assert_eq!(DemoEnum::First.name(), "First");
assert_eq!(DemoEnum::Second.name(), "Second");
} | identifier_body |
htmlbaseelement.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::attr::Attr;
use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use crate::dom::... |
/// <https://html.spec.whatwg.org/multipage/#frozen-base-url>
pub fn frozen_base_url(&self) -> ServoUrl {
let href = self
.upcast::<Element>()
.get_attribute(&ns!(), &local_name!("href"))
.expect(
"The frozen base url is only defined for base elements \... | {
Node::reflect_node(
Box::new(HTMLBaseElement::new_inherited(local_name, prefix, document)),
document,
HTMLBaseElementBinding::Wrap,
)
} | identifier_body |
htmlbaseelement.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::attr::Attr;
use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use crate::dom::... | (&self) -> ServoUrl {
let href = self
.upcast::<Element>()
.get_attribute(&ns!(), &local_name!("href"))
.expect(
"The frozen base url is only defined for base elements \
that have a base url.",
);
let document = document_from_... | frozen_base_url | identifier_name |
htmlbaseelement.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::attr::Attr;
use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use crate::dom::... | }
// https://html.spec.whatwg.org/multipage/#dom-base-href
make_setter!(SetHref, "href");
}
impl VirtualMethods for HTMLBaseElement {
fn super_type(&self) -> Option<&dyn VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
}
fn attribute_mutated(&self, attr: &At... | random_line_split | |
htmlbaseelement.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::attr::Attr;
use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use crate::dom::... |
}
}
impl HTMLBaseElementMethods for HTMLBaseElement {
// https://html.spec.whatwg.org/multipage/#dom-base-href
fn Href(&self) -> DOMString {
// Step 1.
let document = document_from_node(self);
// Step 2.
let attr = self
.upcast::<Element>()
.get_attri... | {
let document = document_from_node(self);
document.refresh_base_element();
} | conditional_block |
u8.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 ... |
#![unstable]
#![doc(primitive = "u8")]
use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
use string::String;
pub use core::u8::{BITS, BYTES, MIN, MAX};
uint_module!(u8) | //! Operations and constants for unsigned 8-bits integers (`u8` type) | random_line_split |
issue-8351-2.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 ... | {
Foo{f: int, b: bool},
Bar,
}
pub fn main() {
let e = Foo{f: 0, b: false};
match e {
Foo{f: 1, b: true} => fail!(),
Foo{b: false, f: 0} => (),
_ => fail!(),
}
}
| E | identifier_name |
issue-8351-2.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 ... | }
} | match e {
Foo{f: 1, b: true} => fail!(),
Foo{b: false, f: 0} => (),
_ => fail!(), | random_line_split |
tsp.rs | extern crate time;
extern crate getopts;
extern crate rand;
// TODO use terminal colors for nicer colored output
// extern crate term;
use getopts::{Options, Matches};
use std::env::args;
use rand::{SeedableRng, StdRng};
use time::precise_time_ns;
use std::str::FromStr;
use graph::Graph;
use population::Population;
... | <T: FromStr>(matches: &Matches, opt: &str, default: T) -> T {
match matches.opt_str(opt) {
Some(o) => o.parse::<T>().unwrap_or(default),
None => default,
}
}
fn main() {
let args: Vec<String> = args().skip(1).collect();
let program = args[0].clone();
let mut opts = Options::new();
... | parse_opt | identifier_name |
tsp.rs | extern crate time;
extern crate getopts;
extern crate rand;
// TODO use terminal colors for nicer colored output
// extern crate term;
use getopts::{Options, Matches};
use std::env::args;
use rand::{SeedableRng, StdRng};
use time::precise_time_ns;
use std::str::FromStr;
use graph::Graph;
use population::Population;
... | else {
// make a seeded RNG for the random graph generation for consistent testing
let seed: &[_] = &[12, 13, 14, 15];
let mut s_rng: StdRng = SeedableRng::from_seed(seed);
graph = Graph::random_graph(&mut s_rng, node_count, scale, scale);
}
if v_flag {
println!("Runnin... | {
let file_path = parse_opt::<String>(&matches, "r", String::new());
if file_path.is_empty() {
panic!("failed to parse file path")
}
graph = Graph::from_file(&file_path).unwrap();
} | conditional_block |
tsp.rs | extern crate time;
extern crate getopts;
extern crate rand;
// TODO use terminal colors for nicer colored output
// extern crate term;
use getopts::{Options, Matches};
use std::env::args;
use rand::{SeedableRng, StdRng};
use time::precise_time_ns;
use std::str::FromStr;
use graph::Graph;
use population::Population;
... |
fn main() {
let args: Vec<String> = args().skip(1).collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu");
opts.optopt("m",
"mutation_rate",
"change the mutation rate (default: 0.015)",
... | {
match matches.opt_str(opt) {
Some(o) => o.parse::<T>().unwrap_or(default),
None => default,
}
} | identifier_body |
tsp.rs | extern crate time;
extern crate getopts;
extern crate rand;
// TODO use terminal colors for nicer colored output
// extern crate term;
use getopts::{Options, Matches};
use std::env::args;
use rand::{SeedableRng, StdRng};
use time::precise_time_ns;
use std::str::FromStr;
use graph::Graph;
use population::Population;
... | fn parse_opt<T: FromStr>(matches: &Matches, opt: &str, default: T) -> T {
match matches.opt_str(opt) {
Some(o) => o.parse::<T>().unwrap_or(default),
None => default,
}
}
fn main() {
let args: Vec<String> = args().skip(1).collect();
let program = args[0].clone();
let mut opts = Optio... | random_line_split | |
cvtdq2ps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn cvtdq2ps_1() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM0)), operand2: Some(Direc... |
fn cvtdq2ps_3() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 252], OperandSize::Qword)
}
fn cvtdq2ps_4() ... | {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexed(EAX, EDI, Eight, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 52,... | identifier_body |
cvtdq2ps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*; |
fn cvtdq2ps_1() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 198], OperandSize::Dword)
}
fn cvtdq2ps_2() {... | use ::Reg::*;
use ::RegScale::*; | random_line_split |
cvtdq2ps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn cvtdq2ps_1() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM0)), operand2: Some(Direc... | () {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexed(EAX, EDI, Eight, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, ... | cvtdq2ps_2 | identifier_name |
main.rs | extern crate splc;
use std::io::prelude::*;
use std::fs::File;
use splc::bio::rna::*;
use splc::bio::fasta::*;
use splc::bio::dna::DNA;
use splc::bio::aa::*;
fn main() {
let mut file = File::open("input").unwrap();
let mut buffer = String::new();
file.read_to_string(&mut buffer).unwrap();
let fastas:... | } | random_line_split | |
main.rs | extern crate splc;
use std::io::prelude::*;
use std::fs::File;
use splc::bio::rna::*;
use splc::bio::fasta::*;
use splc::bio::dna::DNA;
use splc::bio::aa::*;
fn main() {
let mut file = File::open("input").unwrap();
let mut buffer = String::new();
file.read_to_string(&mut buffer).unwrap();
let fastas:... |
pos = pos + 1;
},
Some(n) => {
if &s[pos] == &s[n] {
table.push(Some(n + 1));
cnd = Some(n + 1);
pos = pos + 1;
} else {
... | {
table.push(Some(0));
} | conditional_block |
main.rs | extern crate splc;
use std::io::prelude::*;
use std::fs::File;
use splc::bio::rna::*;
use splc::bio::fasta::*;
use splc::bio::dna::DNA;
use splc::bio::aa::*;
fn main() {
let mut file = File::open("input").unwrap();
let mut buffer = String::new();
file.read_to_string(&mut buffer).unwrap();
let fastas:... | <T: Eq>(haystack: &[T], needle: &[T]) -> Vec<usize> {
let mut vec = Vec::new();
let mut i = 0;
while i < haystack.len() {
let rest = &haystack[i..];
i = i + kmp(rest, needle) + 1;
if i < haystack.len() {
vec.push(i - 1);
}
}
vec
}
fn kmp<T: Eq>(haystack: ... | indices | identifier_name |
main.rs | extern crate splc;
use std::io::prelude::*;
use std::fs::File;
use splc::bio::rna::*;
use splc::bio::fasta::*;
use splc::bio::dna::DNA;
use splc::bio::aa::*;
fn main() {
let mut file = File::open("input").unwrap();
let mut buffer = String::new();
file.read_to_string(&mut buffer).unwrap();
let fastas:... |
fn indices<T: Eq>(haystack: &[T], needle: &[T]) -> Vec<usize> {
let mut vec = Vec::new();
let mut i = 0;
while i < haystack.len() {
let rest = &haystack[i..];
i = i + kmp(rest, needle) + 1;
if i < haystack.len() {
vec.push(i - 1);
}
}
vec
}
fn kmp<T: Eq... | {
// println!("{:?}", intron);
let mut result = Vec::new();
let mut i = 0;
for start in indices(&sequence, intron) {
result.extend_from_slice(&sequence[i .. start]);
i = start + intron.len();
}
result.extend_from_slice(&sequence[i ..]);
*sequence = result;
} | identifier_body |
switch.rs | use core::sync::atomic::Ordering;
use arch;
use super::{contexts, Context, Status, CONTEXT_ID};
/// Switch to the next context
///
/// # Safety
///
/// Do not call this while holding locks!
pub unsafe fn switch() -> bool {
use core::ops::DerefMut;
// Set the global lock to avoid the unsafe operations below f... |
}
if to_ptr as usize == 0 {
for (pid, context_lock) in contexts.iter() {
if *pid < (*from_ptr).id {
let mut context = context_lock.write();
if check_context(&mut context) {
to_ptr = context.deref_mut() as *mut ... | {
let mut context = context_lock.write();
if check_context(&mut context) {
to_ptr = context.deref_mut() as *mut Context;
break;
}
} | conditional_block |
switch.rs | use core::sync::atomic::Ordering;
use arch;
use super::{contexts, Context, Status, CONTEXT_ID};
/// Switch to the next context
///
/// # Safety
///
/// Do not call this while holding locks!
pub unsafe fn | () -> bool {
use core::ops::DerefMut;
// Set the global lock to avoid the unsafe operations below from causing issues
while arch::context::CONTEXT_SWITCH_LOCK.compare_and_swap(false, true, Ordering::SeqCst) {
arch::interrupt::pause();
}
let cpu_id = ::cpu_id();
let from_ptr;
let m... | switch | identifier_name |
switch.rs | use core::sync::atomic::Ordering;
use arch;
use super::{contexts, Context, Status, CONTEXT_ID};
/// Switch to the next context
///
/// # Safety
///
/// Do not call this while holding locks!
pub unsafe fn switch() -> bool | let check_context = |context: &mut Context| -> bool {
if context.cpu_id == None && cpu_id == 0 {
context.cpu_id = Some(cpu_id);
// println!("{}: take {} {}", cpu_id, context.id, ::core::str::from_utf8_unchecked(&context.name.lock()));
}
if con... | {
use core::ops::DerefMut;
// Set the global lock to avoid the unsafe operations below from causing issues
while arch::context::CONTEXT_SWITCH_LOCK.compare_and_swap(false, true, Ordering::SeqCst) {
arch::interrupt::pause();
}
let cpu_id = ::cpu_id();
let from_ptr;
let mut to_ptr =... | identifier_body |
switch.rs | use core::sync::atomic::Ordering;
use arch;
use super::{contexts, Context, Status, CONTEXT_ID};
/// Switch to the next context
///
/// # Safety
///
/// Do not call this while holding locks!
pub unsafe fn switch() -> bool {
use core::ops::DerefMut;
// Set the global lock to avoid the unsafe operations below f... |
(&mut *from_ptr).arch.switch_to(&mut (&mut *to_ptr).arch);
true
} | // Unset global lock before switch, as arch is only usable by the current CPU at this time
arch::context::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst); | random_line_split |
bf.rs | use std::io::{self, Stdout, StdoutLock, Write};
use std::net::TcpStream;
use std::{env, fs, process};
enum Op {
Dec,
Inc,
Prev,
Next,
Loop(Box<[Op]>),
Print,
}
struct Tape {
pos: usize,
tape: Vec<i32>,
}
impl Tape {
fn new() -> Self {
Self {
pos: 0,
... | (&mut self) {
*self.get_mut() -= 1;
}
fn inc(&mut self) {
*self.get_mut() += 1;
}
fn prev(&mut self) {
self.pos -= 1;
}
fn next(&mut self) {
self.pos += 1;
if self.pos >= self.tape.len() {
self.tape.resize(self.pos << 1, 0);
}
}
... | dec | identifier_name |
bf.rs | use std::io::{self, Stdout, StdoutLock, Write};
use std::net::TcpStream;
use std::{env, fs, process};
enum Op {
Dec,
Inc,
Prev,
Next,
Loop(Box<[Op]>),
Print,
}
struct Tape {
pos: usize,
tape: Vec<i32>,
}
impl Tape {
fn new() -> Self {
Self {
pos: 0,
... | fn inc(&mut self) {
*self.get_mut() += 1;
}
fn prev(&mut self) {
self.pos -= 1;
}
fn next(&mut self) {
self.pos += 1;
if self.pos >= self.tape.len() {
self.tape.resize(self.pos << 1, 0);
}
}
}
struct Printer<'a> {
output: StdoutLock<'a>,... | *self.get_mut() -= 1;
}
| random_line_split |
mod.rs | use std::sync::Arc;
use actix_web::HttpRequest;
use anyhow::Result;
use crate::config::AuthenticatorBackend;
use crate::config::Config;
use crate::engine::RulesEngine;
use crate::models::AuditReason;
use crate::models::AuthenticationResult;
use crate::models::AuthenticationStatus;
use crate::models::RequestContext;
u... | }
/// Thread-safe logic to create thread-scoped `Authenticator` instances.
///
/// This allows implementations to initiate and share global state once for the entire process
/// while also allowing the use of thread-scoped objects where needed.
#[derive(Clone)]
pub struct AuthenticatorFactory {
factory: Arc<dyn Au... | random_line_split | |
mod.rs | use std::sync::Arc;
use actix_web::HttpRequest;
use anyhow::Result;
use crate::config::AuthenticatorBackend;
use crate::config::Config;
use crate::engine::RulesEngine;
use crate::models::AuditReason;
use crate::models::AuthenticationResult;
use crate::models::AuthenticationStatus;
use crate::models::RequestContext;
u... | (config: &Config) -> Result<AuthenticatorFactory> {
let factory: Arc<dyn AuthenticationProxyFactory> = match config.authenticator.backend {
#[cfg(debug_assertions)]
AuthenticatorBackend::AllowAll => Arc::new(self::allow_all::AllowAll {}),
AuthenticatorBackend::OAuth2Proxy(ref... | factory | identifier_name |
mod.rs | use std::sync::Arc;
use actix_web::HttpRequest;
use anyhow::Result;
use crate::config::AuthenticatorBackend;
use crate::config::Config;
use crate::engine::RulesEngine;
use crate::models::AuditReason;
use crate::models::AuthenticationResult;
use crate::models::AuthenticationStatus;
use crate::models::RequestContext;
u... |
// Process post-authentication rules.
let postauth = self
.rules
.eval_postauth(context, &result.authentication_context);
match postauth {
RuleAction::Allow => {
result.audit_reason = AuditReason::PostAuthAllowed;
result.status ... | {
return Ok(result);
} | conditional_block |
mod.rs | use std::sync::Arc;
use actix_web::HttpRequest;
use anyhow::Result;
use crate::config::AuthenticatorBackend;
use crate::config::Config;
use crate::engine::RulesEngine;
use crate::models::AuditReason;
use crate::models::AuthenticationResult;
use crate::models::AuthenticationStatus;
use crate::models::RequestContext;
u... |
/// Instantiate an authenticator from the given authentication proxy.
#[cfg(test)]
pub fn from<A>(authenticator: A) -> Authenticator
where
A: AuthenticationProxy +'static,
{
let headers = IdentityHeaders::default();
let rules = RulesEngine::builder().build().unwrap();
... | {
let factory: Arc<dyn AuthenticationProxyFactory> = match config.authenticator.backend {
#[cfg(debug_assertions)]
AuthenticatorBackend::AllowAll => Arc::new(self::allow_all::AllowAll {}),
AuthenticatorBackend::OAuth2Proxy(ref oauth2_proxy) => Arc::new(
self::... | identifier_body |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::error::{Fallible};
use ... |
pub fn Append_(&mut self, name: DOMString, value: DOMString) {
self.data.insert(name, StringData(value));
}
}
impl Reflectable for FormData {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector {
&mut se... | {
let blob = BlobData {
blob: value.clone(),
name: filename.unwrap_or(~"default")
};
self.data.insert(name.clone(), blob);
} | identifier_body |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::error::{Fallible};
use ... | (window: &JS<Window>, form: Option<JS<HTMLFormElement>>)
-> Fallible<JS<FormData>> {
Ok(FormData::new(form, window))
}
pub fn Append(&mut self, name: DOMString, value: &JS<Blob>, filename: Option<DOMString>) {
let blob = BlobData {
blob: value.clone(),
... | Constructor | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.