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 may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ use crate::ir::relay::ExprNode; use crate::runtime::array::Array; use crate::runtime::ObjectRef; use crate::runtime::String as TString; use tvm_macros::Object; type FuncType = ObjectRef; type AttrFieldInfo = ObjectRef; #[repr(C)] #[derive(Object)] #[ref_name = "Op"] #[type_key = "Op"] pub struct
{ 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 may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ use crate::ir::relay::ExprNode; use crate::runtime::array::Array; use crate::runtime::ObjectRef; use crate::runtime::String as TString; use tvm_macros::Object; type FuncType = ObjectRef; type AttrFieldInfo = ObjectRef; #[repr(C)] #[derive(Object)] #[ref_name = "Op"]
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, BotConfig}; use ::core::EventQueue; use ::action::{ActionHandler, ActionGroup, MessageActions}; // Action Implementation ------------------------------------------------------ pub struct Action { 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 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); if let Some(channel_name) = server.channel_name(&self.voice_channel_id)
} 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!( "Note: Audio recording has been **started** for your current voice channel {}.", channel_name ) )) } server.start_recording_voice(&self.voice_channel_id, queue); }
conditional_block
start.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Discord Dependencies ------------------------------------------------------- use discord::model::{ChannelId, ServerId}; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, BotConfig}; use ::core::EventQueue; use ::action::{ActionHandler, ActionGroup, MessageActions}; // Action Implementation ------------------------------------------------------ pub struct Action { server_id: ServerId, voice_channel_id: ChannelId, } impl Action { pub fn new( server_id: ServerId, voice_channel_id: ChannelId ) -> Box<Action>
} 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); if let Some(channel_name) = server.channel_name(&self.voice_channel_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!( "Note: Audio recording has been **started** for your current voice channel {}.", channel_name ) )) } server.start_recording_voice(&self.voice_channel_id, queue); } } actions } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[Action] [StartRecording] Server #{}", self.server_id ) } }
{ 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, BotConfig}; use ::core::EventQueue; use ::action::{ActionHandler, ActionGroup, MessageActions}; // Action Implementation ------------------------------------------------------ pub struct Action { 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 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); if let Some(channel_name) = server.channel_name(&self.voice_channel_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!( "Note: Audio recording has been **started** for your current voice channel {}.", channel_name ) )) } server.start_recording_voice(&self.voice_channel_id, queue); } } actions } }
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, BotConfig}; use ::core::EventQueue; use ::action::{ActionHandler, ActionGroup, MessageActions}; // Action Implementation ------------------------------------------------------ pub struct
{ 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 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); if let Some(channel_name) = server.channel_name(&self.voice_channel_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!( "Note: Audio recording has been **started** for your current voice channel {}.", channel_name ) )) } server.start_recording_voice(&self.voice_channel_id, queue); } } actions } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[Action] [StartRecording] Server #{}", self.server_id ) } }
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 = variable_range_generator(EXAMPLE_SEED); let mut xs = Vec::with_capacity(20); for _ in 0..20 { xs.push(range_generator.next_in_inclusive_range(a, b)) } assert_eq!(xs, expected_values); } #[test] fn test_next_in_inclusive_range() { 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, 17, 15, 10, 12, 16, 13, 15, 12, 12, 19, 15], ); next_in_inclusive_range_helper::<u8>( 0, u8::MAX, &[ 113, 239, 69, 108, 228, 210, 168, 161, 87, 32, 110, 83, 188, 34, 89, 238, 93, 200, 149, 115, ], ); } fn next_in_inclusive_range_fail_helper<T: PrimitiveUnsigned>()
#[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 = variable_range_generator(EXAMPLE_SEED); let mut xs = Vec::with_capacity(20); for _ in 0..20 { xs.push(range_generator.next_in_inclusive_range(a, b)) } assert_eq!(xs, expected_values); } #[test] fn test_next_in_inclusive_range() { 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, 17, 15, 10, 12, 16, 13, 15, 12, 12, 19, 15], ); next_in_inclusive_range_helper::<u8>( 0, u8::MAX, &[ 113, 239, 69, 108, 228, 210, 168, 161, 87, 32, 110, 83, 188, 34, 89, 238, 93, 200, 149, 115, ],
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 = variable_range_generator(EXAMPLE_SEED); let mut xs = Vec::with_capacity(20); for _ in 0..20 { xs.push(range_generator.next_in_inclusive_range(a, b)) } assert_eq!(xs, expected_values); } #[test] fn
() { 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, 17, 15, 10, 12, 16, 13, 15, 12, 12, 19, 15], ); next_in_inclusive_range_helper::<u8>( 0, u8::MAX, &[ 113, 239, 69, 108, 228, 210, 168, 161, 87, 32, 110, 83, 188, 34, 89, 238, 93, 200, 149, 115, ], ); } fn next_in_inclusive_range_fail_helper<T: PrimitiveUnsigned>() { 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); }
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 CassSession, key: &str, basic: &mut Basic) -> Result<(), CassError> { unsafe { let query = CString::new("INSERT INTO examples.basic (key, bln, flt, dbl, i32, i64) VALUES (?,?,?,?,?, \ ?);"); let statement = cass_statement_new(query.unwrap().as_ptr(), 6); cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr()); cass_statement_bind_bool(statement, 1, basic.bln.into()); cass_statement_bind_float(statement, 2, basic.flt); cass_statement_bind_double(statement, 3, basic.dbl); cass_statement_bind_int32(statement, 4, basic.i32); cass_statement_bind_int64(statement, 5, basic.i64); let future = &mut *cass_session_execute(session, statement); cass_future_wait(future); let result = match cass_future_error_code(future) { CASS_OK => Ok(()), rc =>
}; 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 = cass_statement_new(CString::new(query).unwrap().as_ptr(), 1); cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr()); let future = cass_session_execute(session, statement); cass_future_wait(future); let result = match cass_future_error_code(future) { CASS_OK => { let result = cass_future_get_result(future); let iterator = cass_iterator_from_result(result); match cass_iterator_next(iterator) { cass_true => { let row = cass_iterator_get_row(iterator); let ref mut b_bln = basic.bln; let ref mut b_dbl = basic.dbl; let ref mut b_flt = basic.flt; let ref mut b_i32 = basic.i32; let ref mut b_i64 = basic.i64; cass_value_get_bool(cass_row_get_column(row, 1), b_bln); cass_value_get_double(cass_row_get_column(row, 2), b_dbl); cass_value_get_float(cass_row_get_column(row, 3), b_flt); cass_value_get_int32(cass_row_get_column(row, 4), b_i32); cass_value_get_int64(cass_row_get_column(row, 5), b_i64); cass_statement_free(statement); cass_iterator_free(iterator); } cass_false => {} } cass_result_free(result); Ok(()) } rc => Err(rc), }; 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, i64: 2, }; match connect_session(session, cluster) { Ok(()) => { let output = &mut Basic { bln: cass_false, flt: 0f32, dbl: 0f64, i32: 0, i64: 0, }; execute_query(session, "CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': \ 'SimpleStrategy','replication_factor': '1' };") .unwrap(); execute_query(session, "CREATE TABLE IF NOT EXISTS examples.basic (key text, bln boolean, flt float, dbl \ double, i32 int, i64 bigint, PRIMARY KEY (key));") .unwrap(); insert_into_basic(session, "test", input).unwrap(); select_from_basic(session, "test", output).unwrap(); println!("{:?}", input); println!("{:?}", output); assert!(input.bln == output.bln); assert!(input.flt == output.flt); assert!(input.dbl == output.dbl); assert!(input.i32 == output.i32); assert!(input.i64 == output.i64); let close_future = cass_session_close(session); cass_future_wait(close_future); cass_future_free(close_future); } err => println!("Error: {:?}", err), } cass_cluster_free(cluster); cass_session_free(session); } }
{ 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 CassSession, key: &str, basic: &mut Basic) -> Result<(), CassError> { unsafe { let query = CString::new("INSERT INTO examples.basic (key, bln, flt, dbl, i32, i64) VALUES (?,?,?,?,?, \ ?);"); let statement = cass_statement_new(query.unwrap().as_ptr(), 6); cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr()); cass_statement_bind_bool(statement, 1, basic.bln.into()); cass_statement_bind_float(statement, 2, basic.flt); cass_statement_bind_double(statement, 3, basic.dbl); cass_statement_bind_int32(statement, 4, basic.i32); cass_statement_bind_int64(statement, 5, basic.i64); let future = &mut *cass_session_execute(session, statement); cass_future_wait(future); let result = match cass_future_error_code(future) { CASS_OK => Ok(()), rc => { print_error(future); Err(rc) } }; 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 = cass_statement_new(CString::new(query).unwrap().as_ptr(), 1); cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr()); let future = cass_session_execute(session, statement); cass_future_wait(future); let result = match cass_future_error_code(future) { CASS_OK => { let result = cass_future_get_result(future); let iterator = cass_iterator_from_result(result); match cass_iterator_next(iterator) { cass_true => { let row = cass_iterator_get_row(iterator); let ref mut b_bln = basic.bln; let ref mut b_dbl = basic.dbl; let ref mut b_flt = basic.flt; let ref mut b_i32 = basic.i32; let ref mut b_i64 = basic.i64; cass_value_get_bool(cass_row_get_column(row, 1), b_bln); cass_value_get_double(cass_row_get_column(row, 2), b_dbl); cass_value_get_float(cass_row_get_column(row, 3), b_flt); cass_value_get_int32(cass_row_get_column(row, 4), b_i32); cass_value_get_int64(cass_row_get_column(row, 5), b_i64); cass_statement_free(statement); cass_iterator_free(iterator); } cass_false => {} } cass_result_free(result); Ok(()) } rc => Err(rc), }; cass_future_free(future); result } } pub fn main()
i64: 0, }; execute_query(session, "CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': \ 'SimpleStrategy','replication_factor': '1' };") .unwrap(); execute_query(session, "CREATE TABLE IF NOT EXISTS examples.basic (key text, bln boolean, flt float, dbl \ double, i32 int, i64 bigint, PRIMARY KEY (key));") .unwrap(); insert_into_basic(session, "test", input).unwrap(); select_from_basic(session, "test", output).unwrap(); println!("{:?}", input); println!("{:?}", output); assert!(input.bln == output.bln); assert!(input.flt == output.flt); assert!(input.dbl == output.dbl); assert!(input.i32 == output.i32); assert!(input.i64 == output.i64); let close_future = cass_session_close(session); cass_future_wait(close_future); cass_future_free(close_future); } err => println!("Error: {:?}", err), } cass_cluster_free(cluster); cass_session_free(session); } }
{ 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) { Ok(()) => { let output = &mut Basic { bln: cass_false, flt: 0f32, dbl: 0f64, i32: 0,
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 CassSession, key: &str, basic: &mut Basic) -> Result<(), CassError> { unsafe { let query = CString::new("INSERT INTO examples.basic (key, bln, flt, dbl, i32, i64) VALUES (?,?,?,?,?, \ ?);"); let statement = cass_statement_new(query.unwrap().as_ptr(), 6); cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr()); cass_statement_bind_bool(statement, 1, basic.bln.into()); cass_statement_bind_float(statement, 2, basic.flt); cass_statement_bind_double(statement, 3, basic.dbl); cass_statement_bind_int32(statement, 4, basic.i32); cass_statement_bind_int64(statement, 5, basic.i64); let future = &mut *cass_session_execute(session, statement); cass_future_wait(future); let result = match cass_future_error_code(future) { CASS_OK => Ok(()), rc => { print_error(future); Err(rc) } }; cass_future_free(future); cass_statement_free(statement); result } } fn
(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).unwrap().as_ptr()); let future = cass_session_execute(session, statement); cass_future_wait(future); let result = match cass_future_error_code(future) { CASS_OK => { let result = cass_future_get_result(future); let iterator = cass_iterator_from_result(result); match cass_iterator_next(iterator) { cass_true => { let row = cass_iterator_get_row(iterator); let ref mut b_bln = basic.bln; let ref mut b_dbl = basic.dbl; let ref mut b_flt = basic.flt; let ref mut b_i32 = basic.i32; let ref mut b_i64 = basic.i64; cass_value_get_bool(cass_row_get_column(row, 1), b_bln); cass_value_get_double(cass_row_get_column(row, 2), b_dbl); cass_value_get_float(cass_row_get_column(row, 3), b_flt); cass_value_get_int32(cass_row_get_column(row, 4), b_i32); cass_value_get_int64(cass_row_get_column(row, 5), b_i64); cass_statement_free(statement); cass_iterator_free(iterator); } cass_false => {} } cass_result_free(result); Ok(()) } rc => Err(rc), }; 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, i64: 2, }; match connect_session(session, cluster) { Ok(()) => { let output = &mut Basic { bln: cass_false, flt: 0f32, dbl: 0f64, i32: 0, i64: 0, }; execute_query(session, "CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': \ 'SimpleStrategy','replication_factor': '1' };") .unwrap(); execute_query(session, "CREATE TABLE IF NOT EXISTS examples.basic (key text, bln boolean, flt float, dbl \ double, i32 int, i64 bigint, PRIMARY KEY (key));") .unwrap(); insert_into_basic(session, "test", input).unwrap(); select_from_basic(session, "test", output).unwrap(); println!("{:?}", input); println!("{:?}", output); assert!(input.bln == output.bln); assert!(input.flt == output.flt); assert!(input.dbl == output.dbl); assert!(input.i32 == output.i32); assert!(input.i64 == output.i64); let close_future = cass_session_close(session); cass_future_wait(close_future); cass_future_free(close_future); } err => println!("Error: {:?}", err), } cass_cluster_free(cluster); cass_session_free(session); } }
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 CassSession, key: &str, basic: &mut Basic) -> Result<(), CassError> { unsafe { let query = CString::new("INSERT INTO examples.basic (key, bln, flt, dbl, i32, i64) VALUES (?,?,?,?,?, \ ?);"); let statement = cass_statement_new(query.unwrap().as_ptr(), 6); cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr()); cass_statement_bind_bool(statement, 1, basic.bln.into()); cass_statement_bind_float(statement, 2, basic.flt); cass_statement_bind_double(statement, 3, basic.dbl); cass_statement_bind_int32(statement, 4, basic.i32); cass_statement_bind_int64(statement, 5, basic.i64); let future = &mut *cass_session_execute(session, statement); cass_future_wait(future); let result = match cass_future_error_code(future) { CASS_OK => Ok(()), rc => { print_error(future); Err(rc) } }; 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 = cass_statement_new(CString::new(query).unwrap().as_ptr(), 1); cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr()); let future = cass_session_execute(session, statement); cass_future_wait(future); let result = match cass_future_error_code(future) { CASS_OK => { let result = cass_future_get_result(future); let iterator = cass_iterator_from_result(result); match cass_iterator_next(iterator) { cass_true => { let row = cass_iterator_get_row(iterator); let ref mut b_bln = basic.bln; let ref mut b_dbl = basic.dbl; let ref mut b_flt = basic.flt; let ref mut b_i32 = basic.i32; let ref mut b_i64 = basic.i64; cass_value_get_bool(cass_row_get_column(row, 1), b_bln); cass_value_get_double(cass_row_get_column(row, 2), b_dbl); cass_value_get_float(cass_row_get_column(row, 3), b_flt); cass_value_get_int32(cass_row_get_column(row, 4), b_i32); cass_value_get_int64(cass_row_get_column(row, 5), b_i64); cass_statement_free(statement); cass_iterator_free(iterator); } cass_false => {} } cass_result_free(result); Ok(())
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, i64: 2, }; match connect_session(session, cluster) { Ok(()) => { let output = &mut Basic { bln: cass_false, flt: 0f32, dbl: 0f64, i32: 0, i64: 0, }; execute_query(session, "CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': \ 'SimpleStrategy','replication_factor': '1' };") .unwrap(); execute_query(session, "CREATE TABLE IF NOT EXISTS examples.basic (key text, bln boolean, flt float, dbl \ double, i32 int, i64 bigint, PRIMARY KEY (key));") .unwrap(); insert_into_basic(session, "test", input).unwrap(); select_from_basic(session, "test", output).unwrap(); println!("{:?}", input); println!("{:?}", output); assert!(input.bln == output.bln); assert!(input.flt == output.flt); assert!(input.dbl == output.dbl); assert!(input.i32 == output.i32); assert!(input.i64 == output.i64); let close_future = cass_session_close(session); cass_future_wait(close_future); cass_future_free(close_future); } err => println!("Error: {:?}", err), } cass_cluster_free(cluster); cass_session_free(session); } }
} 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::codegen::Bindings::NamedNodeMapBinding; use dom::bindings::codegen::Bindings::NamedNodeMapBinding::NamedNodeMapMethods; 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; use html5ever::LocalName; #[allow(unused_imports)] use std::ascii::AsciiExt; #[dom_struct] pub struct NamedNodeMap { reflector_: Reflector, owner: Dom<Element>, } impl NamedNodeMap { fn new_inherited(elem: &Element) -> NamedNodeMap { NamedNodeMap { reflector_: Reflector::new(), owner: Dom::from_ref(elem), } } pub fn new(window: &Window, elem: &Element) -> DomRoot<NamedNodeMap> { reflect_dom_object(Box::new(NamedNodeMap::new_inherited(elem)), window, NamedNodeMapBinding::Wrap) } } impl NamedNodeMapMethods for NamedNodeMap { // https://dom.spec.whatwg.org/#dom-namednodemap-length fn Length(&self) -> u32 { self.owner.attrs().len() as u32 } // https://dom.spec.whatwg.org/#dom-namednodemap-item fn Item(&self, index: u32) -> Option<DomRoot<Attr>> { self.owner.attrs().get(index as usize).map(|js| DomRoot::from_ref(&**js)) } // 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>, local_name: DOMString) -> Option<DomRoot<Attr>> { let ns = namespace_from_domstring(namespace); self.owner.get_attribute(&ns, &LocalName::from(local_name)) } // https://dom.spec.whatwg.org/#dom-namednodemap-setnameditem fn SetNamedItem(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> { self.owner.SetAttributeNode(attr) } // https://dom.spec.whatwg.org/#dom-namednodemap-setnameditemns fn SetNamedItemNS(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> { self.SetNamedItem(attr) } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem fn RemoveNamedItem(&self, name: DOMString) -> Fallible<DomRoot<Attr>> { let name = self.owner.parsed_name(name); self.owner.remove_attribute_by_name(&name).ok_or(Error::NotFound) } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns fn
(&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-namednodemap-item fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Attr>> { self.Item(index) } // check-tidy: no specs after this line fn NamedGetter(&self, name: DOMString) -> Option<DomRoot<Attr>> { self.GetNamedItem(name) } // https://heycam.github.io/webidl/#dfn-supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { let mut names = vec!(); let html_element_in_html_document = self.owner.html_element_in_html_document(); for attr in self.owner.attrs().iter() { let s = &**attr.name(); if html_element_in_html_document &&!s.bytes().all(|b| b.to_ascii_lowercase() == b) { continue } if!names.iter().any(|name| &*name == s) { names.push(DOMString::from(s)); } } names } }
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::codegen::Bindings::NamedNodeMapBinding; use dom::bindings::codegen::Bindings::NamedNodeMapBinding::NamedNodeMapMethods; 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; use html5ever::LocalName; #[allow(unused_imports)] use std::ascii::AsciiExt; #[dom_struct] pub struct NamedNodeMap { reflector_: Reflector, owner: Dom<Element>, } impl NamedNodeMap { fn new_inherited(elem: &Element) -> NamedNodeMap { NamedNodeMap { reflector_: Reflector::new(), owner: Dom::from_ref(elem), } } pub fn new(window: &Window, elem: &Element) -> DomRoot<NamedNodeMap> { reflect_dom_object(Box::new(NamedNodeMap::new_inherited(elem)), window, NamedNodeMapBinding::Wrap) } } impl NamedNodeMapMethods for NamedNodeMap { // https://dom.spec.whatwg.org/#dom-namednodemap-length fn Length(&self) -> u32 { self.owner.attrs().len() as u32 } // https://dom.spec.whatwg.org/#dom-namednodemap-item fn Item(&self, index: u32) -> Option<DomRoot<Attr>>
// 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>, local_name: DOMString) -> Option<DomRoot<Attr>> { let ns = namespace_from_domstring(namespace); self.owner.get_attribute(&ns, &LocalName::from(local_name)) } // https://dom.spec.whatwg.org/#dom-namednodemap-setnameditem fn SetNamedItem(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> { self.owner.SetAttributeNode(attr) } // https://dom.spec.whatwg.org/#dom-namednodemap-setnameditemns fn SetNamedItemNS(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> { self.SetNamedItem(attr) } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem fn RemoveNamedItem(&self, name: DOMString) -> Fallible<DomRoot<Attr>> { let name = self.owner.parsed_name(name); self.owner.remove_attribute_by_name(&name).ok_or(Error::NotFound) } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns fn RemoveNamedItemNS(&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-namednodemap-item fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Attr>> { self.Item(index) } // check-tidy: no specs after this line fn NamedGetter(&self, name: DOMString) -> Option<DomRoot<Attr>> { self.GetNamedItem(name) } // https://heycam.github.io/webidl/#dfn-supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { let mut names = vec!(); let html_element_in_html_document = self.owner.html_element_in_html_document(); for attr in self.owner.attrs().iter() { let s = &**attr.name(); if html_element_in_html_document &&!s.bytes().all(|b| b.to_ascii_lowercase() == b) { continue } if!names.iter().any(|name| &*name == s) { names.push(DOMString::from(s)); } } names } }
{ 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; use html5ever::LocalName; #[allow(unused_imports)] use std::ascii::AsciiExt; #[dom_struct] pub struct NamedNodeMap { reflector_: Reflector, owner: Dom<Element>, } impl NamedNodeMap { fn new_inherited(elem: &Element) -> NamedNodeMap { NamedNodeMap { reflector_: Reflector::new(), owner: Dom::from_ref(elem), } } pub fn new(window: &Window, elem: &Element) -> DomRoot<NamedNodeMap> { reflect_dom_object(Box::new(NamedNodeMap::new_inherited(elem)), window, NamedNodeMapBinding::Wrap) } } impl NamedNodeMapMethods for NamedNodeMap { // https://dom.spec.whatwg.org/#dom-namednodemap-length fn Length(&self) -> u32 { self.owner.attrs().len() as u32 } // https://dom.spec.whatwg.org/#dom-namednodemap-item fn Item(&self, index: u32) -> Option<DomRoot<Attr>> { self.owner.attrs().get(index as usize).map(|js| DomRoot::from_ref(&**js)) } // 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>, local_name: DOMString) -> Option<DomRoot<Attr>> { let ns = namespace_from_domstring(namespace); self.owner.get_attribute(&ns, &LocalName::from(local_name)) } // https://dom.spec.whatwg.org/#dom-namednodemap-setnameditem fn SetNamedItem(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> { self.owner.SetAttributeNode(attr) } // https://dom.spec.whatwg.org/#dom-namednodemap-setnameditemns fn SetNamedItemNS(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> { self.SetNamedItem(attr) } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem fn RemoveNamedItem(&self, name: DOMString) -> Fallible<DomRoot<Attr>> { let name = self.owner.parsed_name(name); self.owner.remove_attribute_by_name(&name).ok_or(Error::NotFound) } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns fn RemoveNamedItemNS(&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-namednodemap-item fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Attr>> { self.Item(index) } // check-tidy: no specs after this line fn NamedGetter(&self, name: DOMString) -> Option<DomRoot<Attr>> { self.GetNamedItem(name) } // https://heycam.github.io/webidl/#dfn-supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { let mut names = vec!(); let html_element_in_html_document = self.owner.html_element_in_html_document(); for attr in self.owner.attrs().iter() { let s = &**attr.name(); if html_element_in_html_document &&!s.bytes().all(|b| b.to_ascii_lowercase() == b) { continue } if!names.iter().any(|name| &*name == s) { names.push(DOMString::from(s)); } } names } }
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::codegen::Bindings::NamedNodeMapBinding; use dom::bindings::codegen::Bindings::NamedNodeMapBinding::NamedNodeMapMethods; 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; use html5ever::LocalName; #[allow(unused_imports)] use std::ascii::AsciiExt; #[dom_struct] pub struct NamedNodeMap { reflector_: Reflector, owner: Dom<Element>, } impl NamedNodeMap { fn new_inherited(elem: &Element) -> NamedNodeMap { NamedNodeMap { reflector_: Reflector::new(), owner: Dom::from_ref(elem), } } pub fn new(window: &Window, elem: &Element) -> DomRoot<NamedNodeMap> { reflect_dom_object(Box::new(NamedNodeMap::new_inherited(elem)), window, NamedNodeMapBinding::Wrap) } } impl NamedNodeMapMethods for NamedNodeMap { // https://dom.spec.whatwg.org/#dom-namednodemap-length fn Length(&self) -> u32 { self.owner.attrs().len() as u32 } // https://dom.spec.whatwg.org/#dom-namednodemap-item fn Item(&self, index: u32) -> Option<DomRoot<Attr>> { self.owner.attrs().get(index as usize).map(|js| DomRoot::from_ref(&**js)) } // 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>, local_name: DOMString) -> Option<DomRoot<Attr>> { let ns = namespace_from_domstring(namespace); self.owner.get_attribute(&ns, &LocalName::from(local_name)) } // https://dom.spec.whatwg.org/#dom-namednodemap-setnameditem fn SetNamedItem(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> { self.owner.SetAttributeNode(attr) } // https://dom.spec.whatwg.org/#dom-namednodemap-setnameditemns fn SetNamedItemNS(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> { self.SetNamedItem(attr) } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem fn RemoveNamedItem(&self, name: DOMString) -> Fallible<DomRoot<Attr>> { let name = self.owner.parsed_name(name); self.owner.remove_attribute_by_name(&name).ok_or(Error::NotFound) } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns fn RemoveNamedItemNS(&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-namednodemap-item fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Attr>> { self.Item(index) } // check-tidy: no specs after this line fn NamedGetter(&self, name: DOMString) -> Option<DomRoot<Attr>> { self.GetNamedItem(name) } // https://heycam.github.io/webidl/#dfn-supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { let mut names = vec!(); let html_element_in_html_document = self.owner.html_element_in_html_document(); for attr in self.owner.attrs().iter() { let s = &**attr.name(); if html_element_in_html_document &&!s.bytes().all(|b| b.to_ascii_lowercase() == b) { continue } if!names.iter().any(|name| &*name == s)
} 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_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) }
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 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: usize, } impl<'a> Serializer<'a> { fn new(state: &'a PlanetWars, offset: usize) -> Self { Serializer { state: state, player_num_offset: offset, } } fn serialize_state(&self) -> proto::State { proto::State { planets: self.state .planets .iter() .map(|planet| self.serialize_planet(planet)) .collect(), expeditions: self.state .expeditions .iter() .map(|exp| self.serialize_expedition(exp)) .collect(), } } /// Gets the player number for given player id. /// Player numbers are 1-based (as opposed to player ids), They will also be /// rotated based on the number offset for this serializer. fn player_num(&self, player_id: PlayerId) -> u64 { let num_players = self.state.players.len(); let rotated_id = (player_id.as_usize() + self.player_num_offset) % num_players; // protocol player ids start at 1 return (rotated_id + 1) as u64; } fn serialize_planet(&self, planet: &Planet) -> proto::Planet { proto::Planet { name: planet.name.clone(), x: planet.x, y: planet.y, owner: planet.owner().map(|id| self.player_num(id)), ship_count: planet.ship_count(), } } fn
(&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[exp.target].name.clone(), turns_remaining: exp.turns_remaining, } } }
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: usize, } impl<'a> Serializer<'a> { fn new(state: &'a PlanetWars, offset: usize) -> Self { Serializer { state: state, player_num_offset: offset, } } fn serialize_state(&self) -> proto::State { proto::State { planets: self.state .planets .iter() .map(|planet| self.serialize_planet(planet)) .collect(), expeditions: self.state .expeditions .iter() .map(|exp| self.serialize_expedition(exp)) .collect(), } } /// Gets the player number for given player id. /// Player numbers are 1-based (as opposed to player ids), They will also be /// rotated based on the number offset for this serializer. fn player_num(&self, player_id: PlayerId) -> u64 { let num_players = self.state.players.len(); let rotated_id = (player_id.as_usize() + self.player_num_offset) % num_players; // protocol player ids start at 1 return (rotated_id + 1) as u64; } fn serialize_planet(&self, planet: &Planet) -> proto::Planet { proto::Planet { name: planet.name.clone(), x: planet.x, y: planet.y, owner: planet.owner().map(|id| self.player_num(id)), ship_count: planet.ship_count(), } } fn serialize_expedition(&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[exp.target].name.clone(), turns_remaining: exp.turns_remaining, } } }
{ 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 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: usize, } impl<'a> Serializer<'a> { fn new(state: &'a PlanetWars, offset: usize) -> Self { Serializer { state: state, player_num_offset: offset, } } fn serialize_state(&self) -> proto::State { proto::State { planets: self.state .planets .iter() .map(|planet| self.serialize_planet(planet)) .collect(), expeditions: self.state .expeditions .iter() .map(|exp| self.serialize_expedition(exp)) .collect(), } } /// Gets the player number for given player id. /// Player numbers are 1-based (as opposed to player ids), They will also be /// rotated based on the number offset for this serializer. fn player_num(&self, player_id: PlayerId) -> u64 { let num_players = self.state.players.len(); let rotated_id = (player_id.as_usize() + self.player_num_offset) % num_players; // protocol player ids start at 1 return (rotated_id + 1) as u64; } fn serialize_planet(&self, planet: &Planet) -> proto::Planet { proto::Planet { name: planet.name.clone(), x: planet.x, y: planet.y, owner: planet.owner().map(|id| self.player_num(id)), ship_count: planet.ship_count(), } } fn serialize_expedition(&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[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, reil_translate_insn}; pub use openreil_sys::root::{reil_op_t, reil_type_t, reil_size_t, reil_arg_t, reil_raw_t}; use std::mem; use std::ops::Drop; use std::marker; /// Specifies the architecture of the binary code. /// /// As of now, supported architectures are `x86` and `ARM`. #[derive(Clone, Copy, Debug)] pub enum ReilArch { X86, ARM, } /// Callback handler type to further process the resulting REIL instructions. /// Is a type alias for a C function. /// /// Please take care to assert that neither argument is NULL. pub type ReilInstHandler<T> = extern "C" fn(*mut ReilRawInst, *mut T) -> i32; /// A raw REIL instruction, that is a simple autogenerated wrapper for the original C type. pub type ReilRawInst = reil_inst_t; /// A disassembler object. /// /// The `Reil` type provides a simple interface to disassemble and translate single or multiple instructions /// to the OpenREIL intermediate language. /// /// A `handler` callback function can be provided during construction to further process the resulting REIL instructions. pub struct Reil<'a, T: 'a> { reil_handle: reil_t, _marker: marker::PhantomData<&'a mut T>, } impl<'a, T: 'a> Reil<'a, T> { /// 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 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_handler_t = unsafe { mem::transmute(handler) }; let c_ptr = context as *mut _; let reil = unsafe { reil_init(arch, handler, c_ptr as *mut libc::c_void) }; if reil.is_null() { return None; } let new_reil = Reil { reil_handle: reil, _marker: marker::PhantomData, }; Some(new_reil) } /// Translate the binary data given in `data` to REIL instructions, /// `start_address` designates the starting address the decoded instructions get assigned. pub fn 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 instruction from the binary data given in `data` and start addressing at the given address. pub fn translate_instruction(&mut self, data: &mut [u8], start_address: u32) { unsafe { reil_translate_insn( self.reil_handle, start_address as reil_addr_t, data.as_mut_ptr(), data.len() as libc::c_int, ); } } } impl<'a, T: 'a> Drop for Reil<'a, T> { fn drop(&mut self) { unsafe { reil_close(self.reil_handle); } } } pub trait ReilInst { fn address(&self) -> u64; fn reil_offset(&self) -> u8; fn raw_address(&self) -> u64; fn print(&self); fn first_operand(&self) -> Option<reil_arg_t>; fn second_operand(&self) -> Option<reil_arg_t>; fn third_operand(&self) -> Option<reil_arg_t>; fn opcode(&self) -> reil_op_t; fn mnemonic(&self) -> Option<String>; } impl ReilInst for reil_inst_t { fn address(&self) -> u64 { let raw_addr = self.raw_address() << 8; let reil_offset = self.reil_offset() as u64; raw_addr | reil_offset } fn reil_offset(&self) -> u8 { self.inum as u8 } fn raw_address(&self) -> u64 { self.raw_info.addr as u64 } fn print(&self) { let mut_ptr: *mut reil_inst_t = unsafe { mem::transmute(self) }; unsafe { reil_inst_print(mut_ptr); } } fn first_operand(&self) -> Option<reil_arg_t> { match self.a.type_ { reil_type_t::A_NONE => None, _ => Some(self.a) } } fn second_operand(&self) -> Option<reil_arg_t>
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; let mnem = raw_info.str_mnem as *const libc::c_schar; let op = raw_info.str_op as *const libc::c_schar; if mnem.is_null() || op.is_null() { return None; } let mut mnem_bytes = Vec::new(); unsafe { for i in 0.. { if *mnem.offset(i) == 0 { break } 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); } } String::from_utf8(mnem_bytes).ok() } } pub trait ReilArg { fn arg_type(&self) -> reil_type_t; fn size(&self) -> reil_size_t; fn val(&self) -> Option<u64>; fn name(&self) -> Option<String>; fn inum(&self) -> u64; } impl ReilArg for reil_arg_t { fn arg_type(&self) -> reil_type_t { self.type_ } fn size(&self) -> reil_size_t { self.size } fn val(&self) -> Option<u64> { match self.arg_type() { reil_type_t::A_CONST | reil_type_t::A_LOC => Some(self.val as u64), _ => None, } } fn name(&self) -> Option<String> { if self.arg_type() == reil_type_t::A_NONE { return None; } let chars = self.name.iter() .take_while(|&b| *b as u8!= 0) .map(|&b| b as u8) .collect(); String::from_utf8(chars).ok() } fn inum(&self) -> u64 { self.inum as u64 } }
{ 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, reil_translate_insn}; pub use openreil_sys::root::{reil_op_t, reil_type_t, reil_size_t, reil_arg_t, reil_raw_t}; use std::mem; use std::ops::Drop; use std::marker; /// Specifies the architecture of the binary code. /// /// As of now, supported architectures are `x86` and `ARM`. #[derive(Clone, Copy, Debug)] pub enum ReilArch { X86, ARM, } /// Callback handler type to further process the resulting REIL instructions. /// Is a type alias for a C function. /// /// Please take care to assert that neither argument is NULL. pub type ReilInstHandler<T> = extern "C" fn(*mut ReilRawInst, *mut T) -> i32; /// A raw REIL instruction, that is a simple autogenerated wrapper for the original C type. pub type ReilRawInst = reil_inst_t; /// A disassembler object. /// /// The `Reil` type provides a simple interface to disassemble and translate single or multiple instructions /// to the OpenREIL intermediate language. /// /// A `handler` callback function can be provided during construction to further process the resulting REIL instructions. pub struct Reil<'a, T: 'a> { reil_handle: reil_t, _marker: marker::PhantomData<&'a mut T>, } impl<'a, T: 'a> Reil<'a, T> { /// 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 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_handler_t = unsafe { mem::transmute(handler) }; let c_ptr = context as *mut _; let reil = unsafe { reil_init(arch, handler, c_ptr as *mut libc::c_void) }; if reil.is_null() { return None; } let new_reil = Reil { reil_handle: reil, _marker: marker::PhantomData, }; Some(new_reil) } /// Translate the binary data given in `data` to REIL instructions, /// `start_address` designates the starting address the decoded instructions get assigned. pub fn
(&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 instruction from the binary data given in `data` and start addressing at the given address. pub fn translate_instruction(&mut self, data: &mut [u8], start_address: u32) { unsafe { reil_translate_insn( self.reil_handle, start_address as reil_addr_t, data.as_mut_ptr(), data.len() as libc::c_int, ); } } } impl<'a, T: 'a> Drop for Reil<'a, T> { fn drop(&mut self) { unsafe { reil_close(self.reil_handle); } } } pub trait ReilInst { fn address(&self) -> u64; fn reil_offset(&self) -> u8; fn raw_address(&self) -> u64; fn print(&self); fn first_operand(&self) -> Option<reil_arg_t>; fn second_operand(&self) -> Option<reil_arg_t>; fn third_operand(&self) -> Option<reil_arg_t>; fn opcode(&self) -> reil_op_t; fn mnemonic(&self) -> Option<String>; } impl ReilInst for reil_inst_t { fn address(&self) -> u64 { let raw_addr = self.raw_address() << 8; let reil_offset = self.reil_offset() as u64; raw_addr | reil_offset } fn reil_offset(&self) -> u8 { self.inum as u8 } fn raw_address(&self) -> u64 { self.raw_info.addr as u64 } fn print(&self) { let mut_ptr: *mut reil_inst_t = unsafe { mem::transmute(self) }; unsafe { reil_inst_print(mut_ptr); } } fn first_operand(&self) -> Option<reil_arg_t> { match self.a.type_ { reil_type_t::A_NONE => None, _ => Some(self.a) } } fn second_operand(&self) -> Option<reil_arg_t> { match self.b.type_ { reil_type_t::A_NONE => None, _ => Some(self.b) } } 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; let mnem = raw_info.str_mnem as *const libc::c_schar; let op = raw_info.str_op as *const libc::c_schar; if mnem.is_null() || op.is_null() { return None; } let mut mnem_bytes = Vec::new(); unsafe { for i in 0.. { if *mnem.offset(i) == 0 { break } 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); } } String::from_utf8(mnem_bytes).ok() } } pub trait ReilArg { fn arg_type(&self) -> reil_type_t; fn size(&self) -> reil_size_t; fn val(&self) -> Option<u64>; fn name(&self) -> Option<String>; fn inum(&self) -> u64; } impl ReilArg for reil_arg_t { fn arg_type(&self) -> reil_type_t { self.type_ } fn size(&self) -> reil_size_t { self.size } fn val(&self) -> Option<u64> { match self.arg_type() { reil_type_t::A_CONST | reil_type_t::A_LOC => Some(self.val as u64), _ => None, } } fn name(&self) -> Option<String> { if self.arg_type() == reil_type_t::A_NONE { return None; } let chars = self.name.iter() .take_while(|&b| *b as u8!= 0) .map(|&b| b as u8) .collect(); String::from_utf8(chars).ok() } fn inum(&self) -> u64 { self.inum as u64 } }
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, reil_translate_insn}; pub use openreil_sys::root::{reil_op_t, reil_type_t, reil_size_t, reil_arg_t, reil_raw_t}; use std::mem; use std::ops::Drop; use std::marker; /// Specifies the architecture of the binary code. /// /// As of now, supported architectures are `x86` and `ARM`. #[derive(Clone, Copy, Debug)] pub enum ReilArch { X86, ARM, } /// Callback handler type to further process the resulting REIL instructions. /// Is a type alias for a C function. /// /// Please take care to assert that neither argument is NULL. pub type ReilInstHandler<T> = extern "C" fn(*mut ReilRawInst, *mut T) -> i32; /// A raw REIL instruction, that is a simple autogenerated wrapper for the original C type. pub type ReilRawInst = reil_inst_t; /// A disassembler object. /// /// The `Reil` type provides a simple interface to disassemble and translate single or multiple instructions /// to the OpenREIL intermediate language. /// /// A `handler` callback function can be provided during construction to further process the resulting REIL instructions. pub struct Reil<'a, T: 'a> { reil_handle: reil_t, _marker: marker::PhantomData<&'a mut T>, } impl<'a, T: 'a> Reil<'a, T> {
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_handler_t = unsafe { mem::transmute(handler) }; let c_ptr = context as *mut _; let reil = unsafe { reil_init(arch, handler, c_ptr as *mut libc::c_void) }; if reil.is_null() { return None; } let new_reil = Reil { reil_handle: reil, _marker: marker::PhantomData, }; Some(new_reil) } /// Translate the binary data given in `data` to REIL instructions, /// `start_address` designates the starting address the decoded instructions get assigned. pub fn 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 instruction from the binary data given in `data` and start addressing at the given address. pub fn translate_instruction(&mut self, data: &mut [u8], start_address: u32) { unsafe { reil_translate_insn( self.reil_handle, start_address as reil_addr_t, data.as_mut_ptr(), data.len() as libc::c_int, ); } } } impl<'a, T: 'a> Drop for Reil<'a, T> { fn drop(&mut self) { unsafe { reil_close(self.reil_handle); } } } pub trait ReilInst { fn address(&self) -> u64; fn reil_offset(&self) -> u8; fn raw_address(&self) -> u64; fn print(&self); fn first_operand(&self) -> Option<reil_arg_t>; fn second_operand(&self) -> Option<reil_arg_t>; fn third_operand(&self) -> Option<reil_arg_t>; fn opcode(&self) -> reil_op_t; fn mnemonic(&self) -> Option<String>; } impl ReilInst for reil_inst_t { fn address(&self) -> u64 { let raw_addr = self.raw_address() << 8; let reil_offset = self.reil_offset() as u64; raw_addr | reil_offset } fn reil_offset(&self) -> u8 { self.inum as u8 } fn raw_address(&self) -> u64 { self.raw_info.addr as u64 } fn print(&self) { let mut_ptr: *mut reil_inst_t = unsafe { mem::transmute(self) }; unsafe { reil_inst_print(mut_ptr); } } fn first_operand(&self) -> Option<reil_arg_t> { match self.a.type_ { reil_type_t::A_NONE => None, _ => Some(self.a) } } fn second_operand(&self) -> Option<reil_arg_t> { match self.b.type_ { reil_type_t::A_NONE => None, _ => Some(self.b) } } 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; let mnem = raw_info.str_mnem as *const libc::c_schar; let op = raw_info.str_op as *const libc::c_schar; if mnem.is_null() || op.is_null() { return None; } let mut mnem_bytes = Vec::new(); unsafe { for i in 0.. { if *mnem.offset(i) == 0 { break } 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); } } String::from_utf8(mnem_bytes).ok() } } pub trait ReilArg { fn arg_type(&self) -> reil_type_t; fn size(&self) -> reil_size_t; fn val(&self) -> Option<u64>; fn name(&self) -> Option<String>; fn inum(&self) -> u64; } impl ReilArg for reil_arg_t { fn arg_type(&self) -> reil_type_t { self.type_ } fn size(&self) -> reil_size_t { self.size } fn val(&self) -> Option<u64> { match self.arg_type() { reil_type_t::A_CONST | reil_type_t::A_LOC => Some(self.val as u64), _ => None, } } fn name(&self) -> Option<String> { if self.arg_type() == reil_type_t::A_NONE { return None; } let chars = self.name.iter() .take_while(|&b| *b as u8!= 0) .map(|&b| b as u8) .collect(); String::from_utf8(chars).ok() } fn inum(&self) -> u64 { self.inum as u64 } }
/// 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, reil_translate_insn}; pub use openreil_sys::root::{reil_op_t, reil_type_t, reil_size_t, reil_arg_t, reil_raw_t}; use std::mem; use std::ops::Drop; use std::marker; /// Specifies the architecture of the binary code. /// /// As of now, supported architectures are `x86` and `ARM`. #[derive(Clone, Copy, Debug)] pub enum ReilArch { X86, ARM, } /// Callback handler type to further process the resulting REIL instructions. /// Is a type alias for a C function. /// /// Please take care to assert that neither argument is NULL. pub type ReilInstHandler<T> = extern "C" fn(*mut ReilRawInst, *mut T) -> i32; /// A raw REIL instruction, that is a simple autogenerated wrapper for the original C type. pub type ReilRawInst = reil_inst_t; /// A disassembler object. /// /// The `Reil` type provides a simple interface to disassemble and translate single or multiple instructions /// to the OpenREIL intermediate language. /// /// A `handler` callback function can be provided during construction to further process the resulting REIL instructions. pub struct Reil<'a, T: 'a> { reil_handle: reil_t, _marker: marker::PhantomData<&'a mut T>, } impl<'a, T: 'a> Reil<'a, T> { /// 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 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_handler_t = unsafe { mem::transmute(handler) }; let c_ptr = context as *mut _; let reil = unsafe { reil_init(arch, handler, c_ptr as *mut libc::c_void) }; if reil.is_null() { return None; } let new_reil = Reil { reil_handle: reil, _marker: marker::PhantomData, }; Some(new_reil) } /// Translate the binary data given in `data` to REIL instructions, /// `start_address` designates the starting address the decoded instructions get assigned. pub fn 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 instruction from the binary data given in `data` and start addressing at the given address. pub fn translate_instruction(&mut self, data: &mut [u8], start_address: u32) { unsafe { reil_translate_insn( self.reil_handle, start_address as reil_addr_t, data.as_mut_ptr(), data.len() as libc::c_int, ); } } } impl<'a, T: 'a> Drop for Reil<'a, T> { fn drop(&mut self) { unsafe { reil_close(self.reil_handle); } } } pub trait ReilInst { fn address(&self) -> u64; fn reil_offset(&self) -> u8; fn raw_address(&self) -> u64; fn print(&self); fn first_operand(&self) -> Option<reil_arg_t>; fn second_operand(&self) -> Option<reil_arg_t>; fn third_operand(&self) -> Option<reil_arg_t>; fn opcode(&self) -> reil_op_t; fn mnemonic(&self) -> Option<String>; } impl ReilInst for reil_inst_t { fn address(&self) -> u64 { let raw_addr = self.raw_address() << 8; let reil_offset = self.reil_offset() as u64; raw_addr | reil_offset } fn reil_offset(&self) -> u8 { self.inum as u8 } fn raw_address(&self) -> u64 { self.raw_info.addr as u64 } fn print(&self) { let mut_ptr: *mut reil_inst_t = unsafe { mem::transmute(self) }; unsafe { reil_inst_print(mut_ptr); } } fn first_operand(&self) -> Option<reil_arg_t> { match self.a.type_ { reil_type_t::A_NONE => None, _ => Some(self.a) } } fn second_operand(&self) -> Option<reil_arg_t> { match self.b.type_ { reil_type_t::A_NONE => None, _ => Some(self.b) } } 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; let mnem = raw_info.str_mnem as *const libc::c_schar; let op = raw_info.str_op as *const libc::c_schar; if mnem.is_null() || op.is_null() { return None; } let mut mnem_bytes = Vec::new(); unsafe { for i in 0.. { if *mnem.offset(i) == 0
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); } } String::from_utf8(mnem_bytes).ok() } } pub trait ReilArg { fn arg_type(&self) -> reil_type_t; fn size(&self) -> reil_size_t; fn val(&self) -> Option<u64>; fn name(&self) -> Option<String>; fn inum(&self) -> u64; } impl ReilArg for reil_arg_t { fn arg_type(&self) -> reil_type_t { self.type_ } fn size(&self) -> reil_size_t { self.size } fn val(&self) -> Option<u64> { match self.arg_type() { reil_type_t::A_CONST | reil_type_t::A_LOC => Some(self.val as u64), _ => None, } } fn name(&self) -> Option<String> { if self.arg_type() == reil_type_t::A_NONE { return None; } let chars = self.name.iter() .take_while(|&b| *b as u8!= 0) .map(|&b| b as u8) .collect(); String::from_utf8(chars).ok() } fn inum(&self) -> u64 { self.inum as u64 } }
{ 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, /// A boolean value Boolean(bool), /// An integral number value Integer(IntegerType), /// A floating-point number value Float(FloatType), /// A string of text String(Rc<String>), } impl Clone for Value { fn clone(&self) -> Self { use Value::*; match self { Nil => Nil, Boolean(v) => Boolean(*v), Integer(v) => Integer(*v), Float(v) => Float(*v), String(v) => String(v.clone()), } } } 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 == b, _ => false, } } } impl Eq for Value {} impl Hash for Value { fn hash<H: Hasher>(&self, state: &mut H) { use Value::*; match self { Nil => {} Boolean(v) => v.hash(state), Integer(v) => v.hash(state), Float(v) => v.to_bits().hash(state), String(v) => v.hash(state), } } } impl PartialOrd for Value { fn partial_cmp(&self, other: &Value) -> Option<Ordering> { use Value::*; match (self, other) { (Integer(a), Integer(b)) => a.partial_cmp(b), (Integer(a), Float(b)) => (*a as FloatType).partial_cmp(b), (Float(a), Integer(b)) => a.partial_cmp(&(*b as FloatType)), (Float(a), Float(b)) => a.partial_cmp(b), (a, b) if a == b => Some(Ordering::Equal), _ => None, } } } impl Display for Value { fn fmt(&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 escape_string(text: &str) -> String { let mut string = String::with_capacity(text.len() + 2); string.push('"'); for ch in text.chars() { if ch == '\\' { string.push_str("\\\\"); } else if ch == '"' { string.push_str("\\\""); } else if ch.is_ascii_graphic() || ch.is_alphabetic() { string.push(ch); } else {
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("\\\\"), 0x22 => string.push_str("\\\""), code if code <= 0xff => string.push_str(&format!("\\x{:02x}", code)), code if code <= 0xffff => string.push_str(&format!("\\u{:04x}", code)), code => string.push_str(&format!("\\U{:08x}", code)), } } } string.push('"'); string }
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, /// A boolean value Boolean(bool), /// An integral number value Integer(IntegerType), /// A floating-point number value Float(FloatType), /// A string of text String(Rc<String>), } impl Clone for Value { fn clone(&self) -> Self { use Value::*; match self { Nil => Nil, Boolean(v) => Boolean(*v), Integer(v) => Integer(*v), Float(v) => Float(*v), String(v) => String(v.clone()), } } } 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 == b, _ => false, } } } impl Eq for Value {} impl Hash for Value { fn hash<H: Hasher>(&self, state: &mut H) { use Value::*; match self { Nil => {} Boolean(v) => v.hash(state), Integer(v) => v.hash(state), Float(v) => v.to_bits().hash(state), String(v) => v.hash(state), } } } impl PartialOrd for Value { fn partial_cmp(&self, other: &Value) -> Option<Ordering> { use Value::*; match (self, other) { (Integer(a), Integer(b)) => a.partial_cmp(b), (Integer(a), Float(b)) => (*a as FloatType).partial_cmp(b), (Float(a), Integer(b)) => a.partial_cmp(&(*b as FloatType)), (Float(a), Float(b)) => a.partial_cmp(b), (a, b) if a == b => Some(Ordering::Equal), _ => None, } } } impl Display for Value { fn
(&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 escape_string(text: &str) -> String { let mut string = String::with_capacity(text.len() + 2); string.push('"'); for ch in text.chars() { if ch == '\\' { string.push_str("\\\\"); } else if ch == '"' { string.push_str("\\\""); } else if ch.is_ascii_graphic() || ch.is_alphabetic() { string.push(ch); } else { match ch as u32 { 0x20 => string.push(' '), 0x00 => string.push_str("\\0"), 0x07 => string.push_str("\\a"), 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("\\\\"), 0x22 => string.push_str("\\\""), code if code <= 0xff => string.push_str(&format!("\\x{:02x}", code)), code if code <= 0xffff => string.push_str(&format!("\\u{:04x}", code)), code => string.push_str(&format!("\\U{:08x}", code)), } } } string.push('"'); string }
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, /// A boolean value Boolean(bool), /// An integral number value Integer(IntegerType), /// A floating-point number value Float(FloatType), /// A string of text String(Rc<String>), } impl Clone for Value { fn clone(&self) -> Self
} 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 == b, _ => false, } } } impl Eq for Value {} impl Hash for Value { fn hash<H: Hasher>(&self, state: &mut H) { use Value::*; match self { Nil => {} Boolean(v) => v.hash(state), Integer(v) => v.hash(state), Float(v) => v.to_bits().hash(state), String(v) => v.hash(state), } } } impl PartialOrd for Value { fn partial_cmp(&self, other: &Value) -> Option<Ordering> { use Value::*; match (self, other) { (Integer(a), Integer(b)) => a.partial_cmp(b), (Integer(a), Float(b)) => (*a as FloatType).partial_cmp(b), (Float(a), Integer(b)) => a.partial_cmp(&(*b as FloatType)), (Float(a), Float(b)) => a.partial_cmp(b), (a, b) if a == b => Some(Ordering::Equal), _ => None, } } } impl Display for Value { fn fmt(&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 escape_string(text: &str) -> String { let mut string = String::with_capacity(text.len() + 2); string.push('"'); for ch in text.chars() { if ch == '\\' { string.push_str("\\\\"); } else if ch == '"' { string.push_str("\\\""); } else if ch.is_ascii_graphic() || ch.is_alphabetic() { string.push(ch); } else { match ch as u32 { 0x20 => string.push(' '), 0x00 => string.push_str("\\0"), 0x07 => string.push_str("\\a"), 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("\\\\"), 0x22 => string.push_str("\\\""), code if code <= 0xff => string.push_str(&format!("\\x{:02x}", code)), code if code <= 0xffff => string.push_str(&format!("\\u{:04x}", code)), code => string.push_str(&format!("\\U{:08x}", code)), } } } string.push('"'); string }
{ 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 = 10; /// Scheduler for the kernel. Manages scheduling of tasks and timers pub struct Scheduler { inactive_tasks: LinkedList<Task>, active_task: Option<Task>, task_count: u32, last_resched: usize, need_resched: bool, bh_manager: Arc<BottomHalfManager>, } impl Scheduler { /// Creates a new scheduler /// /// The currently active task is created along with a single, currently `WAITING`, task of /// priority `IRQ`. pub fn new(memory_manager: &mut MemoryManager) -> Scheduler { let mut inactive_tasks = LinkedList::new(); // Create the kernel bottom_half IRQ processing thread let stack = memory_manager.allocate_stack(); inactive_tasks.push_front(Task::new( TID_BOTTOMHALFD, stack, bottom_half::execute, TaskPriority::IRQ, TaskStatus::WAITING, )); Scheduler { inactive_tasks: inactive_tasks, active_task: Some(Task::default(TID_SYSTEMIDLE)), task_count: 2, last_resched: 0, need_resched: false, bh_manager: Arc::new(BottomHalfManager::new()), } } /// Create a new task to be scheduled. pub fn new_task(&mut self, memory_manager: &mut MemoryManager, func: fn()) { let stack = memory_manager.allocate_stack(); self.inactive_tasks.push_front(Task::new( self.task_count, stack, func, TaskPriority::NORMAL, TaskStatus::READY, )); self.task_count += 1; } /// Schedule the next task. /// /// Choses the next task with status!= `TaskStatus::COMPLETED` and switches its context with /// that of the currently active task. pub fn schedule(&mut self, active_ctx: &mut TaskContext) { // Optimization - return early if nothing to do if self.inactive_tasks.len() == 0 { return; } // First look for active high priority tasks first, if none of these exist then look for // normal priority tasks. There is guaranteed to always be at least one NORMAL priority // task so it is safe to call unwrap. let new_task = match self.next_task(TaskPriority::IRQ) { Some(t) => t, None => { if let Some(ref t) = self.active_task { // The active task is an interrupt handler that hasn't yet completed, let it // run to completion. if t.get_priority() == TaskPriority::IRQ && t.get_status() == TaskStatus::READY { return; } } // 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 save it old_task.set_context(active_ctx); *active_ctx = *new_task.get_context(); // Update the schedulers internal references and store the initial task back into the // inactive_tasks list if it is not yet finished. By not restoring COMPLETED tasks here // we force cleanup of COMPLETED tasks. self.active_task = Some(new_task); if old_task.get_status()!= TaskStatus::COMPLETED { self.inactive_tasks.push_back(old_task); } // Update the last_resched time self.update_last_resched(); } /// Get a mutable reference to the current active task. pub fn get_active_task_mut(&mut self) -> Option<&mut Task> { self.active_task.as_mut() } /// Returns true if a reschedule is needed /// /// Returns true if the last reschedule was over `THREAD_QUANTUM` cpu ticks ago. pub fn need_resched(&self) -> bool { if self.need_resched { return true; } let clock = unsafe { &mut *kget().clock.get() }; let now = clock.now(); (now - self.last_resched) > THREAD_QUANTUM } /// Returns an Arc pointer to the bh_fifo pub fn bh_manager(&self) -> Arc<BottomHalfManager> { self.bh_manager.clone() } /// Set the status of task with `id` pub fn set_task_status(&mut self, id: u32, status: TaskStatus) { 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; } } } /// Set the internal 'need_resched' flag to true pub fn
(&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 the next task with priority matching `priority` fn next_task(&mut self, priority: TaskPriority) -> Option<Task> { let mut i = 0; let mut found = false; for ref t in self.inactive_tasks.iter() { if t.get_priority()!= priority || t.get_status()!= TaskStatus::READY { // On to the next, this is not suitable i += 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(); // Merge the lists loop { match remainder.pop_front() { Some(t) => self.inactive_tasks.push_back(t), None => break, } } next_task } else { None } } }
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 = 10; /// Scheduler for the kernel. Manages scheduling of tasks and timers pub struct Scheduler { inactive_tasks: LinkedList<Task>, active_task: Option<Task>, task_count: u32, last_resched: usize, need_resched: bool, bh_manager: Arc<BottomHalfManager>, } impl Scheduler { /// Creates a new scheduler /// /// The currently active task is created along with a single, currently `WAITING`, task of /// priority `IRQ`. pub fn new(memory_manager: &mut MemoryManager) -> Scheduler { let mut inactive_tasks = LinkedList::new(); // Create the kernel bottom_half IRQ processing thread let stack = memory_manager.allocate_stack(); inactive_tasks.push_front(Task::new( TID_BOTTOMHALFD, stack, bottom_half::execute, TaskPriority::IRQ, TaskStatus::WAITING, )); Scheduler { inactive_tasks: inactive_tasks, active_task: Some(Task::default(TID_SYSTEMIDLE)), task_count: 2, last_resched: 0, need_resched: false, bh_manager: Arc::new(BottomHalfManager::new()), } } /// Create a new task to be scheduled. pub fn new_task(&mut self, memory_manager: &mut MemoryManager, func: fn()) { let stack = memory_manager.allocate_stack(); self.inactive_tasks.push_front(Task::new( self.task_count, stack, func, TaskPriority::NORMAL, TaskStatus::READY, )); self.task_count += 1; } /// Schedule the next task. /// /// Choses the next task with status!= `TaskStatus::COMPLETED` and switches its context with /// that of the currently active task. pub fn schedule(&mut self, active_ctx: &mut TaskContext) { // Optimization - return early if nothing to do if self.inactive_tasks.len() == 0 { return; } // First look for active high priority tasks first, if none of these exist then look for // normal priority tasks. There is guaranteed to always be at least one NORMAL priority // task so it is safe to call unwrap. let new_task = match self.next_task(TaskPriority::IRQ) { Some(t) => t, None => { if let Some(ref t) = self.active_task { // The active task is an interrupt handler that hasn't yet completed, let it // run to completion.
} } // 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 save it old_task.set_context(active_ctx); *active_ctx = *new_task.get_context(); // Update the schedulers internal references and store the initial task back into the // inactive_tasks list if it is not yet finished. By not restoring COMPLETED tasks here // we force cleanup of COMPLETED tasks. self.active_task = Some(new_task); if old_task.get_status()!= TaskStatus::COMPLETED { self.inactive_tasks.push_back(old_task); } // Update the last_resched time self.update_last_resched(); } /// Get a mutable reference to the current active task. pub fn get_active_task_mut(&mut self) -> Option<&mut Task> { self.active_task.as_mut() } /// Returns true if a reschedule is needed /// /// Returns true if the last reschedule was over `THREAD_QUANTUM` cpu ticks ago. pub fn need_resched(&self) -> bool { if self.need_resched { return true; } let clock = unsafe { &mut *kget().clock.get() }; let now = clock.now(); (now - self.last_resched) > THREAD_QUANTUM } /// Returns an Arc pointer to the bh_fifo pub fn bh_manager(&self) -> Arc<BottomHalfManager> { self.bh_manager.clone() } /// Set the status of task with `id` pub fn set_task_status(&mut self, id: u32, status: TaskStatus) { 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; } } } /// 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.last_resched = clock.now(); self.need_resched = false; } /// Find the next task with priority matching `priority` fn next_task(&mut self, priority: TaskPriority) -> Option<Task> { let mut i = 0; let mut found = false; for ref t in self.inactive_tasks.iter() { if t.get_priority()!= priority || t.get_status()!= TaskStatus::READY { // On to the next, this is not suitable i += 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(); // Merge the lists loop { match remainder.pop_front() { Some(t) => self.inactive_tasks.push_back(t), None => break, } } next_task } else { None } } }
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 = 10; /// Scheduler for the kernel. Manages scheduling of tasks and timers pub struct Scheduler { inactive_tasks: LinkedList<Task>, active_task: Option<Task>, task_count: u32, last_resched: usize, need_resched: bool, bh_manager: Arc<BottomHalfManager>, } impl Scheduler { /// Creates a new scheduler /// /// The currently active task is created along with a single, currently `WAITING`, task of /// priority `IRQ`. pub fn new(memory_manager: &mut MemoryManager) -> Scheduler { let mut inactive_tasks = LinkedList::new(); // Create the kernel bottom_half IRQ processing thread let stack = memory_manager.allocate_stack(); inactive_tasks.push_front(Task::new( TID_BOTTOMHALFD, stack, bottom_half::execute, TaskPriority::IRQ, TaskStatus::WAITING, )); Scheduler { inactive_tasks: inactive_tasks, active_task: Some(Task::default(TID_SYSTEMIDLE)), task_count: 2, last_resched: 0, need_resched: false, bh_manager: Arc::new(BottomHalfManager::new()), } } /// Create a new task to be scheduled. pub fn new_task(&mut self, memory_manager: &mut MemoryManager, func: fn()) { let stack = memory_manager.allocate_stack(); self.inactive_tasks.push_front(Task::new( self.task_count, stack, func, TaskPriority::NORMAL, TaskStatus::READY, )); self.task_count += 1; } /// Schedule the next task. /// /// Choses the next task with status!= `TaskStatus::COMPLETED` and switches its context with /// that of the currently active task. pub fn schedule(&mut self, active_ctx: &mut TaskContext) { // Optimization - return early if nothing to do if self.inactive_tasks.len() == 0 { return; } // First look for active high priority tasks first, if none of these exist then look for // normal priority tasks. There is guaranteed to always be at least one NORMAL priority // task so it is safe to call unwrap. let new_task = match self.next_task(TaskPriority::IRQ) { Some(t) => t, None => { if let Some(ref t) = self.active_task { // The active task is an interrupt handler that hasn't yet completed, let it // run to completion. if t.get_priority() == TaskPriority::IRQ && t.get_status() == TaskStatus::READY { return; } } // 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 save it old_task.set_context(active_ctx); *active_ctx = *new_task.get_context(); // Update the schedulers internal references and store the initial task back into the // inactive_tasks list if it is not yet finished. By not restoring COMPLETED tasks here // we force cleanup of COMPLETED tasks. self.active_task = Some(new_task); if old_task.get_status()!= TaskStatus::COMPLETED { self.inactive_tasks.push_back(old_task); } // Update the last_resched time self.update_last_resched(); } /// Get a mutable reference to the current active task. pub fn get_active_task_mut(&mut self) -> Option<&mut Task> { self.active_task.as_mut() } /// Returns true if a reschedule is needed /// /// Returns true if the last reschedule was over `THREAD_QUANTUM` cpu ticks ago. pub fn need_resched(&self) -> bool { if self.need_resched { return true; } let clock = unsafe { &mut *kget().clock.get() }; let now = clock.now(); (now - self.last_resched) > THREAD_QUANTUM } /// Returns an Arc pointer to the bh_fifo pub fn bh_manager(&self) -> Arc<BottomHalfManager> { self.bh_manager.clone() } /// Set the status of task with `id` pub fn set_task_status(&mut self, id: u32, status: TaskStatus) { 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; } } } /// 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.last_resched = clock.now(); self.need_resched = false; } /// Find the next task with priority matching `priority` fn next_task(&mut self, priority: TaskPriority) -> Option<Task> { let mut i = 0; let mut found = false; for ref t in self.inactive_tasks.iter() { if t.get_priority()!= priority || t.get_status()!= TaskStatus::READY
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(); // Merge the lists loop { match remainder.pop_front() { Some(t) => self.inactive_tasks.push_back(t), None => break, } } next_task } else { None } } }
{ // 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 = 10; /// Scheduler for the kernel. Manages scheduling of tasks and timers pub struct Scheduler { inactive_tasks: LinkedList<Task>, active_task: Option<Task>, task_count: u32, last_resched: usize, need_resched: bool, bh_manager: Arc<BottomHalfManager>, } impl Scheduler { /// Creates a new scheduler /// /// The currently active task is created along with a single, currently `WAITING`, task of /// priority `IRQ`. pub fn new(memory_manager: &mut MemoryManager) -> Scheduler { let mut inactive_tasks = LinkedList::new(); // Create the kernel bottom_half IRQ processing thread let stack = memory_manager.allocate_stack(); inactive_tasks.push_front(Task::new( TID_BOTTOMHALFD, stack, bottom_half::execute, TaskPriority::IRQ, TaskStatus::WAITING, )); Scheduler { inactive_tasks: inactive_tasks, active_task: Some(Task::default(TID_SYSTEMIDLE)), task_count: 2, last_resched: 0, need_resched: false, bh_manager: Arc::new(BottomHalfManager::new()), } } /// Create a new task to be scheduled. pub fn new_task(&mut self, memory_manager: &mut MemoryManager, func: fn()) { let stack = memory_manager.allocate_stack(); self.inactive_tasks.push_front(Task::new( self.task_count, stack, func, TaskPriority::NORMAL, TaskStatus::READY, )); self.task_count += 1; } /// Schedule the next task. /// /// Choses the next task with status!= `TaskStatus::COMPLETED` and switches its context with /// that of the currently active task. pub fn schedule(&mut self, active_ctx: &mut TaskContext) { // Optimization - return early if nothing to do if self.inactive_tasks.len() == 0 { return; } // First look for active high priority tasks first, if none of these exist then look for // normal priority tasks. There is guaranteed to always be at least one NORMAL priority // task so it is safe to call unwrap. let new_task = match self.next_task(TaskPriority::IRQ) { Some(t) => t, None => { if let Some(ref t) = self.active_task { // The active task is an interrupt handler that hasn't yet completed, let it // run to completion. if t.get_priority() == TaskPriority::IRQ && t.get_status() == TaskStatus::READY { return; } } // 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 save it old_task.set_context(active_ctx); *active_ctx = *new_task.get_context(); // Update the schedulers internal references and store the initial task back into the // inactive_tasks list if it is not yet finished. By not restoring COMPLETED tasks here // we force cleanup of COMPLETED tasks. self.active_task = Some(new_task); if old_task.get_status()!= TaskStatus::COMPLETED { self.inactive_tasks.push_back(old_task); } // Update the last_resched time self.update_last_resched(); } /// Get a mutable reference to the current active task. pub fn get_active_task_mut(&mut self) -> Option<&mut Task> { self.active_task.as_mut() } /// Returns true if a reschedule is needed /// /// Returns true if the last reschedule was over `THREAD_QUANTUM` cpu ticks ago. pub fn need_resched(&self) -> bool { if self.need_resched { return true; } let clock = unsafe { &mut *kget().clock.get() }; let now = clock.now(); (now - self.last_resched) > THREAD_QUANTUM } /// Returns an Arc pointer to the bh_fifo pub fn bh_manager(&self) -> Arc<BottomHalfManager> { self.bh_manager.clone() } /// Set the status of task with `id` pub fn set_task_status(&mut self, id: u32, status: TaskStatus)
/// 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.last_resched = clock.now(); self.need_resched = false; } /// Find the next task with priority matching `priority` fn next_task(&mut self, priority: TaskPriority) -> Option<Task> { let mut i = 0; let mut found = false; for ref t in self.inactive_tasks.iter() { if t.get_priority()!= priority || t.get_status()!= TaskStatus::READY { // On to the next, this is not suitable i += 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(); // Merge the lists loop { match remainder.pop_front() { Some(t) => self.inactive_tasks.push_back(t), None => break, } } next_task } else { None } } }
{ 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_user = login(&*token).unwrap(); assert_eq!(logged_in_user, "Michael Yang"); }
{ // 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); token.signed(b"secret_key", Sha256::new()).ok() }
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::default(); let claims = Registered { iss: Some("mikkyang.com".into()), sub: Some(user_id.into()), ..Default::default() }; let token = Token::new(header, claims); token.signed(b"secret_key", Sha256::new()).ok() } fn
(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 = login(&*token).unwrap(); assert_eq!(logged_in_user, "Michael Yang"); }
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::default(); let claims = Registered { iss: Some("mikkyang.com".into()), sub: Some(user_id.into()), ..Default::default() }; let token = Token::new(header, claims); token.signed(b"secret_key", Sha256::new()).ok() }
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_user = login(&*token).unwrap(); assert_eq!(logged_in_user, "Michael Yang"); }
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::default(); let claims = Registered { iss: Some("mikkyang.com".into()), sub: Some(user_id.into()), ..Default::default() }; let token = Token::new(header, claims); token.signed(b"secret_key", Sha256::new()).ok() } fn login(token: &str) -> Option<String> { let token = Token::<Header, Registered>::parse(token).unwrap(); if token.verify(b"secret_key", Sha256::new())
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}; use cranelift_faerie::FaerieProduct; use faerie::{Artifact, Decl, Link}; use failure::{format_err, Error, ResultExt}; use lucet_module::{ FunctionSpec, SerializedModule, VersionInfo, LUCET_MODULE_SYM, MODULE_DATA_SYM, }; use std::collections::HashMap; use std::fs::File; use std::io::{Cursor, Write}; use std::path::Path; use target_lexicon::BinaryFormat; pub struct CraneliftFuncs { funcs: HashMap<Name, ir::Function>, isa: Box<dyn isa::TargetIsa>, }
/// 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_function(&mut buffer, func, &Some(self.isa.as_ref()).into()) .context(format_err!("writing func {:?}", n))? } let mut file = File::create(path)?; file.write_all(buffer.as_bytes())?; Ok(()) } } pub struct ObjectFile { artifact: Artifact, } impl ObjectFile { pub fn new( mut product: FaerieProduct, module_data_len: usize, mut function_manifest: Vec<(String, FunctionSpec)>, table_manifest: Vec<Name>, ) -> Result<Self, Error> { stack_probe::declare_and_define(&mut product)?; // stack_probe::declare_and_define never exists as clif, and as a result never exists a // cranelift-compiled function. As a result, the declared length of the stack probe's // "code" is 0. This is incorrect, and must be fixed up before writing out the function // manifest. // because the stack probe is the last declared function... let last_idx = function_manifest.len() - 1; let stack_probe_entry = function_manifest .get_mut(last_idx) .expect("function manifest has entries"); debug_assert!(stack_probe_entry.0 == stack_probe::STACK_PROBE_SYM); debug_assert!(stack_probe_entry.1.code_len() == 0); std::mem::swap( &mut stack_probe_entry.1, &mut FunctionSpec::new( 0, // there is no real address for the function until written to an object file stack_probe::STACK_PROBE_BINARY.len() as u32, 0, 0, // fix up this FunctionSpec with trap info like any other ), ); let trap_manifest = &product .trap_manifest .expect("trap manifest will be present"); // Now that we have trap information, we can fix up FunctionSpec entries to have // correct `trap_length` values let mut function_map: HashMap<String, u32> = HashMap::new(); for (i, (name, _)) in function_manifest.iter().enumerate() { function_map.insert(name.clone(), i as u32); } for sink in trap_manifest.sinks.iter() { if let Some(idx) = function_map.get(&sink.name) { let (_, fn_spec) = &mut function_manifest .get_mut(*idx as usize) .expect("index is valid"); std::mem::replace::<FunctionSpec>( fn_spec, FunctionSpec::new(0, fn_spec.code_len(), 0, sink.sites.len() as u64), ); } else { Err(format_err!("Inconsistent state: trap records present for function {} but the function does not exist?", sink.name)) .context(LucetcErrorKind::TranslatingModule)?; } } write_trap_tables(trap_manifest, &mut product.artifact)?; write_function_manifest(function_manifest.as_slice(), &mut product.artifact)?; link_tables(table_manifest.as_slice(), &mut product.artifact)?; // And now write out the actual structure tying together all the data in this module. write_module( module_data_len, table_manifest.len(), function_manifest.len(), &mut product.artifact, )?; Ok(Self { artifact: product.artifact, }) } pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> { let _ = path.as_ref().file_name().ok_or(format_err!( "path {:?} needs to have filename", path.as_ref() )); let file = File::create(path)?; self.artifact.write(file)?; Ok(()) } } fn write_module( module_data_len: usize, table_manifest_len: usize, function_manifest_len: usize, obj: &mut Artifact, ) -> Result<(), Error> { 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")).as_bytes()); version.write_to(&mut native_data)?; write_relocated_slice( obj, &mut native_data, LUCET_MODULE_SYM, Some(MODULE_DATA_SYM), module_data_len as u64, )?; write_relocated_slice( obj, &mut native_data, 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_inner()) .context(format!("defining {}", LUCET_MODULE_SYM))?; Ok(()) } pub(crate) fn write_relocated_slice( obj: &mut Artifact, buf: &mut Cursor<Vec<u8>>, from: &str, to: Option<&str>, len: u64, ) -> Result<(), Error> { match (to, len) { (Some(to), 0) => { // This is an imported slice of unknown size let absolute_reloc = match obj.target.binary_format { BinaryFormat::Elf => faerie::artifact::Reloc::Raw { reloc: goblin::elf::reloc::R_X86_64_64, addend: 0, }, BinaryFormat::Macho => faerie::artifact::Reloc::Raw { reloc: goblin::mach::relocation::X86_64_RELOC_UNSIGNED as u32, addend: 0, }, _ => panic!("Unsupported target format!"), }; obj.link_with( Link { from, to, at: buf.position(), }, absolute_reloc, ) .context(format!("linking {} into function manifest", to))?; } (Some(to), _len) => { // This is a local buffer of known size obj.link(Link { from, // the data at `from` + `at` (eg. FUNCTION_MANIFEST_SYM) to, // is a reference to `to` (eg. fn_name) at: buf.position(), }) .context(format!("linking {} into function manifest", to))?; } (None, len) => { // There's actually no relocation to add, because there's no slice to put here. // // Since there's no slice, its length must be zero. assert!( len == 0, "Invalid slice: no data, but there are more than zero bytes of it" ); } } buf.write_u64::<LittleEndian>(0).unwrap(); buf.write_u64::<LittleEndian>(len).unwrap(); Ok(()) }
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}; use cranelift_faerie::FaerieProduct; use faerie::{Artifact, Decl, Link}; use failure::{format_err, Error, ResultExt}; use lucet_module::{ FunctionSpec, SerializedModule, VersionInfo, LUCET_MODULE_SYM, MODULE_DATA_SYM, }; use std::collections::HashMap; use std::fs::File; use std::io::{Cursor, Write}; use std::path::Path; use target_lexicon::BinaryFormat; pub struct
{ 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<(), 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_function(&mut buffer, func, &Some(self.isa.as_ref()).into()) .context(format_err!("writing func {:?}", n))? } let mut file = File::create(path)?; file.write_all(buffer.as_bytes())?; Ok(()) } } pub struct ObjectFile { artifact: Artifact, } impl ObjectFile { pub fn new( mut product: FaerieProduct, module_data_len: usize, mut function_manifest: Vec<(String, FunctionSpec)>, table_manifest: Vec<Name>, ) -> Result<Self, Error> { stack_probe::declare_and_define(&mut product)?; // stack_probe::declare_and_define never exists as clif, and as a result never exists a // cranelift-compiled function. As a result, the declared length of the stack probe's // "code" is 0. This is incorrect, and must be fixed up before writing out the function // manifest. // because the stack probe is the last declared function... let last_idx = function_manifest.len() - 1; let stack_probe_entry = function_manifest .get_mut(last_idx) .expect("function manifest has entries"); debug_assert!(stack_probe_entry.0 == stack_probe::STACK_PROBE_SYM); debug_assert!(stack_probe_entry.1.code_len() == 0); std::mem::swap( &mut stack_probe_entry.1, &mut FunctionSpec::new( 0, // there is no real address for the function until written to an object file stack_probe::STACK_PROBE_BINARY.len() as u32, 0, 0, // fix up this FunctionSpec with trap info like any other ), ); let trap_manifest = &product .trap_manifest .expect("trap manifest will be present"); // Now that we have trap information, we can fix up FunctionSpec entries to have // correct `trap_length` values let mut function_map: HashMap<String, u32> = HashMap::new(); for (i, (name, _)) in function_manifest.iter().enumerate() { function_map.insert(name.clone(), i as u32); } for sink in trap_manifest.sinks.iter() { if let Some(idx) = function_map.get(&sink.name) { let (_, fn_spec) = &mut function_manifest .get_mut(*idx as usize) .expect("index is valid"); std::mem::replace::<FunctionSpec>( fn_spec, FunctionSpec::new(0, fn_spec.code_len(), 0, sink.sites.len() as u64), ); } else { Err(format_err!("Inconsistent state: trap records present for function {} but the function does not exist?", sink.name)) .context(LucetcErrorKind::TranslatingModule)?; } } write_trap_tables(trap_manifest, &mut product.artifact)?; write_function_manifest(function_manifest.as_slice(), &mut product.artifact)?; link_tables(table_manifest.as_slice(), &mut product.artifact)?; // And now write out the actual structure tying together all the data in this module. write_module( module_data_len, table_manifest.len(), function_manifest.len(), &mut product.artifact, )?; Ok(Self { artifact: product.artifact, }) } pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> { let _ = path.as_ref().file_name().ok_or(format_err!( "path {:?} needs to have filename", path.as_ref() )); let file = File::create(path)?; self.artifact.write(file)?; Ok(()) } } fn write_module( module_data_len: usize, table_manifest_len: usize, function_manifest_len: usize, obj: &mut Artifact, ) -> Result<(), Error> { 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")).as_bytes()); version.write_to(&mut native_data)?; write_relocated_slice( obj, &mut native_data, LUCET_MODULE_SYM, Some(MODULE_DATA_SYM), module_data_len as u64, )?; write_relocated_slice( obj, &mut native_data, 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_inner()) .context(format!("defining {}", LUCET_MODULE_SYM))?; Ok(()) } pub(crate) fn write_relocated_slice( obj: &mut Artifact, buf: &mut Cursor<Vec<u8>>, from: &str, to: Option<&str>, len: u64, ) -> Result<(), Error> { match (to, len) { (Some(to), 0) => { // This is an imported slice of unknown size let absolute_reloc = match obj.target.binary_format { BinaryFormat::Elf => faerie::artifact::Reloc::Raw { reloc: goblin::elf::reloc::R_X86_64_64, addend: 0, }, BinaryFormat::Macho => faerie::artifact::Reloc::Raw { reloc: goblin::mach::relocation::X86_64_RELOC_UNSIGNED as u32, addend: 0, }, _ => panic!("Unsupported target format!"), }; obj.link_with( Link { from, to, at: buf.position(), }, absolute_reloc, ) .context(format!("linking {} into function manifest", to))?; } (Some(to), _len) => { // This is a local buffer of known size obj.link(Link { from, // the data at `from` + `at` (eg. FUNCTION_MANIFEST_SYM) to, // is a reference to `to` (eg. fn_name) at: buf.position(), }) .context(format!("linking {} into function manifest", to))?; } (None, len) => { // There's actually no relocation to add, because there's no slice to put here. // // Since there's no slice, its length must be zero. assert!( len == 0, "Invalid slice: no data, but there are more than zero bytes of it" ); } } buf.write_u64::<LittleEndian>(0).unwrap(); buf.write_u64::<LittleEndian>(len).unwrap(); Ok(()) }
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}; use cranelift_faerie::FaerieProduct; use faerie::{Artifact, Decl, Link}; use failure::{format_err, Error, ResultExt}; use lucet_module::{ FunctionSpec, SerializedModule, VersionInfo, LUCET_MODULE_SYM, MODULE_DATA_SYM, }; use std::collections::HashMap; use std::fs::File; use std::io::{Cursor, Write}; use std::path::Path; use target_lexicon::BinaryFormat; pub struct CraneliftFuncs { 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<(), 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_function(&mut buffer, func, &Some(self.isa.as_ref()).into()) .context(format_err!("writing func {:?}", n))? } let mut file = File::create(path)?; file.write_all(buffer.as_bytes())?; Ok(()) } } pub struct ObjectFile { artifact: Artifact, } impl ObjectFile { pub fn new( mut product: FaerieProduct, module_data_len: usize, mut function_manifest: Vec<(String, FunctionSpec)>, table_manifest: Vec<Name>, ) -> Result<Self, Error> { stack_probe::declare_and_define(&mut product)?; // stack_probe::declare_and_define never exists as clif, and as a result never exists a // cranelift-compiled function. As a result, the declared length of the stack probe's // "code" is 0. This is incorrect, and must be fixed up before writing out the function // manifest. // because the stack probe is the last declared function... let last_idx = function_manifest.len() - 1; let stack_probe_entry = function_manifest .get_mut(last_idx) .expect("function manifest has entries"); debug_assert!(stack_probe_entry.0 == stack_probe::STACK_PROBE_SYM); debug_assert!(stack_probe_entry.1.code_len() == 0); std::mem::swap( &mut stack_probe_entry.1, &mut FunctionSpec::new( 0, // there is no real address for the function until written to an object file stack_probe::STACK_PROBE_BINARY.len() as u32, 0, 0, // fix up this FunctionSpec with trap info like any other ), ); let trap_manifest = &product .trap_manifest .expect("trap manifest will be present"); // Now that we have trap information, we can fix up FunctionSpec entries to have // correct `trap_length` values let mut function_map: HashMap<String, u32> = HashMap::new(); for (i, (name, _)) in function_manifest.iter().enumerate() { function_map.insert(name.clone(), i as u32); } for sink in trap_manifest.sinks.iter() { if let Some(idx) = function_map.get(&sink.name) { let (_, fn_spec) = &mut function_manifest .get_mut(*idx as usize) .expect("index is valid"); std::mem::replace::<FunctionSpec>( fn_spec, FunctionSpec::new(0, fn_spec.code_len(), 0, sink.sites.len() as u64), ); } else { Err(format_err!("Inconsistent state: trap records present for function {} but the function does not exist?", sink.name)) .context(LucetcErrorKind::TranslatingModule)?; } } write_trap_tables(trap_manifest, &mut product.artifact)?; write_function_manifest(function_manifest.as_slice(), &mut product.artifact)?; link_tables(table_manifest.as_slice(), &mut product.artifact)?; // And now write out the actual structure tying together all the data in this module. write_module( module_data_len, table_manifest.len(), function_manifest.len(), &mut product.artifact, )?; Ok(Self { artifact: product.artifact, }) } pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> { let _ = path.as_ref().file_name().ok_or(format_err!( "path {:?} needs to have filename", path.as_ref() )); let file = File::create(path)?; self.artifact.write(file)?; Ok(()) } } fn write_module( module_data_len: usize, table_manifest_len: usize, function_manifest_len: usize, obj: &mut Artifact, ) -> Result<(), Error>
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_inner()) .context(format!("defining {}", LUCET_MODULE_SYM))?; Ok(()) } pub(crate) fn write_relocated_slice( obj: &mut Artifact, buf: &mut Cursor<Vec<u8>>, from: &str, to: Option<&str>, len: u64, ) -> Result<(), Error> { match (to, len) { (Some(to), 0) => { // This is an imported slice of unknown size let absolute_reloc = match obj.target.binary_format { BinaryFormat::Elf => faerie::artifact::Reloc::Raw { reloc: goblin::elf::reloc::R_X86_64_64, addend: 0, }, BinaryFormat::Macho => faerie::artifact::Reloc::Raw { reloc: goblin::mach::relocation::X86_64_RELOC_UNSIGNED as u32, addend: 0, }, _ => panic!("Unsupported target format!"), }; obj.link_with( Link { from, to, at: buf.position(), }, absolute_reloc, ) .context(format!("linking {} into function manifest", to))?; } (Some(to), _len) => { // This is a local buffer of known size obj.link(Link { from, // the data at `from` + `at` (eg. FUNCTION_MANIFEST_SYM) to, // is a reference to `to` (eg. fn_name) at: buf.position(), }) .context(format!("linking {} into function manifest", to))?; } (None, len) => { // There's actually no relocation to add, because there's no slice to put here. // // Since there's no slice, its length must be zero. assert!( len == 0, "Invalid slice: no data, but there are more than zero bytes of it" ); } } buf.write_u64::<LittleEndian>(0).unwrap(); buf.write_u64::<LittleEndian>(len).unwrap(); Ok(()) }
{ 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")).as_bytes()); version.write_to(&mut native_data)?; write_relocated_slice( obj, &mut native_data, LUCET_MODULE_SYM, Some(MODULE_DATA_SYM), module_data_len as u64, )?; write_relocated_slice( obj, &mut native_data,
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_bytes()); let flush = stream.flush(); loop { let mut stream_reader = BufReader::new(&stream); //~^ ERROR the trait bound `&T: std::io::Read` is not satisfied [E0277] //~| HELP consider removing the leading `&`-reference //~| HELP consider changing this borrow's mutability stream_reader.read_until(b'\n', &mut buffer).expect("Reading into buffer failed"); //~^ ERROR the method `read_until` exists for struct `BufReader<&T>`, } } fn main()
{}
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_bytes()); let flush = stream.flush(); loop { let mut stream_reader = BufReader::new(&stream); //~^ ERROR the trait bound `&T: std::io::Read` is not satisfied [E0277] //~| HELP consider removing the leading `&`-reference //~| HELP consider changing this borrow's mutability stream_reader.read_until(b'\n', &mut buffer).expect("Reading into buffer failed"); //~^ ERROR the method `read_until` exists for struct `BufReader<&T>`, } } fn
() {}
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_bytes()); let flush = stream.flush(); loop { let mut stream_reader = BufReader::new(&stream); //~^ ERROR the trait bound `&T: std::io::Read` is not satisfied [E0277] //~| HELP consider removing the leading `&`-reference //~| HELP consider changing this borrow's mutability stream_reader.read_until(b'\n', &mut buffer).expect("Reading into buffer failed"); //~^ ERROR the method `read_until` exists for struct `BufReader<&T>`,
} 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(Pin<Box<dyn Future<Output = ()> + Send + Sync>>); #[derive(Clone)] pub(crate) struct Watch { rx: watch::Receiver<()>, } pin_project! { #[allow(missing_debug_implementations)] pub struct Watching<F, FN> { #[pin] future: F, state: State<FN>, watch: Pin<Box<dyn Future<Output = ()> + Send + Sync>>, _rx: watch::Receiver<()>, } } enum State<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<'_>) -> Poll<Self::Output> { Pin::new(&mut self.as_mut().0).poll(cx) } } impl Watch { pub(crate) fn watch<F, FN>(self, future: F, on_drain: FN) -> Watching<F, FN> where F: Future, FN: FnOnce(Pin<&mut F>), { let Self { mut rx } = self; let _rx = rx.clone(); Watching { future, state: State::Watch(on_drain), watch: Box::pin(async move { let _ = rx.changed().await; }), // Keep the receiver alive until the future completes, so that // dropping it can signal that draining has completed. _rx, } } } impl<F, FN> Future for Watching<F, FN> where F: Future, FN: FnOnce(Pin<&mut F>), { type Output = F::Output; fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { let mut me = self.project(); loop { match mem::replace(me.state, State::Draining) { State::Watch(on_drain) => { match Pin::new(&mut me.watch).poll(cx) { Poll::Ready(()) => { // Drain has been triggered! on_drain(me.future.as_mut()); } Poll::Pending => { *me.state = State::Watch(on_drain); return me.future.poll(cx); } } } State::Draining => return me.future.poll(cx), } } } } #[cfg(test)] mod tests { use super::*; struct TestMe { draining: bool, finished: bool, poll_cnt: usize,
} 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 } } } #[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_cnt: 0, }; let mut watch = rx.watch(fut, |mut fut| { fut.draining = true; }); assert_eq!(watch.future.poll_cnt, 0); // First poll should poll the inner future assert!(Pin::new(&mut watch).poll(cx).is_pending()); assert_eq!(watch.future.poll_cnt, 1); // Second poll should poll the inner future again assert!(Pin::new(&mut watch).poll(cx).is_pending()); assert_eq!(watch.future.poll_cnt, 2); let mut draining = tx.drain(); // Drain signaled, but needs another poll to be noticed. assert!(!watch.future.draining); assert_eq!(watch.future.poll_cnt, 2); // Now, poll after drain has been signaled. assert!(Pin::new(&mut watch).poll(cx).is_pending()); assert_eq!(watch.future.poll_cnt, 3); assert!(watch.future.draining); // Draining is not ready until watcher completes assert!(Pin::new(&mut draining).poll(cx).is_pending()); // Finishing up the watch future watch.future.finished = true; assert!(Pin::new(&mut watch).poll(cx).is_ready()); assert_eq!(watch.future.poll_cnt, 4); drop(watch); assert!(Pin::new(&mut draining).poll(cx).is_ready()); }) } #[test] fn watch_clones() { let mut mock = tokio_test::task::spawn(()); mock.enter(|cx, _| { let (tx, rx) = channel(); let fut1 = TestMe { draining: false, finished: false, poll_cnt: 0, }; let fut2 = TestMe { draining: false, finished: false, poll_cnt: 0, }; let watch1 = rx.clone().watch(fut1, |mut fut| { fut.draining = true; }); let watch2 = rx.watch(fut2, |mut fut| { fut.draining = true; }); let mut draining = tx.drain(); // Still 2 outstanding watchers assert!(Pin::new(&mut draining).poll(cx).is_pending()); // drop 1 for whatever reason drop(watch1); // Still not ready, 1 other watcher still pending assert!(Pin::new(&mut draining).poll(cx).is_pending()); drop(watch2); // Now all watchers are gone, draining is complete assert!(Pin::new(&mut draining).poll(cx).is_ready()); }); } }
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(Pin<Box<dyn Future<Output = ()> + Send + Sync>>); #[derive(Clone)] pub(crate) struct Watch { rx: watch::Receiver<()>, } pin_project! { #[allow(missing_debug_implementations)] pub struct Watching<F, FN> { #[pin] future: F, state: State<FN>, watch: Pin<Box<dyn Future<Output = ()> + Send + Sync>>, _rx: watch::Receiver<()>, } } enum State<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<'_>) -> Poll<Self::Output> { Pin::new(&mut self.as_mut().0).poll(cx) } } impl Watch { pub(crate) fn watch<F, FN>(self, future: F, on_drain: FN) -> Watching<F, FN> where F: Future, FN: FnOnce(Pin<&mut F>), { let Self { mut rx } = self; let _rx = rx.clone(); Watching { future, state: State::Watch(on_drain), watch: Box::pin(async move { let _ = rx.changed().await; }), // Keep the receiver alive until the future completes, so that // dropping it can signal that draining has completed. _rx, } } } impl<F, FN> Future for Watching<F, FN> where F: Future, FN: FnOnce(Pin<&mut F>), { type Output = F::Output; fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { let mut me = self.project(); loop { match mem::replace(me.state, State::Draining) { State::Watch(on_drain) => { match Pin::new(&mut me.watch).poll(cx) { Poll::Ready(()) => { // Drain has been triggered! on_drain(me.future.as_mut()); } Poll::Pending => { *me.state = State::Watch(on_drain); return me.future.poll(cx); } } } State::Draining => return me.future.poll(cx), } } } } #[cfg(test)] mod tests { use super::*; struct TestMe { draining: bool, finished: bool, poll_cnt: usize, } 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
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_cnt: 0, }; let mut watch = rx.watch(fut, |mut fut| { fut.draining = true; }); assert_eq!(watch.future.poll_cnt, 0); // First poll should poll the inner future assert!(Pin::new(&mut watch).poll(cx).is_pending()); assert_eq!(watch.future.poll_cnt, 1); // Second poll should poll the inner future again assert!(Pin::new(&mut watch).poll(cx).is_pending()); assert_eq!(watch.future.poll_cnt, 2); let mut draining = tx.drain(); // Drain signaled, but needs another poll to be noticed. assert!(!watch.future.draining); assert_eq!(watch.future.poll_cnt, 2); // Now, poll after drain has been signaled. assert!(Pin::new(&mut watch).poll(cx).is_pending()); assert_eq!(watch.future.poll_cnt, 3); assert!(watch.future.draining); // Draining is not ready until watcher completes assert!(Pin::new(&mut draining).poll(cx).is_pending()); // Finishing up the watch future watch.future.finished = true; assert!(Pin::new(&mut watch).poll(cx).is_ready()); assert_eq!(watch.future.poll_cnt, 4); drop(watch); assert!(Pin::new(&mut draining).poll(cx).is_ready()); }) } #[test] fn watch_clones() { let mut mock = tokio_test::task::spawn(()); mock.enter(|cx, _| { let (tx, rx) = channel(); let fut1 = TestMe { draining: false, finished: false, poll_cnt: 0, }; let fut2 = TestMe { draining: false, finished: false, poll_cnt: 0, }; let watch1 = rx.clone().watch(fut1, |mut fut| { fut.draining = true; }); let watch2 = rx.watch(fut2, |mut fut| { fut.draining = true; }); let mut draining = tx.drain(); // Still 2 outstanding watchers assert!(Pin::new(&mut draining).poll(cx).is_pending()); // drop 1 for whatever reason drop(watch1); // Still not ready, 1 other watcher still pending assert!(Pin::new(&mut draining).poll(cx).is_pending()); drop(watch2); // Now all watchers are gone, draining is complete assert!(Pin::new(&mut draining).poll(cx).is_ready()); }); } }
{ 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(Pin<Box<dyn Future<Output = ()> + Send + Sync>>); #[derive(Clone)] pub(crate) struct Watch { rx: watch::Receiver<()>, } pin_project! { #[allow(missing_debug_implementations)] pub struct Watching<F, FN> { #[pin] future: F, state: State<FN>, watch: Pin<Box<dyn Future<Output = ()> + Send + Sync>>, _rx: watch::Receiver<()>, } } enum
<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<'_>) -> Poll<Self::Output> { Pin::new(&mut self.as_mut().0).poll(cx) } } impl Watch { pub(crate) fn watch<F, FN>(self, future: F, on_drain: FN) -> Watching<F, FN> where F: Future, FN: FnOnce(Pin<&mut F>), { let Self { mut rx } = self; let _rx = rx.clone(); Watching { future, state: State::Watch(on_drain), watch: Box::pin(async move { let _ = rx.changed().await; }), // Keep the receiver alive until the future completes, so that // dropping it can signal that draining has completed. _rx, } } } impl<F, FN> Future for Watching<F, FN> where F: Future, FN: FnOnce(Pin<&mut F>), { type Output = F::Output; fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { let mut me = self.project(); loop { match mem::replace(me.state, State::Draining) { State::Watch(on_drain) => { match Pin::new(&mut me.watch).poll(cx) { Poll::Ready(()) => { // Drain has been triggered! on_drain(me.future.as_mut()); } Poll::Pending => { *me.state = State::Watch(on_drain); return me.future.poll(cx); } } } State::Draining => return me.future.poll(cx), } } } } #[cfg(test)] mod tests { use super::*; struct TestMe { draining: bool, finished: bool, poll_cnt: usize, } 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 } } } #[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_cnt: 0, }; let mut watch = rx.watch(fut, |mut fut| { fut.draining = true; }); assert_eq!(watch.future.poll_cnt, 0); // First poll should poll the inner future assert!(Pin::new(&mut watch).poll(cx).is_pending()); assert_eq!(watch.future.poll_cnt, 1); // Second poll should poll the inner future again assert!(Pin::new(&mut watch).poll(cx).is_pending()); assert_eq!(watch.future.poll_cnt, 2); let mut draining = tx.drain(); // Drain signaled, but needs another poll to be noticed. assert!(!watch.future.draining); assert_eq!(watch.future.poll_cnt, 2); // Now, poll after drain has been signaled. assert!(Pin::new(&mut watch).poll(cx).is_pending()); assert_eq!(watch.future.poll_cnt, 3); assert!(watch.future.draining); // Draining is not ready until watcher completes assert!(Pin::new(&mut draining).poll(cx).is_pending()); // Finishing up the watch future watch.future.finished = true; assert!(Pin::new(&mut watch).poll(cx).is_ready()); assert_eq!(watch.future.poll_cnt, 4); drop(watch); assert!(Pin::new(&mut draining).poll(cx).is_ready()); }) } #[test] fn watch_clones() { let mut mock = tokio_test::task::spawn(()); mock.enter(|cx, _| { let (tx, rx) = channel(); let fut1 = TestMe { draining: false, finished: false, poll_cnt: 0, }; let fut2 = TestMe { draining: false, finished: false, poll_cnt: 0, }; let watch1 = rx.clone().watch(fut1, |mut fut| { fut.draining = true; }); let watch2 = rx.watch(fut2, |mut fut| { fut.draining = true; }); let mut draining = tx.drain(); // Still 2 outstanding watchers assert!(Pin::new(&mut draining).poll(cx).is_pending()); // drop 1 for whatever reason drop(watch1); // Still not ready, 1 other watcher still pending assert!(Pin::new(&mut draining).poll(cx).is_pending()); drop(watch2); // Now all watchers are gone, draining is complete assert!(Pin::new(&mut draining).poll(cx).is_ready()); }); } }
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>; } #[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; impl Graph for MyGraph { type Node = Node; type Edge = Edge; fn has_edge( &self, _n1: &Node, _n2: &Node ) -> bool
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; impl Graph for MyGraph { type Node = Node; type Edge = Edge; fn has_edge( &self, _n1: &Node, _n2: &Node ) -> bool { true } 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>>; }
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>; } #[allow(dead_code)] fn
<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: &Node, _n2: &Node ) -> bool { true } 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>>; }
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 reason, //! native serde support was removed from rust-protobuf. //! //! This crate is an example how to inject serde annotations into generated code. //! //! Annotations are configured from `build.rs`. use std::fmt::Formatter; use std::marker::PhantomData; use protobuf::EnumFull; use protobuf::EnumOrUnknown; include!(concat!(env!("OUT_DIR"), "/protos/mod.rs")); fn serialize_enum_or_unknown<E: EnumFull, S: serde::Serializer>( e: &Option<EnumOrUnknown<E>>, s: S, ) -> Result<S::Ok, S::Error> { if let Some(e) = e { match e.enum_value() { Ok(v) => s.serialize_str(v.descriptor().name()), Err(v) => s.serialize_i32(v), } } else { s.serialize_unit() } } 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<EnumOrUnknown<E>>; fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { write!(formatter, "a string, an integer or none") } fn visit_str<R>(self, v: &str) -> Result<Self::Value, R> where R: serde::de::Error, { 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 ))),
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(PhantomData)) } #[cfg(test)] mod test { use crate::customize_example::Fruit; use crate::customize_example::Shape; #[test] fn test() { let mut fruit = Fruit::new(); fruit.set_name("Orange".to_owned()); fruit.set_weight(1.5); fruit.set_shape(Shape::CIRCLE); // Serde works. // Note rust-protobuf has built in support for JSON, // which follows protobuf-JSON serialization more correctly than default serde-json. // This example here is for the demonstration of generation of custom derives. let json = serde_json::to_string(&fruit).unwrap(); assert_eq!( "{\"name\":\"Orange\",\"weight\":1.5,\"shape\":\"CIRCLE\"}", json ); // TODO: add deserialization test } }
} } 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 reason, //! native serde support was removed from rust-protobuf. //! //! This crate is an example how to inject serde annotations into generated code. //! //! Annotations are configured from `build.rs`. use std::fmt::Formatter; use std::marker::PhantomData; use protobuf::EnumFull; use protobuf::EnumOrUnknown; include!(concat!(env!("OUT_DIR"), "/protos/mod.rs")); fn serialize_enum_or_unknown<E: EnumFull, S: serde::Serializer>( e: &Option<EnumOrUnknown<E>>, s: S, ) -> Result<S::Ok, S::Error> { if let Some(e) = e { match e.enum_value() { Ok(v) => s.serialize_str(v.descriptor().name()), Err(v) => s.serialize_i32(v), } } else { s.serialize_unit() } } 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<EnumOrUnknown<E>>; fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { write!(formatter, "a string, an integer or none") } fn visit_str<R>(self, v: &str) -> Result<Self::Value, R> where R: serde::de::Error,
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) } } d.deserialize_any(DeserializeEnumVisitor(PhantomData)) } #[cfg(test)] mod test { use crate::customize_example::Fruit; use crate::customize_example::Shape; #[test] fn test() { let mut fruit = Fruit::new(); fruit.set_name("Orange".to_owned()); fruit.set_weight(1.5); fruit.set_shape(Shape::CIRCLE); // Serde works. // Note rust-protobuf has built in support for JSON, // which follows protobuf-JSON serialization more correctly than default serde-json. // This example here is for the demonstration of generation of custom derives. let json = serde_json::to_string(&fruit).unwrap(); assert_eq!( "{\"name\":\"Orange\",\"weight\":1.5,\"shape\":\"CIRCLE\"}", json ); // TODO: add deserialization test } }
{ 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 reason, //! native serde support was removed from rust-protobuf. //! //! This crate is an example how to inject serde annotations into generated code. //! //! Annotations are configured from `build.rs`. use std::fmt::Formatter; use std::marker::PhantomData; use protobuf::EnumFull; use protobuf::EnumOrUnknown; include!(concat!(env!("OUT_DIR"), "/protos/mod.rs")); fn serialize_enum_or_unknown<E: EnumFull, S: serde::Serializer>( e: &Option<EnumOrUnknown<E>>, s: S, ) -> Result<S::Ok, S::Error> { if let Some(e) = e { match e.enum_value() { Ok(v) => s.serialize_str(v.descriptor().name()), Err(v) => s.serialize_i32(v), } } else { s.serialize_unit() } } fn deserialize_enum_or_unknown<'de, E: EnumFull, D: serde::Deserializer<'de>>( d: D, ) -> Result<Option<EnumOrUnknown<E>>, D::Error> { struct
<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") } fn visit_str<R>(self, v: &str) -> Result<Self::Value, R> where R: serde::de::Error, { 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 ))), } } 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) } } d.deserialize_any(DeserializeEnumVisitor(PhantomData)) } #[cfg(test)] mod test { use crate::customize_example::Fruit; use crate::customize_example::Shape; #[test] fn test() { let mut fruit = Fruit::new(); fruit.set_name("Orange".to_owned()); fruit.set_weight(1.5); fruit.set_shape(Shape::CIRCLE); // Serde works. // Note rust-protobuf has built in support for JSON, // which follows protobuf-JSON serialization more correctly than default serde-json. // This example here is for the demonstration of generation of custom derives. let json = serde_json::to_string(&fruit).unwrap(); assert_eq!( "{\"name\":\"Orange\",\"weight\":1.5,\"shape\":\"CIRCLE\"}", json ); // TODO: add deserialization test } }
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 reason, //! native serde support was removed from rust-protobuf. //! //! This crate is an example how to inject serde annotations into generated code. //! //! Annotations are configured from `build.rs`. use std::fmt::Formatter; use std::marker::PhantomData; use protobuf::EnumFull; use protobuf::EnumOrUnknown; include!(concat!(env!("OUT_DIR"), "/protos/mod.rs")); fn serialize_enum_or_unknown<E: EnumFull, S: serde::Serializer>( e: &Option<EnumOrUnknown<E>>, s: S, ) -> Result<S::Ok, S::Error> { if let Some(e) = e { match e.enum_value() { Ok(v) => s.serialize_str(v.descriptor().name()), Err(v) => s.serialize_i32(v), } } else
} 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<EnumOrUnknown<E>>; fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { write!(formatter, "a string, an integer or none") } fn visit_str<R>(self, v: &str) -> Result<Self::Value, R> where R: serde::de::Error, { 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 ))), } } 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) } } d.deserialize_any(DeserializeEnumVisitor(PhantomData)) } #[cfg(test)] mod test { use crate::customize_example::Fruit; use crate::customize_example::Shape; #[test] fn test() { let mut fruit = Fruit::new(); fruit.set_name("Orange".to_owned()); fruit.set_weight(1.5); fruit.set_shape(Shape::CIRCLE); // Serde works. // Note rust-protobuf has built in support for JSON, // which follows protobuf-JSON serialization more correctly than default serde-json. // This example here is for the demonstration of generation of custom derives. let json = serde_json::to_string(&fruit).unwrap(); assert_eq!( "{\"name\":\"Orange\",\"weight\":1.5,\"shape\":\"CIRCLE\"}", json ); // TODO: add deserialization test } }
{ 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(rustc_private, rustdoc)] extern crate syntax; extern crate rustdoc; extern crate serialize as rustc_serialize; use std::collections::BTreeMap; use std::fs::{read_dir, File}; use std::io::{Read, Write}; use std::path::Path; use std::error::Error; use syntax::diagnostics::metadata::{get_metadata_dir, ErrorMetadataMap}; use rustdoc::html::markdown::Markdown; use rustc_serialize::json; /// Load all the metadata files from `metadata_dir` into an in-memory map. fn load_all_errors(metadata_dir: &Path) -> Result<ErrorMetadataMap, Box<Error>> { let mut all_errors = BTreeMap::new(); for entry in try!(read_dir(metadata_dir)) { let path = try!(entry).path(); let mut metadata_str = String::new(); try!( File::open(&path).and_then(|mut f| f.read_to_string(&mut metadata_str)) );
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!(write!(&mut output_file, r##"<!DOCTYPE html> <html> <head> <title>Rust Compiler Error Index</title> <meta charset="utf-8"> <!-- Include rust.css after main.css so its rules take priority. --> <link rel="stylesheet" type="text/css" href="main.css"/> <link rel="stylesheet" type="text/css" href="rust.css"/> <style> .error-undescribed {{ display: none; }} </style> </head> <body> "## )); try!(write!(&mut output_file, "<h1>Rust Compiler Error Index</h1>\n")); for (err_code, info) in err_map { // Enclose each error in a div so they can be shown/hidden en masse. let desc_desc = match info.description { Some(_) => "error-described", None => "error-undescribed" }; let use_desc = match info.use_site { Some(_) => "error-used", None => "error-unused" }; try!(write!(&mut output_file, "<div class=\"{} {}\">", desc_desc, use_desc)); // Error title (with self-link). try!(write!(&mut output_file, "<h2 id=\"{0}\" class=\"section-header\"><a href=\"#{0}\">{0}</a></h2>\n", err_code )); // Description rendered as markdown. match info.description { Some(ref desc) => try!(write!(&mut output_file, "{}", Markdown(desc))), None => try!(write!(&mut output_file, "<p>No description.</p>\n")) } try!(write!(&mut output_file, "</div>\n")); } try!(write!(&mut output_file, "</body>\n</html>")); Ok(()) } fn main_with_result() -> Result<(), Box<Error>> { 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(()) } fn main() { if let Err(e) = main_with_result() { panic!("{}", e.description()); } }
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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(rustc_private, rustdoc)] extern crate syntax; extern crate rustdoc; extern crate serialize as rustc_serialize; use std::collections::BTreeMap; use std::fs::{read_dir, File}; use std::io::{Read, Write}; use std::path::Path; use std::error::Error; use syntax::diagnostics::metadata::{get_metadata_dir, ErrorMetadataMap}; use rustdoc::html::markdown::Markdown; use rustc_serialize::json; /// Load all the metadata files from `metadata_dir` into an in-memory map. fn load_all_errors(metadata_dir: &Path) -> Result<ErrorMetadataMap, Box<Error>> { let mut all_errors = BTreeMap::new(); for entry in try!(read_dir(metadata_dir)) { let path = try!(entry).path(); let mut metadata_str = String::new(); try!( File::open(&path).and_then(|mut f| f.read_to_string(&mut metadata_str)) ); let some_errors: ErrorMetadataMap = try!(json::decode(&metadata_str)); for (err_code, info) in some_errors { 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!(write!(&mut output_file, r##"<!DOCTYPE html> <html> <head> <title>Rust Compiler Error Index</title> <meta charset="utf-8"> <!-- Include rust.css after main.css so its rules take priority. --> <link rel="stylesheet" type="text/css" href="main.css"/> <link rel="stylesheet" type="text/css" href="rust.css"/> <style> .error-undescribed {{ display: none; }} </style> </head> <body> "## )); try!(write!(&mut output_file, "<h1>Rust Compiler Error Index</h1>\n")); for (err_code, info) in err_map { // Enclose each error in a div so they can be shown/hidden en masse. let desc_desc = match info.description { Some(_) => "error-described", None => "error-undescribed" }; let use_desc = match info.use_site { Some(_) => "error-used", None => "error-unused" }; try!(write!(&mut output_file, "<div class=\"{} {}\">", desc_desc, use_desc)); // Error title (with self-link). try!(write!(&mut output_file, "<h2 id=\"{0}\" class=\"section-header\"><a href=\"#{0}\">{0}</a></h2>\n", err_code )); // Description rendered as markdown. match info.description { Some(ref desc) => try!(write!(&mut output_file, "{}", Markdown(desc))), None => try!(write!(&mut output_file, "<p>No description.</p>\n")) } try!(write!(&mut output_file, "</div>\n")); } try!(write!(&mut output_file, "</body>\n</html>")); Ok(()) } fn main_with_result() -> Result<(), Box<Error>> { 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(()) } fn main() { if let Err(e) = main_with_result()
}
{ 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(rustc_private, rustdoc)] extern crate syntax; extern crate rustdoc; extern crate serialize as rustc_serialize; use std::collections::BTreeMap; use std::fs::{read_dir, File}; use std::io::{Read, Write}; use std::path::Path; use std::error::Error; use syntax::diagnostics::metadata::{get_metadata_dir, ErrorMetadataMap}; use rustdoc::html::markdown::Markdown; use rustc_serialize::json; /// Load all the metadata files from `metadata_dir` into an in-memory map. fn load_all_errors(metadata_dir: &Path) -> Result<ErrorMetadataMap, Box<Error>> { let mut all_errors = BTreeMap::new(); for entry in try!(read_dir(metadata_dir)) { let path = try!(entry).path(); let mut metadata_str = String::new(); try!( File::open(&path).and_then(|mut f| f.read_to_string(&mut metadata_str)) ); let some_errors: ErrorMetadataMap = try!(json::decode(&metadata_str)); for (err_code, info) in some_errors { 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!(write!(&mut output_file, r##"<!DOCTYPE html> <html> <head> <title>Rust Compiler Error Index</title> <meta charset="utf-8"> <!-- Include rust.css after main.css so its rules take priority. --> <link rel="stylesheet" type="text/css" href="main.css"/> <link rel="stylesheet" type="text/css" href="rust.css"/> <style> .error-undescribed {{ display: none; }} </style> </head> <body> "## )); try!(write!(&mut output_file, "<h1>Rust Compiler Error Index</h1>\n")); for (err_code, info) in err_map { // Enclose each error in a div so they can be shown/hidden en masse. let desc_desc = match info.description { Some(_) => "error-described", None => "error-undescribed" }; let use_desc = match info.use_site { Some(_) => "error-used", None => "error-unused" }; try!(write!(&mut output_file, "<div class=\"{} {}\">", desc_desc, use_desc)); // Error title (with self-link). try!(write!(&mut output_file, "<h2 id=\"{0}\" class=\"section-header\"><a href=\"#{0}\">{0}</a></h2>\n", err_code )); // Description rendered as markdown. match info.description { Some(ref desc) => try!(write!(&mut output_file, "{}", Markdown(desc))), None => try!(write!(&mut output_file, "<p>No description.</p>\n")) } try!(write!(&mut output_file, "</div>\n")); } try!(write!(&mut output_file, "</body>\n</html>")); Ok(()) } fn main_with_result() -> Result<(), Box<Error>> { 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(()) } fn
() { 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(rustc_private, rustdoc)] extern crate syntax; extern crate rustdoc; extern crate serialize as rustc_serialize; use std::collections::BTreeMap; use std::fs::{read_dir, File}; use std::io::{Read, Write}; use std::path::Path; use std::error::Error; use syntax::diagnostics::metadata::{get_metadata_dir, ErrorMetadataMap}; use rustdoc::html::markdown::Markdown; use rustc_serialize::json; /// Load all the metadata files from `metadata_dir` into an in-memory map. fn load_all_errors(metadata_dir: &Path) -> Result<ErrorMetadataMap, Box<Error>> { let mut all_errors = BTreeMap::new(); for entry in try!(read_dir(metadata_dir)) { let path = try!(entry).path(); let mut metadata_str = String::new(); try!( File::open(&path).and_then(|mut f| f.read_to_string(&mut metadata_str)) ); let some_errors: ErrorMetadataMap = try!(json::decode(&metadata_str)); for (err_code, info) in some_errors { 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!(write!(&mut output_file, r##"<!DOCTYPE html> <html> <head> <title>Rust Compiler Error Index</title> <meta charset="utf-8"> <!-- Include rust.css after main.css so its rules take priority. --> <link rel="stylesheet" type="text/css" href="main.css"/> <link rel="stylesheet" type="text/css" href="rust.css"/> <style> .error-undescribed {{ display: none; }} </style> </head> <body> "## )); try!(write!(&mut output_file, "<h1>Rust Compiler Error Index</h1>\n")); for (err_code, info) in err_map { // Enclose each error in a div so they can be shown/hidden en masse. let desc_desc = match info.description { Some(_) => "error-described", None => "error-undescribed" }; let use_desc = match info.use_site { Some(_) => "error-used", None => "error-unused" }; try!(write!(&mut output_file, "<div class=\"{} {}\">", desc_desc, use_desc)); // Error title (with self-link). try!(write!(&mut output_file, "<h2 id=\"{0}\" class=\"section-header\"><a href=\"#{0}\">{0}</a></h2>\n", err_code )); // Description rendered as markdown. match info.description { Some(ref desc) => try!(write!(&mut output_file, "{}", Markdown(desc))), None => try!(write!(&mut output_file, "<p>No description.</p>\n")) } try!(write!(&mut output_file, "</div>\n")); } try!(write!(&mut output_file, "</body>\n</html>")); Ok(()) } fn main_with_result() -> Result<(), Box<Error>>
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!(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"); assert!((0u8, 0u32).foo() == "(u8, u32)"); assert!((0u8, 0u8).foo() == "(u8, u8)"); }
// // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // 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
() { 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"); assert!((0u8, 0u32).foo() == "(u8, u32)"); assert!((0u8, 0u8).foo() == "(u8, u8)"); }
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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // 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!(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"); assert!((0u8, 0u32).foo() == "(u8, u32)"); assert!((0u8, 0u8).foo() == "(u8, u8)"); }
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); } let truth = collection.clone(); // Create the client 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 = client.gen_query(0 as u64); let answer = server.gen_answer(query.query, query.num); let result = client.decode_answer(answer.answer, answer.num); assert!(PungTuple::new(result.result) == truth[first + 0 as usize]); } let first = 1; let last = 3; let test_num = last - first; let server_2 = 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 = client.gen_query(1 as u64); let answer = server_2.gen_answer(query.query, query.num); let result = client.decode_answer(answer.answer, answer.num); assert!(PungTuple::new(result.result) == truth[first + 1 as usize]); } let first = 3; let last = 6; let test_num = last - first; let server_3 = 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 = client.gen_query(2 as u64); let answer = server_3.gen_answer(query.query, query.num); let result = client.decode_answer(answer.answer, answer.num); assert!(PungTuple::new(result.result) == truth[first + 2 as usize]); } }
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]; rng.fill_bytes(&mut x); let pt = PungTuple::new(&x); collection.push(pt); } let truth = collection.clone(); // Create the client 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 = client.gen_query(0 as u64); let answer = server.gen_answer(query.query, query.num); let result = client.decode_answer(answer.answer, answer.num); assert!(PungTuple::new(result.result) == truth[first + 0 as usize]); } let first = 1; let last = 3; let test_num = last - first; let server_2 = 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 = client.gen_query(1 as u64); let answer = server_2.gen_answer(query.query, query.num); let result = client.decode_answer(answer.answer, answer.num); assert!(PungTuple::new(result.result) == truth[first + 1 as usize]); } let first = 3; let last = 6; let test_num = last - first; let server_3 = 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 = client.gen_query(2 as u64); let answer = server_3.gen_answer(query.query, query.num); let result = client.decode_answer(answer.answer, answer.num); assert!(PungTuple::new(result.result) == truth[first + 2 as usize]); } }
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 = client.gen_query(0 as u64); let answer = server.gen_answer(query.query, query.num); let result = client.decode_answer(answer.answer, answer.num); assert!(PungTuple::new(result.result) == truth[first + 0 as usize]); } let first = 1; let last = 3; let test_num = last - first; let server_2 = 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 = client.gen_query(1 as u64); let answer = server_2.gen_answer(query.query, query.num); let result = client.decode_answer(answer.answer, answer.num); assert!(PungTuple::new(result.result) == truth[first + 1 as usize]); } let first = 3; let last = 6; let test_num = last - first; let server_3 = 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 = client.gen_query(2 as u64); let answer = server_3.gen_answer(query.query, query.num); let result = client.decode_answer(answer.answer, answer.num); assert!(PungTuple::new(result.result) == truth[first + 2 as usize]); } }
{ 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); } let truth = collection.clone(); // Create the client
identifier_body
fpe.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) Ben Segall <[email protected]> // Copyright (c) edef <[email protected]> // 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://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. #![cfg(target_os = "linux")] #![feature(test)] #![feature(thread_local)] #![feature(asm)] extern crate fringe; extern crate test; use fringe::{OsStack, Generator}; use test::black_box; const FE_DIVBYZERO: i32 = 0x4; extern { fn feenableexcept(except: i32) -> i32; } #[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(())); }
identifier_body
fpe.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) Ben Segall <[email protected]> // Copyright (c) edef <[email protected]> // 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://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. #![cfg(target_os = "linux")] #![feature(test)] #![feature(thread_local)] #![feature(asm)] extern crate fringe; extern crate test; use fringe::{OsStack, Generator}; use test::black_box; const FE_DIVBYZERO: i32 = 0x4; extern { fn feenableexcept(except: i32) -> i32; } #[test] #[ignore] fn
() { 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 <[email protected]> // Copyright (c) edef <[email protected]> // 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://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. #![cfg(target_os = "linux")] #![feature(test)] #![feature(thread_local)] #![feature(asm)] extern crate fringe; extern crate test; use fringe::{OsStack, Generator}; use test::black_box; const FE_DIVBYZERO: i32 = 0x4; extern { fn feenableexcept(except: i32) -> i32;
#[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 similar //! to the core traits in the [`serde`] library. Rather than representing a //! generically serializeable type, they represent types that can be converted //! to and from Cerberus's wire format, which has a unique, ad-hoc data model. //! //! [`FromWire`]: trait.FromWire.html //! [`ToWire`]: trait.ToWire.html //! [`serde`]: https://serde.rs use crate::io; use crate::io::BeInt; use crate::io::Read; use crate::io::Write; /// A type which can be deserialized from the Cerberus wire format. /// /// The lifetime `'wire` indicates that the type can be deserialized from a /// buffer of lifetime `'wire`. pub trait FromWire<'wire>: Sized { /// Deserializes a `Self` w of `r`. fn from_wire<R: Read<'wire>>(r: R) -> Result<Self, FromWireError>; } /// An deserialization error. #[derive(Clone, Copy, Debug)] pub enum FromWireError { /// Indicates that something went wrong in an `io` operation. /// /// [`io`]:../../io/index.html Io(io::Error), /// Indicates that some field within the request was outside of its /// valid range. OutOfRange, } impl From<io::Error> for FromWireError { fn
(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 ToWireError { /// Indicates that something went wrong in an [`io`] operation. /// /// [`io`]:../../io/index.html Io(io::Error), /// Indicates that the data to be serialized was invalid. InvalidData, } impl From<io::Error> for ToWireError { fn from(e: io::Error) -> Self { Self::Io(e) } } /// Represents a C-like enum that can be converted to and from a wire /// representation as well as to and from a string representation. /// /// An implementation of this trait can be thought of as an unsigned /// integer with a limited range: every enum variant can be converted /// to the wire format and back, though not every value of the wire /// representation can be converted into an enum variant. /// /// In particular the following identity must hold for all types T: /// ``` /// # use spiutils::protocol::wire::WireEnum; /// # fn test<T: WireEnum + Copy + PartialEq + std::fmt::Debug>(x: T) { /// assert_eq!(T::from_wire_value(T::to_wire_value(x)), Some(x)); /// # } /// ``` /// /// Also, the following identity must hold for all types T: /// ``` /// # use manticore::protocol::wire::WireEnum; /// # fn test<T: WireEnum + Copy + PartialEq + std::fmt::Debug>(x: T) { /// assert_eq!(T::from_name(T::name(x)), Some(x)); /// # } /// ``` pub trait WireEnum: Sized + Copy { /// The unrelying "wire type". This is almost always some kind of /// unsigned integer. type Wire: BeInt; /// Converts `self` into its underlying wire representation. fn to_wire_value(self) -> Self::Wire; /// Attempts to parse a value of `Self` from the underlying wire /// representation. fn from_wire_value(wire: Self::Wire) -> Option<Self>; /// Converts `self` into a string representation. fn name(self) -> &'static str; /// Attempts to convert a value of `Self` from a string representation. fn from_name(str: &str) -> Option<Self>; } impl<'wire, E> FromWire<'wire> for E where E: WireEnum, { fn from_wire<R: Read<'wire>>(mut r: R) -> Result<Self, FromWireError> { let wire = <Self as WireEnum>::Wire::read_from(&mut r)?; Self::from_wire_value(wire).ok_or(FromWireError::OutOfRange) } } impl<E> ToWire for E where E: WireEnum, { fn to_wire<W: Write>(&self, mut w: W) -> Result<(), ToWireError> { self.to_wire_value().write_to(&mut w)?; Ok(()) } } /// A deserialization-from-string error. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct WireEnumFromStrError; /// A conveinence macro for generating `WireEnum`-implementing enums. /// /// /// Syntax is as follows: /// ```text /// wire_enum! { /// /// This is my enum. /// pub enum MyEnum : u8 { /// /// Variant `A`. /// A = 0x00, /// /// Variant `B`. /// B = 0x01, /// } /// } /// ``` /// This macro will generate an implementation of `WireEnum<Wire=u8>` for /// the above enum. macro_rules! wire_enum { ($(#[$meta:meta])* $vis:vis enum $name:ident : $wire:ident { $($(#[$meta_variant:meta])* $variant:ident = $value:literal,)* }) => { $(#[$meta])* #[repr($wire)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] $vis enum $name { $( $(#[$meta_variant])* $variant = $value, )* } impl $crate::protocol::wire::WireEnum for $name { type Wire = $wire; fn to_wire_value(self) -> Self::Wire { self as $wire } fn from_wire_value(wire: Self::Wire) -> Option<Self> { match wire { $( $value => Some(Self::$variant), )* _ => None, } } fn name(self) -> &'static str { match self { $( Self::$variant => stringify!($variant), )* } } fn from_name(name: &str) -> Option<Self> { match name { $( stringify!($variant) => Some(Self::$variant), )* _ => None, } } } impl core::fmt::Display for $name { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { use $crate::protocol::wire::WireEnum; write!(f, "{}", self.name()) } } impl core::str::FromStr for $name { type Err = $crate::protocol::wire::WireEnumFromStrError; 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), } } } } } #[cfg(test)] mod test { wire_enum! { /// An enum for testing. #[cfg_attr(feature = "arbitrary-derive", derive(Arbitrary))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum DemoEnum: u8 { /// Unknown value Unknown = 0x00, /// First enum value First = 0x01, /// Second enum value Second = 0x02, } } #[test] fn from_name() { use crate::protocol::wire::*; let value = DemoEnum::from_name("Second").expect("from_name failed"); assert_eq!(value, DemoEnum::Second); let value = DemoEnum::from_name("First").expect("from_name failed"); assert_eq!(value, DemoEnum::First); assert_eq!(None, DemoEnum::from_name("does not exist")); } #[test] fn name() { use crate::protocol::wire::*; assert_eq!(DemoEnum::First.name(), "First"); assert_eq!(DemoEnum::Second.name(), "Second"); } }
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 similar //! to the core traits in the [`serde`] library. Rather than representing a //! generically serializeable type, they represent types that can be converted //! to and from Cerberus's wire format, which has a unique, ad-hoc data model. //! //! [`FromWire`]: trait.FromWire.html //! [`ToWire`]: trait.ToWire.html //! [`serde`]: https://serde.rs use crate::io; use crate::io::BeInt; use crate::io::Read; use crate::io::Write; /// A type which can be deserialized from the Cerberus wire format. /// /// The lifetime `'wire` indicates that the type can be deserialized from a /// buffer of lifetime `'wire`. pub trait FromWire<'wire>: Sized { /// Deserializes a `Self` w of `r`. fn from_wire<R: Read<'wire>>(r: R) -> Result<Self, FromWireError>; } /// An deserialization error. #[derive(Clone, Copy, Debug)] pub enum FromWireError { /// Indicates that something went wrong in an `io` operation. /// /// [`io`]:../../io/index.html Io(io::Error), /// Indicates that some field within the request was outside of its /// valid range. OutOfRange, } impl From<io::Error> for FromWireError { fn from(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 ToWireError { /// Indicates that something went wrong in an [`io`] operation. /// /// [`io`]:../../io/index.html Io(io::Error), /// Indicates that the data to be serialized was invalid. InvalidData, } impl From<io::Error> for ToWireError { fn from(e: io::Error) -> Self { Self::Io(e) } } /// Represents a C-like enum that can be converted to and from a wire /// representation as well as to and from a string representation. /// /// An implementation of this trait can be thought of as an unsigned /// integer with a limited range: every enum variant can be converted /// to the wire format and back, though not every value of the wire /// representation can be converted into an enum variant. /// /// In particular the following identity must hold for all types T: /// ``` /// # use spiutils::protocol::wire::WireEnum; /// # fn test<T: WireEnum + Copy + PartialEq + std::fmt::Debug>(x: T) { /// assert_eq!(T::from_wire_value(T::to_wire_value(x)), Some(x)); /// # } /// ``` /// /// Also, the following identity must hold for all types T: /// ``` /// # use manticore::protocol::wire::WireEnum; /// # fn test<T: WireEnum + Copy + PartialEq + std::fmt::Debug>(x: T) { /// assert_eq!(T::from_name(T::name(x)), Some(x)); /// # } /// ``` pub trait WireEnum: Sized + Copy { /// The unrelying "wire type". This is almost always some kind of /// unsigned integer. type Wire: BeInt; /// Converts `self` into its underlying wire representation. fn to_wire_value(self) -> Self::Wire; /// Attempts to parse a value of `Self` from the underlying wire /// representation. fn from_wire_value(wire: Self::Wire) -> Option<Self>; /// Converts `self` into a string representation. fn name(self) -> &'static str; /// Attempts to convert a value of `Self` from a string representation. fn from_name(str: &str) -> Option<Self>; } impl<'wire, E> FromWire<'wire> for E where E: WireEnum, { fn from_wire<R: Read<'wire>>(mut r: R) -> Result<Self, FromWireError> { let wire = <Self as WireEnum>::Wire::read_from(&mut r)?; Self::from_wire_value(wire).ok_or(FromWireError::OutOfRange) } } impl<E> ToWire for E where E: WireEnum, { fn to_wire<W: Write>(&self, mut w: W) -> Result<(), ToWireError> { self.to_wire_value().write_to(&mut w)?; Ok(()) } } /// A deserialization-from-string error. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct WireEnumFromStrError; /// A conveinence macro for generating `WireEnum`-implementing enums. /// /// /// Syntax is as follows: /// ```text /// wire_enum! { /// /// This is my enum. /// pub enum MyEnum : u8 { /// /// Variant `A`. /// A = 0x00, /// /// Variant `B`. /// B = 0x01, /// } /// } /// ``` /// This macro will generate an implementation of `WireEnum<Wire=u8>` for /// the above enum. macro_rules! wire_enum { ($(#[$meta:meta])* $vis:vis enum $name:ident : $wire:ident { $($(#[$meta_variant:meta])* $variant:ident = $value:literal,)* }) => { $(#[$meta])* #[repr($wire)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] $vis enum $name { $( $(#[$meta_variant])* $variant = $value, )* } impl $crate::protocol::wire::WireEnum for $name { type Wire = $wire; fn to_wire_value(self) -> Self::Wire { self as $wire } fn from_wire_value(wire: Self::Wire) -> Option<Self> { match wire { $( $value => Some(Self::$variant), )* _ => None, } } fn name(self) -> &'static str { match self { $( Self::$variant => stringify!($variant), )* } } fn from_name(name: &str) -> Option<Self> { match name { $( stringify!($variant) => Some(Self::$variant), )* _ => None, } } } impl core::fmt::Display for $name { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { use $crate::protocol::wire::WireEnum; write!(f, "{}", self.name()) }
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), } } } } } #[cfg(test)] mod test { wire_enum! { /// An enum for testing. #[cfg_attr(feature = "arbitrary-derive", derive(Arbitrary))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum DemoEnum: u8 { /// Unknown value Unknown = 0x00, /// First enum value First = 0x01, /// Second enum value Second = 0x02, } } #[test] fn from_name() { use crate::protocol::wire::*; let value = DemoEnum::from_name("Second").expect("from_name failed"); assert_eq!(value, DemoEnum::Second); let value = DemoEnum::from_name("First").expect("from_name failed"); assert_eq!(value, DemoEnum::First); assert_eq!(None, DemoEnum::from_name("does not exist")); } #[test] fn name() { use crate::protocol::wire::*; assert_eq!(DemoEnum::First.name(), "First"); assert_eq!(DemoEnum::Second.name(), "Second"); } }
} 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 similar //! to the core traits in the [`serde`] library. Rather than representing a //! generically serializeable type, they represent types that can be converted //! to and from Cerberus's wire format, which has a unique, ad-hoc data model. //! //! [`FromWire`]: trait.FromWire.html //! [`ToWire`]: trait.ToWire.html //! [`serde`]: https://serde.rs use crate::io; use crate::io::BeInt; use crate::io::Read; use crate::io::Write; /// A type which can be deserialized from the Cerberus wire format. /// /// The lifetime `'wire` indicates that the type can be deserialized from a /// buffer of lifetime `'wire`. pub trait FromWire<'wire>: Sized { /// Deserializes a `Self` w of `r`. fn from_wire<R: Read<'wire>>(r: R) -> Result<Self, FromWireError>; } /// An deserialization error. #[derive(Clone, Copy, Debug)] pub enum FromWireError { /// Indicates that something went wrong in an `io` operation. /// /// [`io`]:../../io/index.html Io(io::Error), /// Indicates that some field within the request was outside of its /// valid range. OutOfRange, } impl From<io::Error> for FromWireError { fn from(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 ToWireError { /// Indicates that something went wrong in an [`io`] operation. /// /// [`io`]:../../io/index.html Io(io::Error), /// Indicates that the data to be serialized was invalid. InvalidData, } impl From<io::Error> for ToWireError { fn from(e: io::Error) -> Self { Self::Io(e) } } /// Represents a C-like enum that can be converted to and from a wire /// representation as well as to and from a string representation. /// /// An implementation of this trait can be thought of as an unsigned /// integer with a limited range: every enum variant can be converted /// to the wire format and back, though not every value of the wire /// representation can be converted into an enum variant. /// /// In particular the following identity must hold for all types T: /// ``` /// # use spiutils::protocol::wire::WireEnum; /// # fn test<T: WireEnum + Copy + PartialEq + std::fmt::Debug>(x: T) { /// assert_eq!(T::from_wire_value(T::to_wire_value(x)), Some(x)); /// # } /// ``` /// /// Also, the following identity must hold for all types T: /// ``` /// # use manticore::protocol::wire::WireEnum; /// # fn test<T: WireEnum + Copy + PartialEq + std::fmt::Debug>(x: T) { /// assert_eq!(T::from_name(T::name(x)), Some(x)); /// # } /// ``` pub trait WireEnum: Sized + Copy { /// The unrelying "wire type". This is almost always some kind of /// unsigned integer. type Wire: BeInt; /// Converts `self` into its underlying wire representation. fn to_wire_value(self) -> Self::Wire; /// Attempts to parse a value of `Self` from the underlying wire /// representation. fn from_wire_value(wire: Self::Wire) -> Option<Self>; /// Converts `self` into a string representation. fn name(self) -> &'static str; /// Attempts to convert a value of `Self` from a string representation. fn from_name(str: &str) -> Option<Self>; } impl<'wire, E> FromWire<'wire> for E where E: WireEnum, { fn from_wire<R: Read<'wire>>(mut r: R) -> Result<Self, FromWireError> { let wire = <Self as WireEnum>::Wire::read_from(&mut r)?; Self::from_wire_value(wire).ok_or(FromWireError::OutOfRange) } } impl<E> ToWire for E where E: WireEnum, { fn to_wire<W: Write>(&self, mut w: W) -> Result<(), ToWireError> { self.to_wire_value().write_to(&mut w)?; Ok(()) } } /// A deserialization-from-string error. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct WireEnumFromStrError; /// A conveinence macro for generating `WireEnum`-implementing enums. /// /// /// Syntax is as follows: /// ```text /// wire_enum! { /// /// This is my enum. /// pub enum MyEnum : u8 { /// /// Variant `A`. /// A = 0x00, /// /// Variant `B`. /// B = 0x01, /// } /// } /// ``` /// This macro will generate an implementation of `WireEnum<Wire=u8>` for /// the above enum. macro_rules! wire_enum { ($(#[$meta:meta])* $vis:vis enum $name:ident : $wire:ident { $($(#[$meta_variant:meta])* $variant:ident = $value:literal,)* }) => { $(#[$meta])* #[repr($wire)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] $vis enum $name { $( $(#[$meta_variant])* $variant = $value, )* } impl $crate::protocol::wire::WireEnum for $name { type Wire = $wire; fn to_wire_value(self) -> Self::Wire { self as $wire } fn from_wire_value(wire: Self::Wire) -> Option<Self> { match wire { $( $value => Some(Self::$variant), )* _ => None, } } fn name(self) -> &'static str { match self { $( Self::$variant => stringify!($variant), )* } } fn from_name(name: &str) -> Option<Self> { match name { $( stringify!($variant) => Some(Self::$variant), )* _ => None, } } } impl core::fmt::Display for $name { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { use $crate::protocol::wire::WireEnum; write!(f, "{}", self.name()) } } impl core::str::FromStr for $name { type Err = $crate::protocol::wire::WireEnumFromStrError; 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), } } } } } #[cfg(test)] mod test { wire_enum! { /// An enum for testing. #[cfg_attr(feature = "arbitrary-derive", derive(Arbitrary))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum DemoEnum: u8 { /// Unknown value Unknown = 0x00, /// First enum value First = 0x01, /// Second enum value Second = 0x02, } } #[test] fn from_name() { use crate::protocol::wire::*; let value = DemoEnum::from_name("Second").expect("from_name failed"); assert_eq!(value, DemoEnum::Second); let value = DemoEnum::from_name("First").expect("from_name failed"); assert_eq!(value, DemoEnum::First); assert_eq!(None, DemoEnum::from_name("does not exist")); } #[test] fn name()
}
{ 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::bindings::codegen::Bindings::HTMLBaseElementBinding::HTMLBaseElementMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element}; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{document_from_node, BindContext, Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use servo_url::ServoUrl; #[dom_struct] pub struct HTMLBaseElement { htmlelement: HTMLElement, } impl HTMLBaseElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLBaseElement { HTMLBaseElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLBaseElement>
/// <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 \ that have a base url.", ); let document = document_from_node(self); let base = document.fallback_base_url(); let parsed = base.join(&href.value()); parsed.unwrap_or(base) } /// Update the cached base element in response to binding or unbinding from /// a tree. pub fn bind_unbind(&self, tree_in_doc: bool) { if!tree_in_doc || self.upcast::<Node>().containing_shadow_root().is_some() { return; } if self.upcast::<Element>().has_attribute(&local_name!("href")) { let document = document_from_node(self); document.refresh_base_element(); } } } 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_attribute(&ns!(), &local_name!("href")); let value = attr.as_ref().map(|attr| attr.value()); let url = value.as_ref().map_or("", |value| &**value); // Step 3. let url_record = document.fallback_base_url().join(url); match url_record { Err(_) => { // Step 4. url.into() }, Ok(url_record) => { // Step 5. url_record.into_string().into() }, } } // 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: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if *attr.local_name() == local_name!("href") { document_from_node(self).refresh_base_element(); } } fn bind_to_tree(&self, context: &BindContext) { self.super_type().unwrap().bind_to_tree(context); self.bind_unbind(context.tree_in_doc); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); self.bind_unbind(context.tree_in_doc); } }
{ 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::bindings::codegen::Bindings::HTMLBaseElementBinding::HTMLBaseElementMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element}; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{document_from_node, BindContext, Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use servo_url::ServoUrl; #[dom_struct] pub struct HTMLBaseElement { htmlelement: HTMLElement, } impl HTMLBaseElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLBaseElement { HTMLBaseElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLBaseElement> { Node::reflect_node( Box::new(HTMLBaseElement::new_inherited(local_name, prefix, document)), document, HTMLBaseElementBinding::Wrap, ) } /// <https://html.spec.whatwg.org/multipage/#frozen-base-url> pub fn
(&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_node(self); let base = document.fallback_base_url(); let parsed = base.join(&href.value()); parsed.unwrap_or(base) } /// Update the cached base element in response to binding or unbinding from /// a tree. pub fn bind_unbind(&self, tree_in_doc: bool) { if!tree_in_doc || self.upcast::<Node>().containing_shadow_root().is_some() { return; } if self.upcast::<Element>().has_attribute(&local_name!("href")) { let document = document_from_node(self); document.refresh_base_element(); } } } 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_attribute(&ns!(), &local_name!("href")); let value = attr.as_ref().map(|attr| attr.value()); let url = value.as_ref().map_or("", |value| &**value); // Step 3. let url_record = document.fallback_base_url().join(url); match url_record { Err(_) => { // Step 4. url.into() }, Ok(url_record) => { // Step 5. url_record.into_string().into() }, } } // 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: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if *attr.local_name() == local_name!("href") { document_from_node(self).refresh_base_element(); } } fn bind_to_tree(&self, context: &BindContext) { self.super_type().unwrap().bind_to_tree(context); self.bind_unbind(context.tree_in_doc); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); self.bind_unbind(context.tree_in_doc); } }
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::bindings::codegen::Bindings::HTMLBaseElementBinding::HTMLBaseElementMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element}; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{document_from_node, BindContext, Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use servo_url::ServoUrl; #[dom_struct] pub struct HTMLBaseElement { htmlelement: HTMLElement, } impl HTMLBaseElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLBaseElement { HTMLBaseElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLBaseElement> { Node::reflect_node( Box::new(HTMLBaseElement::new_inherited(local_name, prefix, document)), document, HTMLBaseElementBinding::Wrap, ) } /// <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 \ that have a base url.", ); let document = document_from_node(self); let base = document.fallback_base_url(); let parsed = base.join(&href.value()); parsed.unwrap_or(base) } /// Update the cached base element in response to binding or unbinding from /// a tree. pub fn bind_unbind(&self, tree_in_doc: bool) { if!tree_in_doc || self.upcast::<Node>().containing_shadow_root().is_some() { return; } if self.upcast::<Element>().has_attribute(&local_name!("href")) { let document = document_from_node(self); document.refresh_base_element(); } } } 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_attribute(&ns!(), &local_name!("href")); let value = attr.as_ref().map(|attr| attr.value()); let url = value.as_ref().map_or("", |value| &**value); // Step 3. let url_record = document.fallback_base_url().join(url); match url_record { Err(_) => { // Step 4. url.into() }, Ok(url_record) => { // Step 5. url_record.into_string().into() }, }
} // 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: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if *attr.local_name() == local_name!("href") { document_from_node(self).refresh_base_element(); } } fn bind_to_tree(&self, context: &BindContext) { self.super_type().unwrap().bind_to_tree(context); self.bind_unbind(context.tree_in_doc); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); self.bind_unbind(context.tree_in_doc); } }
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::bindings::codegen::Bindings::HTMLBaseElementBinding::HTMLBaseElementMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element}; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{document_from_node, BindContext, Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use servo_url::ServoUrl; #[dom_struct] pub struct HTMLBaseElement { htmlelement: HTMLElement, } impl HTMLBaseElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLBaseElement { HTMLBaseElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLBaseElement> { Node::reflect_node( Box::new(HTMLBaseElement::new_inherited(local_name, prefix, document)), document, HTMLBaseElementBinding::Wrap, ) } /// <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 \ that have a base url.", ); let document = document_from_node(self); let base = document.fallback_base_url(); let parsed = base.join(&href.value()); parsed.unwrap_or(base) } /// Update the cached base element in response to binding or unbinding from /// a tree. pub fn bind_unbind(&self, tree_in_doc: bool) { if!tree_in_doc || self.upcast::<Node>().containing_shadow_root().is_some() { return; } if self.upcast::<Element>().has_attribute(&local_name!("href"))
} } 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_attribute(&ns!(), &local_name!("href")); let value = attr.as_ref().map(|attr| attr.value()); let url = value.as_ref().map_or("", |value| &**value); // Step 3. let url_record = document.fallback_base_url().join(url); match url_record { Err(_) => { // Step 4. url.into() }, Ok(url_record) => { // Step 5. url_record.into_string().into() }, } } // 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: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if *attr.local_name() == local_name!("href") { document_from_node(self).refresh_base_element(); } } fn bind_to_tree(&self, context: &BindContext) { self.super_type().unwrap().bind_to_tree(context); self.bind_unbind(context.tree_in_doc); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); self.bind_unbind(context.tree_in_doc); } }
{ 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
#![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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(struct_variant)]; enum
{ 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(struct_variant)]; enum E { 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!(),
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; pub mod edge; pub mod graph; pub mod nodept; pub mod population; pub mod tour; // pub mod graphviz_conv; static DEFAULT_ITERS: usize = 800; static DEFAULT_MUT_RATE: f64 = 0.02; static DEFAULT_POP_SIZE: usize = 200; static DEFAULT_TOURNAMENT_SIZE: usize = 15; fn usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief[..])); } fn
<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(); opts.optflag("h", "help", "print this help menu"); opts.optopt("m", "mutation_rate", "change the mutation rate (default: 0.015)", "MUTRATE"); opts.optopt("i", "iters", "change the number of GA iterations (default: 50)", "ITERS"); opts.optopt("p", "pop_size", "change the population size (default: 5000)", "POPSIZE"); opts.optflag("v", "verbose", "print a lot of information, including timing."); opts.optopt("r", "read", "read graph from a.tsp file", "READ"); opts.optopt("t", "tournament_size", "change the number of specimens used for tournament selection", "TSIZE"); let matches = match opts.parse(args) { Ok(m) => m, Err(_) => panic!("Failed matching options"), }; if matches.opt_present("h") { usage(&program, opts); return; } let v_flag = matches.opt_present("v"); let node_count = 15; let tournament_size = parse_opt::<usize>(&matches, "t", DEFAULT_TOURNAMENT_SIZE); let scale = 200.0; let mutation_rate = parse_opt::<f64>(&matches, "m", DEFAULT_MUT_RATE); let iter_count = parse_opt::<usize>(&matches, "i", DEFAULT_ITERS); let population_size = parse_opt::<usize>(&matches, "p", DEFAULT_POP_SIZE); let graph; if matches.opt_present("r") { 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(); } 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!("Running TSP-GA on a graph with |N| = {}, |E| = {}", graph.num_nodes, graph.all_edges().len()); println!("GA parameters:"); println!("\tMutation rate = {}", mutation_rate); println!("\tPopulation size = {}", population_size); println!("\tNumber of iterations = {}", iter_count); println!("\tTournament size = {}", tournament_size); } // RNG for the GA let rng: StdRng = match StdRng::new() { Ok(r) => r, Err(_) => panic!("failed to acquire RNG"), }; let mut pop = Population::new(population_size, Box::new(graph), mutation_rate, tournament_size, rng); let first_result = pop.fittest().total_weight; let mut best_result = pop.fittest(); if v_flag { println!("Fittest at start: {}", first_result) } // Evolve the population let t0 = precise_time_ns(); for _ in 0..iter_count { pop = pop.evolve(); let r = pop.fittest(); if r.total_weight < best_result.total_weight { best_result = r; } } let t1 = precise_time_ns(); // Show the end result and the time it took. println!("Resulting tour: {:?}\nwith weight {}", best_result.nodes, best_result.total_weight); if v_flag { let dt = ((t1 - t0) as f64) / 1e6; println!("t_avg = {} ms, t_overall = {} s", dt / iter_count as f64, dt / 1000.0); println!("Improvement factor from first solution: {}", (first_result / best_result.total_weight)); } }
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; pub mod edge; pub mod graph; pub mod nodept; pub mod population; pub mod tour; // pub mod graphviz_conv; static DEFAULT_ITERS: usize = 800; static DEFAULT_MUT_RATE: f64 = 0.02; static DEFAULT_POP_SIZE: usize = 200; static DEFAULT_TOURNAMENT_SIZE: usize = 15; fn usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief[..])); } 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 = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optopt("m", "mutation_rate", "change the mutation rate (default: 0.015)", "MUTRATE"); opts.optopt("i", "iters", "change the number of GA iterations (default: 50)", "ITERS"); opts.optopt("p", "pop_size", "change the population size (default: 5000)", "POPSIZE"); opts.optflag("v", "verbose", "print a lot of information, including timing."); opts.optopt("r", "read", "read graph from a.tsp file", "READ"); opts.optopt("t", "tournament_size", "change the number of specimens used for tournament selection", "TSIZE"); let matches = match opts.parse(args) { Ok(m) => m, Err(_) => panic!("Failed matching options"), }; if matches.opt_present("h") { usage(&program, opts); return; } let v_flag = matches.opt_present("v"); let node_count = 15; let tournament_size = parse_opt::<usize>(&matches, "t", DEFAULT_TOURNAMENT_SIZE); let scale = 200.0; let mutation_rate = parse_opt::<f64>(&matches, "m", DEFAULT_MUT_RATE); let iter_count = parse_opt::<usize>(&matches, "i", DEFAULT_ITERS); let population_size = parse_opt::<usize>(&matches, "p", DEFAULT_POP_SIZE); let graph; if matches.opt_present("r")
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!("Running TSP-GA on a graph with |N| = {}, |E| = {}", graph.num_nodes, graph.all_edges().len()); println!("GA parameters:"); println!("\tMutation rate = {}", mutation_rate); println!("\tPopulation size = {}", population_size); println!("\tNumber of iterations = {}", iter_count); println!("\tTournament size = {}", tournament_size); } // RNG for the GA let rng: StdRng = match StdRng::new() { Ok(r) => r, Err(_) => panic!("failed to acquire RNG"), }; let mut pop = Population::new(population_size, Box::new(graph), mutation_rate, tournament_size, rng); let first_result = pop.fittest().total_weight; let mut best_result = pop.fittest(); if v_flag { println!("Fittest at start: {}", first_result) } // Evolve the population let t0 = precise_time_ns(); for _ in 0..iter_count { pop = pop.evolve(); let r = pop.fittest(); if r.total_weight < best_result.total_weight { best_result = r; } } let t1 = precise_time_ns(); // Show the end result and the time it took. println!("Resulting tour: {:?}\nwith weight {}", best_result.nodes, best_result.total_weight); if v_flag { let dt = ((t1 - t0) as f64) / 1e6; println!("t_avg = {} ms, t_overall = {} s", dt / iter_count as f64, dt / 1000.0); println!("Improvement factor from first solution: {}", (first_result / best_result.total_weight)); } }
{ 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; pub mod edge; pub mod graph; pub mod nodept; pub mod population; pub mod tour; // pub mod graphviz_conv; static DEFAULT_ITERS: usize = 800; static DEFAULT_MUT_RATE: f64 = 0.02; static DEFAULT_POP_SIZE: usize = 200; static DEFAULT_TOURNAMENT_SIZE: usize = 15; fn usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief[..])); } fn parse_opt<T: FromStr>(matches: &Matches, opt: &str, default: T) -> T
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)", "MUTRATE"); opts.optopt("i", "iters", "change the number of GA iterations (default: 50)", "ITERS"); opts.optopt("p", "pop_size", "change the population size (default: 5000)", "POPSIZE"); opts.optflag("v", "verbose", "print a lot of information, including timing."); opts.optopt("r", "read", "read graph from a.tsp file", "READ"); opts.optopt("t", "tournament_size", "change the number of specimens used for tournament selection", "TSIZE"); let matches = match opts.parse(args) { Ok(m) => m, Err(_) => panic!("Failed matching options"), }; if matches.opt_present("h") { usage(&program, opts); return; } let v_flag = matches.opt_present("v"); let node_count = 15; let tournament_size = parse_opt::<usize>(&matches, "t", DEFAULT_TOURNAMENT_SIZE); let scale = 200.0; let mutation_rate = parse_opt::<f64>(&matches, "m", DEFAULT_MUT_RATE); let iter_count = parse_opt::<usize>(&matches, "i", DEFAULT_ITERS); let population_size = parse_opt::<usize>(&matches, "p", DEFAULT_POP_SIZE); let graph; if matches.opt_present("r") { 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(); } 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!("Running TSP-GA on a graph with |N| = {}, |E| = {}", graph.num_nodes, graph.all_edges().len()); println!("GA parameters:"); println!("\tMutation rate = {}", mutation_rate); println!("\tPopulation size = {}", population_size); println!("\tNumber of iterations = {}", iter_count); println!("\tTournament size = {}", tournament_size); } // RNG for the GA let rng: StdRng = match StdRng::new() { Ok(r) => r, Err(_) => panic!("failed to acquire RNG"), }; let mut pop = Population::new(population_size, Box::new(graph), mutation_rate, tournament_size, rng); let first_result = pop.fittest().total_weight; let mut best_result = pop.fittest(); if v_flag { println!("Fittest at start: {}", first_result) } // Evolve the population let t0 = precise_time_ns(); for _ in 0..iter_count { pop = pop.evolve(); let r = pop.fittest(); if r.total_weight < best_result.total_weight { best_result = r; } } let t1 = precise_time_ns(); // Show the end result and the time it took. println!("Resulting tour: {:?}\nwith weight {}", best_result.nodes, best_result.total_weight); if v_flag { let dt = ((t1 - t0) as f64) / 1e6; println!("t_avg = {} ms, t_overall = {} s", dt / iter_count as f64, dt / 1000.0); println!("Improvement factor from first solution: {}", (first_result / best_result.total_weight)); } }
{ 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; pub mod edge; pub mod graph; pub mod nodept; pub mod population; pub mod tour; // pub mod graphviz_conv; static DEFAULT_ITERS: usize = 800; static DEFAULT_MUT_RATE: f64 = 0.02; static DEFAULT_POP_SIZE: usize = 200; static DEFAULT_TOURNAMENT_SIZE: usize = 15; fn usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief[..])); }
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 = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optopt("m", "mutation_rate", "change the mutation rate (default: 0.015)", "MUTRATE"); opts.optopt("i", "iters", "change the number of GA iterations (default: 50)", "ITERS"); opts.optopt("p", "pop_size", "change the population size (default: 5000)", "POPSIZE"); opts.optflag("v", "verbose", "print a lot of information, including timing."); opts.optopt("r", "read", "read graph from a.tsp file", "READ"); opts.optopt("t", "tournament_size", "change the number of specimens used for tournament selection", "TSIZE"); let matches = match opts.parse(args) { Ok(m) => m, Err(_) => panic!("Failed matching options"), }; if matches.opt_present("h") { usage(&program, opts); return; } let v_flag = matches.opt_present("v"); let node_count = 15; let tournament_size = parse_opt::<usize>(&matches, "t", DEFAULT_TOURNAMENT_SIZE); let scale = 200.0; let mutation_rate = parse_opt::<f64>(&matches, "m", DEFAULT_MUT_RATE); let iter_count = parse_opt::<usize>(&matches, "i", DEFAULT_ITERS); let population_size = parse_opt::<usize>(&matches, "p", DEFAULT_POP_SIZE); let graph; if matches.opt_present("r") { 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(); } 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!("Running TSP-GA on a graph with |N| = {}, |E| = {}", graph.num_nodes, graph.all_edges().len()); println!("GA parameters:"); println!("\tMutation rate = {}", mutation_rate); println!("\tPopulation size = {}", population_size); println!("\tNumber of iterations = {}", iter_count); println!("\tTournament size = {}", tournament_size); } // RNG for the GA let rng: StdRng = match StdRng::new() { Ok(r) => r, Err(_) => panic!("failed to acquire RNG"), }; let mut pop = Population::new(population_size, Box::new(graph), mutation_rate, tournament_size, rng); let first_result = pop.fittest().total_weight; let mut best_result = pop.fittest(); if v_flag { println!("Fittest at start: {}", first_result) } // Evolve the population let t0 = precise_time_ns(); for _ in 0..iter_count { pop = pop.evolve(); let r = pop.fittest(); if r.total_weight < best_result.total_weight { best_result = r; } } let t1 = precise_time_ns(); // Show the end result and the time it took. println!("Resulting tour: {:?}\nwith weight {}", best_result.nodes, best_result.total_weight); if v_flag { let dt = ((t1 - t0) as f64) / 1e6; println!("t_avg = {} ms, t_overall = {} s", dt / iter_count as f64, dt / 1000.0); println!("Improvement factor from first solution: {}", (first_result / best_result.total_weight)); } }
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(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()
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(XMM0)), operand2: Some(Indirect(RDI, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 7], OperandSize::Qword) }
{ 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, 248], OperandSize::Dword) }
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() { 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, 248], OperandSize::Dword) } 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(XMM0)), operand2: Some(Indirect(RDI, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 7], OperandSize::Qword) }
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(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
() { 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, 248], OperandSize::Dword) } 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(XMM0)), operand2: Some(Indirect(RDI, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 7], OperandSize::Qword) }
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: Vec<Fasta<DNA>> = parse_fastas(buffer.trim()); let mut sequence: Vec<RNA> = fastas[0].rna().collect(); for intron in &fastas[1..] { let intron_rna: Vec<RNA> = intron.rna().collect(); remove_intron(&mut sequence, &intron_rna); } let spliced = Fasta { id: fastas[0].id.clone(), sequence: sequence }; for aa in spliced.aa() { print!("{}", aa); } println!(""); } fn remove_intron(sequence: &mut Vec<RNA>, intron: &[RNA]) { // 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; } 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>(haystack: &[T], needle: &[T]) -> usize { let mut m = 0; let mut i = 0; let table = build_table(needle); while m + i < haystack.len() { if needle[i] == haystack[m+i] { if i + 1 == needle.len() { return m; } i = i + 1; } else { match table[i] { None => { m = m + 1; i = 0; }, Some(n) => { m = m + i - n; i = n; } } } } haystack.len() } fn build_table<T: Eq>(s: &[T]) -> Vec<Option<usize>> { match s.len() { 0 => Vec::new(), 1 => vec![None], _ => { // let chars: Vec<char> = s.chars().collect(); let mut table = Vec::new(); table.push(None); table.push(Some(0)); let mut pos = 2; let mut cnd = Some(0); while pos < s.len() { match cnd { None => {}, // should never happen Some(0) => { if &s[pos] == &s[0] { table.push(Some(1)); cnd = Some(1); } else { table.push(Some(0)); } pos = pos + 1; }, Some(n) => { if &s[pos] == &s[n] { table.push(Some(n + 1)); cnd = Some(n + 1); pos = pos + 1; } else { cnd = table[n]; } }, } } return table } }
}
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: Vec<Fasta<DNA>> = parse_fastas(buffer.trim()); let mut sequence: Vec<RNA> = fastas[0].rna().collect(); for intron in &fastas[1..] { let intron_rna: Vec<RNA> = intron.rna().collect(); remove_intron(&mut sequence, &intron_rna); } let spliced = Fasta { id: fastas[0].id.clone(), sequence: sequence }; for aa in spliced.aa() { print!("{}", aa); } println!(""); } fn remove_intron(sequence: &mut Vec<RNA>, intron: &[RNA]) { // 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; } 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>(haystack: &[T], needle: &[T]) -> usize { let mut m = 0; let mut i = 0; let table = build_table(needle); while m + i < haystack.len() { if needle[i] == haystack[m+i] { if i + 1 == needle.len() { return m; } i = i + 1; } else { match table[i] { None => { m = m + 1; i = 0; }, Some(n) => { m = m + i - n; i = n; } } } } haystack.len() } fn build_table<T: Eq>(s: &[T]) -> Vec<Option<usize>> { match s.len() { 0 => Vec::new(), 1 => vec![None], _ => { // let chars: Vec<char> = s.chars().collect(); let mut table = Vec::new(); table.push(None); table.push(Some(0)); let mut pos = 2; let mut cnd = Some(0); while pos < s.len() { match cnd { None => {}, // should never happen Some(0) => { if &s[pos] == &s[0] { table.push(Some(1)); cnd = Some(1); } else
pos = pos + 1; }, Some(n) => { if &s[pos] == &s[n] { table.push(Some(n + 1)); cnd = Some(n + 1); pos = pos + 1; } else { cnd = table[n]; } }, } } return table } } }
{ 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: Vec<Fasta<DNA>> = parse_fastas(buffer.trim()); let mut sequence: Vec<RNA> = fastas[0].rna().collect(); for intron in &fastas[1..] { let intron_rna: Vec<RNA> = intron.rna().collect(); remove_intron(&mut sequence, &intron_rna); } let spliced = Fasta { id: fastas[0].id.clone(), sequence: sequence }; for aa in spliced.aa() { print!("{}", aa); } println!(""); } fn remove_intron(sequence: &mut Vec<RNA>, intron: &[RNA]) { // 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; } fn
<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: &[T], needle: &[T]) -> usize { let mut m = 0; let mut i = 0; let table = build_table(needle); while m + i < haystack.len() { if needle[i] == haystack[m+i] { if i + 1 == needle.len() { return m; } i = i + 1; } else { match table[i] { None => { m = m + 1; i = 0; }, Some(n) => { m = m + i - n; i = n; } } } } haystack.len() } fn build_table<T: Eq>(s: &[T]) -> Vec<Option<usize>> { match s.len() { 0 => Vec::new(), 1 => vec![None], _ => { // let chars: Vec<char> = s.chars().collect(); let mut table = Vec::new(); table.push(None); table.push(Some(0)); let mut pos = 2; let mut cnd = Some(0); while pos < s.len() { match cnd { None => {}, // should never happen Some(0) => { if &s[pos] == &s[0] { table.push(Some(1)); cnd = Some(1); } else { table.push(Some(0)); } pos = pos + 1; }, Some(n) => { if &s[pos] == &s[n] { table.push(Some(n + 1)); cnd = Some(n + 1); pos = pos + 1; } else { cnd = table[n]; } }, } } return table } } }
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: Vec<Fasta<DNA>> = parse_fastas(buffer.trim()); let mut sequence: Vec<RNA> = fastas[0].rna().collect(); for intron in &fastas[1..] { let intron_rna: Vec<RNA> = intron.rna().collect(); remove_intron(&mut sequence, &intron_rna); } let spliced = Fasta { id: fastas[0].id.clone(), sequence: sequence }; for aa in spliced.aa() { print!("{}", aa); } println!(""); } fn remove_intron(sequence: &mut Vec<RNA>, intron: &[RNA])
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>(haystack: &[T], needle: &[T]) -> usize { let mut m = 0; let mut i = 0; let table = build_table(needle); while m + i < haystack.len() { if needle[i] == haystack[m+i] { if i + 1 == needle.len() { return m; } i = i + 1; } else { match table[i] { None => { m = m + 1; i = 0; }, Some(n) => { m = m + i - n; i = n; } } } } haystack.len() } fn build_table<T: Eq>(s: &[T]) -> Vec<Option<usize>> { match s.len() { 0 => Vec::new(), 1 => vec![None], _ => { // let chars: Vec<char> = s.chars().collect(); let mut table = Vec::new(); table.push(None); table.push(Some(0)); let mut pos = 2; let mut cnd = Some(0); while pos < s.len() { match cnd { None => {}, // should never happen Some(0) => { if &s[pos] == &s[0] { table.push(Some(1)); cnd = Some(1); } else { table.push(Some(0)); } pos = pos + 1; }, Some(n) => { if &s[pos] == &s[n] { table.push(Some(n + 1)); cnd = Some(n + 1); pos = pos + 1; } else { cnd = table[n]; } }, } } return table } } }
{ // 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 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 = 0 as *mut Context; { let contexts = contexts(); { let context_lock = contexts.current().expect("context::switch: not inside of context"); let mut context = context_lock.write(); from_ptr = context.deref_mut() as *mut Context; } 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 context.status == Status::Blocked && context.wake.is_some() { let wake = context.wake.expect("context::switch: wake not set"); let current = arch::time::monotonic(); if current.0 > wake.0 || (current.0 == wake.0 && current.1 >= wake.1) { context.unblock(); } } if context.cpu_id == Some(cpu_id) { if context.status == Status::Runnable &&! context.running { return true; } } false }; for (pid, context_lock) in contexts.iter() { if *pid > (*from_ptr).id
} 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 Context; break; } } } } }; if to_ptr as usize == 0 { // Unset global lock if no context found arch::context::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst); return false; } (&mut *from_ptr).running = false; (&mut *to_ptr).running = true; if let Some(ref stack) = (*to_ptr).kstack { arch::gdt::TSS.rsp[0] = (stack.as_ptr() as usize + stack.len() - 256) as u64; } CONTEXT_ID.store((&mut *to_ptr).id, Ordering::SeqCst); // 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); (&mut *from_ptr).arch.switch_to(&mut (&mut *to_ptr).arch); true }
{ 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 mut to_ptr = 0 as *mut Context; { let contexts = contexts(); { let context_lock = contexts.current().expect("context::switch: not inside of context"); let mut context = context_lock.write(); from_ptr = context.deref_mut() as *mut Context; } 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 context.status == Status::Blocked && context.wake.is_some() { let wake = context.wake.expect("context::switch: wake not set"); let current = arch::time::monotonic(); if current.0 > wake.0 || (current.0 == wake.0 && current.1 >= wake.1) { context.unblock(); } } if context.cpu_id == Some(cpu_id) { if context.status == Status::Runnable &&! context.running { return true; } } false }; 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 Context; break; } } } 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 Context; break; } } } } }; if to_ptr as usize == 0 { // Unset global lock if no context found arch::context::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst); return false; } (&mut *from_ptr).running = false; (&mut *to_ptr).running = true; if let Some(ref stack) = (*to_ptr).kstack { arch::gdt::TSS.rsp[0] = (stack.as_ptr() as usize + stack.len() - 256) as u64; } CONTEXT_ID.store((&mut *to_ptr).id, Ordering::SeqCst); // 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); (&mut *from_ptr).arch.switch_to(&mut (&mut *to_ptr).arch); true }
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 context.status == Status::Blocked && context.wake.is_some() { let wake = context.wake.expect("context::switch: wake not set"); let current = arch::time::monotonic(); if current.0 > wake.0 || (current.0 == wake.0 && current.1 >= wake.1) { context.unblock(); } } if context.cpu_id == Some(cpu_id) { if context.status == Status::Runnable &&! context.running { return true; } } false }; 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 Context; break; } } } 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 Context; break; } } } } }; if to_ptr as usize == 0 { // Unset global lock if no context found arch::context::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst); return false; } (&mut *from_ptr).running = false; (&mut *to_ptr).running = true; if let Some(ref stack) = (*to_ptr).kstack { arch::gdt::TSS.rsp[0] = (stack.as_ptr() as usize + stack.len() - 256) as u64; } CONTEXT_ID.store((&mut *to_ptr).id, Ordering::SeqCst); // 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); (&mut *from_ptr).arch.switch_to(&mut (&mut *to_ptr).arch); true }
{ 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 = 0 as *mut Context; { let contexts = contexts(); { let context_lock = contexts.current().expect("context::switch: not inside of context"); let mut context = context_lock.write(); from_ptr = context.deref_mut() as *mut Context; }
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 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 = 0 as *mut Context; { let contexts = contexts(); { let context_lock = contexts.current().expect("context::switch: not inside of context"); let mut context = context_lock.write(); from_ptr = context.deref_mut() as *mut Context; } 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 context.status == Status::Blocked && context.wake.is_some() { let wake = context.wake.expect("context::switch: wake not set"); let current = arch::time::monotonic(); if current.0 > wake.0 || (current.0 == wake.0 && current.1 >= wake.1) { context.unblock(); } } if context.cpu_id == Some(cpu_id) { if context.status == Status::Runnable &&! context.running { return true; } } false }; 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 Context; break; } } } 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 Context; break; } } } } }; if to_ptr as usize == 0 { // Unset global lock if no context found arch::context::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst); return false; } (&mut *from_ptr).running = false; (&mut *to_ptr).running = true; if let Some(ref stack) = (*to_ptr).kstack { arch::gdt::TSS.rsp[0] = (stack.as_ptr() as usize + stack.len() - 256) as u64; } CONTEXT_ID.store((&mut *to_ptr).id, Ordering::SeqCst);
(&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, tape: vec![0], } } fn get(&self) -> i32 { // SAFETY: `self.pos` is already checked in `self.next()` unsafe { *self.tape.get_unchecked(self.pos) } } fn get_mut(&mut self) -> &mut i32 { // SAFETY: `self.pos` is already checked in `self.next()` unsafe { self.tape.get_unchecked_mut(self.pos) } } fn
(&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); } } } struct Printer<'a> { output: StdoutLock<'a>, sum1: i32, sum2: i32, quiet: bool, } impl<'a> Printer<'a> { fn new(output: &'a Stdout, quiet: bool) -> Self { Self { output: output.lock(), sum1: 0, sum2: 0, quiet, } } fn print(&mut self, n: i32) { if self.quiet { self.sum1 = (self.sum1 + n) % 255; self.sum2 = (self.sum2 + self.sum1) % 255; } else { self.output.write_all(&[n as u8]).unwrap(); self.output.flush().unwrap(); } } const fn get_checksum(&self) -> i32 { (self.sum2 << 8) | self.sum1 } } fn run(program: &[Op], tape: &mut Tape, p: &mut Printer) { for op in program { match op { Op::Dec => tape.dec(), Op::Inc => tape.inc(), Op::Prev => tape.prev(), Op::Next => tape.next(), Op::Loop(program) => { while tape.get() > 0 { run(program, tape, p); } } Op::Print => p.print(tape.get()), } } } fn parse(it: &mut impl Iterator<Item = u8>) -> Box<[Op]> { let mut buf = vec![]; while let Some(c) = it.next() { buf.push(match c { b'-' => Op::Dec, b'+' => Op::Inc, b'<' => Op::Prev, b'>' => Op::Next, b'.' => Op::Print, b'[' => Op::Loop(parse(it)), b']' => break, _ => continue, }); } buf.into_boxed_slice() } struct Program { ops: Box<[Op]>, } impl Program { fn new(code: &[u8]) -> Self { Self { ops: parse(&mut code.iter().copied()), } } fn run(&self, p: &mut Printer) { let mut tape = Tape::new(); run(&self.ops, &mut tape, p); } } fn notify(msg: &str) { if let Ok(mut stream) = TcpStream::connect("localhost:9001") { stream.write_all(msg.as_bytes()).unwrap(); } } fn verify() { const S: &[u8] = b"++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>\ ---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; let left = { let output = io::stdout(); let mut p_left = Printer::new(&output, true); Program::new(S).run(&mut p_left); p_left.get_checksum() }; let right = { let output = io::stdout(); let mut p_right = Printer::new(&output, true); for &c in b"Hello World!\n" { p_right.print(c as i32); } p_right.get_checksum() }; if left!= right { eprintln!("{}!= {}", left, right); process::exit(-1); } } fn main() { verify(); let s = fs::read(env::args().nth(1).unwrap()).unwrap(); let output = io::stdout(); let mut p = Printer::new(&output, env::var("QUIET").is_ok()); notify(&format!("Rust\t{}", process::id())); Program::new(&s).run(&mut p); notify("stop"); if p.quiet { println!("Output checksum: {}", p.get_checksum()); } }
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, tape: vec![0], } } fn get(&self) -> i32 { // SAFETY: `self.pos` is already checked in `self.next()` unsafe { *self.tape.get_unchecked(self.pos) } } fn get_mut(&mut self) -> &mut i32 { // SAFETY: `self.pos` is already checked in `self.next()` unsafe { self.tape.get_unchecked_mut(self.pos) } } fn dec(&mut self) {
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>, sum1: i32, sum2: i32, quiet: bool, } impl<'a> Printer<'a> { fn new(output: &'a Stdout, quiet: bool) -> Self { Self { output: output.lock(), sum1: 0, sum2: 0, quiet, } } fn print(&mut self, n: i32) { if self.quiet { self.sum1 = (self.sum1 + n) % 255; self.sum2 = (self.sum2 + self.sum1) % 255; } else { self.output.write_all(&[n as u8]).unwrap(); self.output.flush().unwrap(); } } const fn get_checksum(&self) -> i32 { (self.sum2 << 8) | self.sum1 } } fn run(program: &[Op], tape: &mut Tape, p: &mut Printer) { for op in program { match op { Op::Dec => tape.dec(), Op::Inc => tape.inc(), Op::Prev => tape.prev(), Op::Next => tape.next(), Op::Loop(program) => { while tape.get() > 0 { run(program, tape, p); } } Op::Print => p.print(tape.get()), } } } fn parse(it: &mut impl Iterator<Item = u8>) -> Box<[Op]> { let mut buf = vec![]; while let Some(c) = it.next() { buf.push(match c { b'-' => Op::Dec, b'+' => Op::Inc, b'<' => Op::Prev, b'>' => Op::Next, b'.' => Op::Print, b'[' => Op::Loop(parse(it)), b']' => break, _ => continue, }); } buf.into_boxed_slice() } struct Program { ops: Box<[Op]>, } impl Program { fn new(code: &[u8]) -> Self { Self { ops: parse(&mut code.iter().copied()), } } fn run(&self, p: &mut Printer) { let mut tape = Tape::new(); run(&self.ops, &mut tape, p); } } fn notify(msg: &str) { if let Ok(mut stream) = TcpStream::connect("localhost:9001") { stream.write_all(msg.as_bytes()).unwrap(); } } fn verify() { const S: &[u8] = b"++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>\ ---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; let left = { let output = io::stdout(); let mut p_left = Printer::new(&output, true); Program::new(S).run(&mut p_left); p_left.get_checksum() }; let right = { let output = io::stdout(); let mut p_right = Printer::new(&output, true); for &c in b"Hello World!\n" { p_right.print(c as i32); } p_right.get_checksum() }; if left!= right { eprintln!("{}!= {}", left, right); process::exit(-1); } } fn main() { verify(); let s = fs::read(env::args().nth(1).unwrap()).unwrap(); let output = io::stdout(); let mut p = Printer::new(&output, env::var("QUIET").is_ok()); notify(&format!("Rust\t{}", process::id())); Program::new(&s).run(&mut p); notify("stop"); if p.quiet { println!("Output checksum: {}", p.get_checksum()); } }
*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; use crate::models::RuleAction; mod allow_all; mod identity_headers; mod oauth2_proxy; #[cfg(test)] pub mod tests; use self::identity_headers::IdentityHeaders; /// Interface to authentication implementations. #[async_trait::async_trait(?Send)] pub trait AuthenticationProxy { /// Check if the request is authenticated context. async fn check( &self, context: &RequestContext, request: &HttpRequest, ) -> Result<AuthenticationResult>; } /// Thread-safe logic to create thread-scoped `AuthenticationProxy` instances. /// /// Used by `AuthenticatorFactory` instances to create authentication proxy /// while reusing as much logic as possible. pub trait AuthenticationProxyFactory: Send + Sync { /// Return a new `AuthenticationProxy` instance. fn make(&self) -> Box<dyn AuthenticationProxy>; } /// Wrap logic around authentication proxy and rules engine. pub struct Authenticator { /// Headers to inject user identity information into. pub headers: IdentityHeaders, /// The Authenticator proxy to check requests with. proxy: Box<dyn AuthenticationProxy>, /// Rules engine to customise and enrich the authentication process. rules: RulesEngine, } impl Authenticator { /// Create an AuthenticatorFactory from configuration options. pub fn factory(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 oauth2_proxy) => Arc::new( self::oauth2_proxy::OAuth2ProxyFactory::from_config(oauth2_proxy), ), }; let headers = IdentityHeaders::from_config(&config.authenticator)?; let rules = RulesEngine::builder() .rule_files(&config.rule_files) .build()?; Ok(AuthenticatorFactory { factory, headers, rules, }) } /// 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 proxy = Box::new(authenticator); Authenticator { headers, proxy, rules, } } /// Check a request for valid authentication. pub async fn check( &self, context: &RequestContext<'_>, request: &HttpRequest, ) -> Result<AuthenticationResult> { // Process pre-authentication rules and exit early if possible. match self.rules.eval_preauth(context) { RuleAction::Allow => { let mut result = AuthenticationResult::allowed(); result.audit_reason = AuditReason::PreAuthAllowed; return self.rules.eval_enrich(context, result); } RuleAction::Delegate => (), RuleAction::Deny => { let mut result = AuthenticationResult::denied(); result.audit_reason = AuditReason::PreAuthDenied; return Ok(result); } }; // Authenticate against the AuthProxy, directing users to login if needed. let mut result = self.proxy.check(context, request).await?; if let AuthenticationStatus::MustLogin = result.status { return Ok(result); } // 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 = AuthenticationStatus::Allowed; } RuleAction::Delegate => (), RuleAction::Deny => { result.audit_reason = AuditReason::PostAuthDenied; result.status = AuthenticationStatus::Denied; } }; // Process enrich rules for allowed responses. self.rules.eval_enrich(context, result) }
} /// 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 AuthenticationProxyFactory>, headers: IdentityHeaders, rules: RulesEngine, } impl AuthenticatorFactory { /// Return a new `Authenticator` instance. pub fn make(&self) -> Authenticator { Authenticator { headers: self.headers.clone(), proxy: self.factory.make(), rules: self.rules.clone(), } } }
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; use crate::models::RuleAction; mod allow_all; mod identity_headers; mod oauth2_proxy; #[cfg(test)] pub mod tests; use self::identity_headers::IdentityHeaders; /// Interface to authentication implementations. #[async_trait::async_trait(?Send)] pub trait AuthenticationProxy { /// Check if the request is authenticated context. async fn check( &self, context: &RequestContext, request: &HttpRequest, ) -> Result<AuthenticationResult>; } /// Thread-safe logic to create thread-scoped `AuthenticationProxy` instances. /// /// Used by `AuthenticatorFactory` instances to create authentication proxy /// while reusing as much logic as possible. pub trait AuthenticationProxyFactory: Send + Sync { /// Return a new `AuthenticationProxy` instance. fn make(&self) -> Box<dyn AuthenticationProxy>; } /// Wrap logic around authentication proxy and rules engine. pub struct Authenticator { /// Headers to inject user identity information into. pub headers: IdentityHeaders, /// The Authenticator proxy to check requests with. proxy: Box<dyn AuthenticationProxy>, /// Rules engine to customise and enrich the authentication process. rules: RulesEngine, } impl Authenticator { /// Create an AuthenticatorFactory from configuration options. pub fn
(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 oauth2_proxy) => Arc::new( self::oauth2_proxy::OAuth2ProxyFactory::from_config(oauth2_proxy), ), }; let headers = IdentityHeaders::from_config(&config.authenticator)?; let rules = RulesEngine::builder() .rule_files(&config.rule_files) .build()?; Ok(AuthenticatorFactory { factory, headers, rules, }) } /// 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 proxy = Box::new(authenticator); Authenticator { headers, proxy, rules, } } /// Check a request for valid authentication. pub async fn check( &self, context: &RequestContext<'_>, request: &HttpRequest, ) -> Result<AuthenticationResult> { // Process pre-authentication rules and exit early if possible. match self.rules.eval_preauth(context) { RuleAction::Allow => { let mut result = AuthenticationResult::allowed(); result.audit_reason = AuditReason::PreAuthAllowed; return self.rules.eval_enrich(context, result); } RuleAction::Delegate => (), RuleAction::Deny => { let mut result = AuthenticationResult::denied(); result.audit_reason = AuditReason::PreAuthDenied; return Ok(result); } }; // Authenticate against the AuthProxy, directing users to login if needed. let mut result = self.proxy.check(context, request).await?; if let AuthenticationStatus::MustLogin = result.status { return Ok(result); } // 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 = AuthenticationStatus::Allowed; } RuleAction::Delegate => (), RuleAction::Deny => { result.audit_reason = AuditReason::PostAuthDenied; result.status = AuthenticationStatus::Denied; } }; // Process enrich rules for allowed responses. self.rules.eval_enrich(context, result) } } /// 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 AuthenticationProxyFactory>, headers: IdentityHeaders, rules: RulesEngine, } impl AuthenticatorFactory { /// Return a new `Authenticator` instance. pub fn make(&self) -> Authenticator { Authenticator { headers: self.headers.clone(), proxy: self.factory.make(), rules: self.rules.clone(), } } }
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; use crate::models::RuleAction; mod allow_all; mod identity_headers; mod oauth2_proxy; #[cfg(test)] pub mod tests; use self::identity_headers::IdentityHeaders; /// Interface to authentication implementations. #[async_trait::async_trait(?Send)] pub trait AuthenticationProxy { /// Check if the request is authenticated context. async fn check( &self, context: &RequestContext, request: &HttpRequest, ) -> Result<AuthenticationResult>; } /// Thread-safe logic to create thread-scoped `AuthenticationProxy` instances. /// /// Used by `AuthenticatorFactory` instances to create authentication proxy /// while reusing as much logic as possible. pub trait AuthenticationProxyFactory: Send + Sync { /// Return a new `AuthenticationProxy` instance. fn make(&self) -> Box<dyn AuthenticationProxy>; } /// Wrap logic around authentication proxy and rules engine. pub struct Authenticator { /// Headers to inject user identity information into. pub headers: IdentityHeaders, /// The Authenticator proxy to check requests with. proxy: Box<dyn AuthenticationProxy>, /// Rules engine to customise and enrich the authentication process. rules: RulesEngine, } impl Authenticator { /// Create an AuthenticatorFactory from configuration options. pub fn factory(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 oauth2_proxy) => Arc::new( self::oauth2_proxy::OAuth2ProxyFactory::from_config(oauth2_proxy), ), }; let headers = IdentityHeaders::from_config(&config.authenticator)?; let rules = RulesEngine::builder() .rule_files(&config.rule_files) .build()?; Ok(AuthenticatorFactory { factory, headers, rules, }) } /// 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 proxy = Box::new(authenticator); Authenticator { headers, proxy, rules, } } /// Check a request for valid authentication. pub async fn check( &self, context: &RequestContext<'_>, request: &HttpRequest, ) -> Result<AuthenticationResult> { // Process pre-authentication rules and exit early if possible. match self.rules.eval_preauth(context) { RuleAction::Allow => { let mut result = AuthenticationResult::allowed(); result.audit_reason = AuditReason::PreAuthAllowed; return self.rules.eval_enrich(context, result); } RuleAction::Delegate => (), RuleAction::Deny => { let mut result = AuthenticationResult::denied(); result.audit_reason = AuditReason::PreAuthDenied; return Ok(result); } }; // Authenticate against the AuthProxy, directing users to login if needed. let mut result = self.proxy.check(context, request).await?; if let AuthenticationStatus::MustLogin = result.status
// 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 = AuthenticationStatus::Allowed; } RuleAction::Delegate => (), RuleAction::Deny => { result.audit_reason = AuditReason::PostAuthDenied; result.status = AuthenticationStatus::Denied; } }; // Process enrich rules for allowed responses. self.rules.eval_enrich(context, result) } } /// 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 AuthenticationProxyFactory>, headers: IdentityHeaders, rules: RulesEngine, } impl AuthenticatorFactory { /// Return a new `Authenticator` instance. pub fn make(&self) -> Authenticator { Authenticator { headers: self.headers.clone(), proxy: self.factory.make(), rules: self.rules.clone(), } } }
{ 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; use crate::models::RuleAction; mod allow_all; mod identity_headers; mod oauth2_proxy; #[cfg(test)] pub mod tests; use self::identity_headers::IdentityHeaders; /// Interface to authentication implementations. #[async_trait::async_trait(?Send)] pub trait AuthenticationProxy { /// Check if the request is authenticated context. async fn check( &self, context: &RequestContext, request: &HttpRequest, ) -> Result<AuthenticationResult>; } /// Thread-safe logic to create thread-scoped `AuthenticationProxy` instances. /// /// Used by `AuthenticatorFactory` instances to create authentication proxy /// while reusing as much logic as possible. pub trait AuthenticationProxyFactory: Send + Sync { /// Return a new `AuthenticationProxy` instance. fn make(&self) -> Box<dyn AuthenticationProxy>; } /// Wrap logic around authentication proxy and rules engine. pub struct Authenticator { /// Headers to inject user identity information into. pub headers: IdentityHeaders, /// The Authenticator proxy to check requests with. proxy: Box<dyn AuthenticationProxy>, /// Rules engine to customise and enrich the authentication process. rules: RulesEngine, } impl Authenticator { /// Create an AuthenticatorFactory from configuration options. pub fn factory(config: &Config) -> Result<AuthenticatorFactory>
/// 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 proxy = Box::new(authenticator); Authenticator { headers, proxy, rules, } } /// Check a request for valid authentication. pub async fn check( &self, context: &RequestContext<'_>, request: &HttpRequest, ) -> Result<AuthenticationResult> { // Process pre-authentication rules and exit early if possible. match self.rules.eval_preauth(context) { RuleAction::Allow => { let mut result = AuthenticationResult::allowed(); result.audit_reason = AuditReason::PreAuthAllowed; return self.rules.eval_enrich(context, result); } RuleAction::Delegate => (), RuleAction::Deny => { let mut result = AuthenticationResult::denied(); result.audit_reason = AuditReason::PreAuthDenied; return Ok(result); } }; // Authenticate against the AuthProxy, directing users to login if needed. let mut result = self.proxy.check(context, request).await?; if let AuthenticationStatus::MustLogin = result.status { return Ok(result); } // 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 = AuthenticationStatus::Allowed; } RuleAction::Delegate => (), RuleAction::Deny => { result.audit_reason = AuditReason::PostAuthDenied; result.status = AuthenticationStatus::Denied; } }; // Process enrich rules for allowed responses. self.rules.eval_enrich(context, result) } } /// 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 AuthenticationProxyFactory>, headers: IdentityHeaders, rules: RulesEngine, } impl AuthenticatorFactory { /// Return a new `Authenticator` instance. pub fn make(&self) -> Authenticator { Authenticator { headers: self.headers.clone(), proxy: self.factory.make(), rules: self.rules.clone(), } } }
{ 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::oauth2_proxy::OAuth2ProxyFactory::from_config(oauth2_proxy), ), }; let headers = IdentityHeaders::from_config(&config.authenticator)?; let rules = RulesEngine::builder() .rule_files(&config.rule_files) .build()?; Ok(AuthenticatorFactory { factory, headers, rules, }) }
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 dom::bindings::codegen::FormDataBinding; use dom::bindings::js::JS; use dom::blob::Blob; use dom::htmlformelement::HTMLFormElement; use dom::window::Window; use servo_util::str::DOMString; use collections::hashmap::HashMap; #[deriving(Encodable)] pub enum FormDatum { StringData(DOMString), BlobData { blob: JS<Blob>, name: DOMString } } #[deriving(Encodable)] pub struct FormData { data: HashMap<DOMString, FormDatum>, reflector_: Reflector, window: JS<Window>, form: Option<JS<HTMLFormElement>> } impl FormData { pub fn new_inherited(form: Option<JS<HTMLFormElement>>, window: JS<Window>) -> FormData { FormData { data: HashMap::new(), reflector_: Reflector::new(), window: window, form: form } } pub fn new(form: Option<JS<HTMLFormElement>>, window: &JS<Window>) -> JS<FormData> { reflect_dom_object(~FormData::new_inherited(form, window.clone()), window, FormDataBinding::Wrap) } pub fn Constructor(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>)
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 self.reflector_ } }
{ 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 dom::bindings::codegen::FormDataBinding; use dom::bindings::js::JS; use dom::blob::Blob; use dom::htmlformelement::HTMLFormElement; use dom::window::Window; use servo_util::str::DOMString; use collections::hashmap::HashMap; #[deriving(Encodable)] pub enum FormDatum { StringData(DOMString), BlobData { blob: JS<Blob>, name: DOMString } } #[deriving(Encodable)] pub struct FormData { data: HashMap<DOMString, FormDatum>, reflector_: Reflector, window: JS<Window>, form: Option<JS<HTMLFormElement>> } impl FormData { pub fn new_inherited(form: Option<JS<HTMLFormElement>>, window: JS<Window>) -> FormData { FormData { data: HashMap::new(), reflector_: Reflector::new(), window: window, form: form } } pub fn new(form: Option<JS<HTMLFormElement>>, window: &JS<Window>) -> JS<FormData> { reflect_dom_object(~FormData::new_inherited(form, window.clone()), window, FormDataBinding::Wrap) } pub fn
(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(), name: filename.unwrap_or(~"default") }; self.data.insert(name.clone(), blob); } 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 self.reflector_ } }
Constructor
identifier_name