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
format.rs
use super::{ Attributes, Data, Event, EventFormatDeserializerV03, EventFormatDeserializerV10, EventFormatSerializerV03, EventFormatSerializerV10, }; use crate::event::{AttributesReader, ExtensionValue}; use serde::de::{Error, IntoDeserializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::{Map, Value}; use std::collections::HashMap; macro_rules! parse_field { ($value:expr, $target_type:ty, $error:ty) => { <$target_type>::deserialize($value.into_deserializer()).map_err(<$error>::custom) }; ($value:expr, $target_type:ty, $error:ty, $mapper:expr) => { <$target_type>::deserialize($value.into_deserializer()) .map_err(<$error>::custom) .and_then(|v| $mapper(v).map_err(<$error>::custom)) }; } macro_rules! extract_optional_field { ($map:ident, $name:literal, $target_type:ty, $error:ty) => { $map.remove($name) .filter(|v|!v.is_null()) .map(|v| parse_field!(v, $target_type, $error)) .transpose() }; ($map:ident, $name:literal, $target_type:ty, $error:ty, $mapper:expr) => { $map.remove($name) .filter(|v|!v.is_null()) .map(|v| parse_field!(v, $target_type, $error, $mapper)) .transpose() }; } macro_rules! extract_field { ($map:ident, $name:literal, $target_type:ty, $error:ty) => { extract_optional_field!($map, $name, $target_type, $error)? .ok_or_else(|| <$error>::missing_field($name)) }; ($map:ident, $name:literal, $target_type:ty, $error:ty, $mapper:expr) => { extract_optional_field!($map, $name, $target_type, $error, $mapper)? .ok_or_else(|| <$error>::missing_field($name)) }; } pub fn parse_data_json<E: serde::de::Error>(v: Value) -> Result<Value, E> { Value::deserialize(v.into_deserializer()).map_err(E::custom) } pub fn parse_data_string<E: serde::de::Error>(v: Value) -> Result<String, E> { parse_field!(v, String, E) } pub fn parse_data_base64<E: serde::de::Error>(v: Value) -> Result<Vec<u8>, E> { parse_field!(v, String, E).and_then(|s| { base64::decode(&s).map_err(|e| E::custom(format_args!("decode error `{}`", e))) }) } pub fn parse_data_base64_json<E: serde::de::Error>(v: Value) -> Result<Value, E> { let data = parse_data_base64(v)?; serde_json::from_slice(&data).map_err(E::custom) } pub(crate) trait EventFormatDeserializer {
map: &mut Map<String, Value>, ) -> Result<Attributes, E>; fn deserialize_data<E: serde::de::Error>( content_type: &str, map: &mut Map<String, Value>, ) -> Result<Option<Data>, E>; fn deserialize_event<E: serde::de::Error>(mut map: Map<String, Value>) -> Result<Event, E> { let attributes = Self::deserialize_attributes(&mut map)?; let data = Self::deserialize_data( attributes.datacontenttype().unwrap_or("application/json"), &mut map, )?; let extensions = map .into_iter() .filter(|v|!v.1.is_null()) .map(|(k, v)| { Ok(( k, ExtensionValue::deserialize(v.into_deserializer()).map_err(E::custom)?, )) }) .collect::<Result<HashMap<String, ExtensionValue>, E>>()?; Ok(Event { attributes, data, extensions, }) } } pub(crate) trait EventFormatSerializer<S: Serializer, A: Sized> { fn serialize( attributes: &A, data: &Option<Data>, extensions: &HashMap<String, ExtensionValue>, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>; } impl<'de> Deserialize<'de> for Event { fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where D: Deserializer<'de>, { let root_value = Value::deserialize(deserializer)?; let mut map: Map<String, Value> = Map::deserialize(root_value.into_deserializer()).map_err(D::Error::custom)?; match extract_field!(map, "specversion", String, <D as Deserializer<'de>>::Error)?.as_str() { "0.3" => EventFormatDeserializerV03::deserialize_event(map), "1.0" => EventFormatDeserializerV10::deserialize_event(map), s => Err(D::Error::unknown_variant( s, &super::spec_version::SPEC_VERSIONS, )), } } } impl Serialize for Event { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { match &self.attributes { Attributes::V03(a) => { EventFormatSerializerV03::serialize(a, &self.data, &self.extensions, serializer) } Attributes::V10(a) => { EventFormatSerializerV10::serialize(a, &self.data, &self.extensions, serializer) } } } }
fn deserialize_attributes<E: serde::de::Error>(
random_line_split
clear.rs
use fbo::{self, ValidatedAttachments}; use context::Context; use ContextExt; use Rect; use Surface; use Api; use version::Version; use gl; pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>, rect: Option<&Rect>, color: Option<(f32, f32, f32, f32)>, depth: Option<f32>, stencil: Option<i32>) { unsafe { let mut ctxt = context.make_current(); let fbo_id = context.get_framebuffer_objects() .get_framebuffer_for_drawing(framebuffer, &mut ctxt); fbo::bind_framebuffer(&mut ctxt, fbo_id, true, false); if ctxt.state.enabled_rasterizer_discard { ctxt.gl.Disable(gl::RASTERIZER_DISCARD); ctxt.state.enabled_rasterizer_discard = false; } if ctxt.state.color_mask!= (1, 1, 1, 1) { ctxt.state.color_mask = (1, 1, 1, 1); ctxt.gl.ColorMask(1, 1, 1, 1); } if let Some(_) = ctxt.state.conditional_render { if ctxt.version >= &Version(Api::Gl, 3, 0) { ctxt.gl.EndConditionalRender(); } else if ctxt.extensions.gl_nv_conditional_render { ctxt.gl.EndConditionalRenderNV(); } else { unreachable!(); } ctxt.state.conditional_render = None; } if let Some(rect) = rect { let rect = (rect.left as gl::types::GLint, rect.bottom as gl::types::GLint, rect.width as gl::types::GLsizei, rect.height as gl::types::GLsizei); if ctxt.state.scissor!= Some(rect) { ctxt.gl.Scissor(rect.0, rect.1, rect.2, rect.3); ctxt.state.scissor = Some(rect); } if!ctxt.state.enabled_scissor_test { ctxt.gl.Enable(gl::SCISSOR_TEST); ctxt.state.enabled_scissor_test = true; } } else { if ctxt.state.enabled_scissor_test { ctxt.gl.Disable(gl::SCISSOR_TEST); ctxt.state.enabled_scissor_test = false; } } let mut flags = 0; if let Some(color) = color { let color = (color.0 as gl::types::GLclampf, color.1 as gl::types::GLclampf, color.2 as gl::types::GLclampf, color.3 as gl::types::GLclampf); flags |= gl::COLOR_BUFFER_BIT; if ctxt.state.clear_color!= color { ctxt.gl.ClearColor(color.0, color.1, color.2, color.3); ctxt.state.clear_color = color; } } if let Some(depth) = depth { let depth = depth as gl::types::GLclampf; flags |= gl::DEPTH_BUFFER_BIT; if ctxt.state.clear_depth!= depth { if ctxt.version >= &Version(Api::Gl, 1, 0) { ctxt.gl.ClearDepth(depth as gl::types::GLclampd); } else if ctxt.version >= &Version(Api::GlEs, 2, 0) { ctxt.gl.ClearDepthf(depth); } else { unreachable!(); } ctxt.state.clear_depth = depth; } if!ctxt.state.depth_mask
} if let Some(stencil) = stencil { let stencil = stencil as gl::types::GLint; flags |= gl::STENCIL_BUFFER_BIT; if ctxt.state.clear_stencil!= stencil { ctxt.gl.ClearStencil(stencil); ctxt.state.clear_stencil = stencil; } } ctxt.gl.Clear(flags); } }
{ ctxt.gl.DepthMask(gl::TRUE); ctxt.state.depth_mask = true; }
conditional_block
clear.rs
use fbo::{self, ValidatedAttachments}; use context::Context; use ContextExt; use Rect; use Surface; use Api; use version::Version; use gl; pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>, rect: Option<&Rect>, color: Option<(f32, f32, f32, f32)>, depth: Option<f32>, stencil: Option<i32>)
if ctxt.version >= &Version(Api::Gl, 3, 0) { ctxt.gl.EndConditionalRender(); } else if ctxt.extensions.gl_nv_conditional_render { ctxt.gl.EndConditionalRenderNV(); } else { unreachable!(); } ctxt.state.conditional_render = None; } if let Some(rect) = rect { let rect = (rect.left as gl::types::GLint, rect.bottom as gl::types::GLint, rect.width as gl::types::GLsizei, rect.height as gl::types::GLsizei); if ctxt.state.scissor!= Some(rect) { ctxt.gl.Scissor(rect.0, rect.1, rect.2, rect.3); ctxt.state.scissor = Some(rect); } if!ctxt.state.enabled_scissor_test { ctxt.gl.Enable(gl::SCISSOR_TEST); ctxt.state.enabled_scissor_test = true; } } else { if ctxt.state.enabled_scissor_test { ctxt.gl.Disable(gl::SCISSOR_TEST); ctxt.state.enabled_scissor_test = false; } } let mut flags = 0; if let Some(color) = color { let color = (color.0 as gl::types::GLclampf, color.1 as gl::types::GLclampf, color.2 as gl::types::GLclampf, color.3 as gl::types::GLclampf); flags |= gl::COLOR_BUFFER_BIT; if ctxt.state.clear_color!= color { ctxt.gl.ClearColor(color.0, color.1, color.2, color.3); ctxt.state.clear_color = color; } } if let Some(depth) = depth { let depth = depth as gl::types::GLclampf; flags |= gl::DEPTH_BUFFER_BIT; if ctxt.state.clear_depth!= depth { if ctxt.version >= &Version(Api::Gl, 1, 0) { ctxt.gl.ClearDepth(depth as gl::types::GLclampd); } else if ctxt.version >= &Version(Api::GlEs, 2, 0) { ctxt.gl.ClearDepthf(depth); } else { unreachable!(); } ctxt.state.clear_depth = depth; } if!ctxt.state.depth_mask { ctxt.gl.DepthMask(gl::TRUE); ctxt.state.depth_mask = true; } } if let Some(stencil) = stencil { let stencil = stencil as gl::types::GLint; flags |= gl::STENCIL_BUFFER_BIT; if ctxt.state.clear_stencil!= stencil { ctxt.gl.ClearStencil(stencil); ctxt.state.clear_stencil = stencil; } } ctxt.gl.Clear(flags); } }
{ unsafe { let mut ctxt = context.make_current(); let fbo_id = context.get_framebuffer_objects() .get_framebuffer_for_drawing(framebuffer, &mut ctxt); fbo::bind_framebuffer(&mut ctxt, fbo_id, true, false); if ctxt.state.enabled_rasterizer_discard { ctxt.gl.Disable(gl::RASTERIZER_DISCARD); ctxt.state.enabled_rasterizer_discard = false; } if ctxt.state.color_mask != (1, 1, 1, 1) { ctxt.state.color_mask = (1, 1, 1, 1); ctxt.gl.ColorMask(1, 1, 1, 1); } if let Some(_) = ctxt.state.conditional_render {
identifier_body
clear.rs
use fbo::{self, ValidatedAttachments}; use context::Context; use ContextExt; use Rect; use Surface; use Api; use version::Version; use gl; pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>, rect: Option<&Rect>, color: Option<(f32, f32, f32, f32)>, depth: Option<f32>, stencil: Option<i32>)
{ unsafe { let mut ctxt = context.make_current(); let fbo_id = context.get_framebuffer_objects() .get_framebuffer_for_drawing(framebuffer, &mut ctxt); fbo::bind_framebuffer(&mut ctxt, fbo_id, true, false); if ctxt.state.enabled_rasterizer_discard { ctxt.gl.Disable(gl::RASTERIZER_DISCARD); ctxt.state.enabled_rasterizer_discard = false; } if ctxt.state.color_mask!= (1, 1, 1, 1) { ctxt.state.color_mask = (1, 1, 1, 1); ctxt.gl.ColorMask(1, 1, 1, 1); } if let Some(_) = ctxt.state.conditional_render { if ctxt.version >= &Version(Api::Gl, 3, 0) { ctxt.gl.EndConditionalRender(); } else if ctxt.extensions.gl_nv_conditional_render { ctxt.gl.EndConditionalRenderNV(); } else { unreachable!(); } ctxt.state.conditional_render = None; } if let Some(rect) = rect { let rect = (rect.left as gl::types::GLint, rect.bottom as gl::types::GLint, rect.width as gl::types::GLsizei, rect.height as gl::types::GLsizei); if ctxt.state.scissor!= Some(rect) { ctxt.gl.Scissor(rect.0, rect.1, rect.2, rect.3); ctxt.state.scissor = Some(rect); } if!ctxt.state.enabled_scissor_test { ctxt.gl.Enable(gl::SCISSOR_TEST); ctxt.state.enabled_scissor_test = true; } } else { if ctxt.state.enabled_scissor_test { ctxt.gl.Disable(gl::SCISSOR_TEST); ctxt.state.enabled_scissor_test = false; } } let mut flags = 0; if let Some(color) = color { let color = (color.0 as gl::types::GLclampf, color.1 as gl::types::GLclampf, color.2 as gl::types::GLclampf, color.3 as gl::types::GLclampf); flags |= gl::COLOR_BUFFER_BIT; if ctxt.state.clear_color!= color { ctxt.gl.ClearColor(color.0, color.1, color.2, color.3); ctxt.state.clear_color = color; } } if let Some(depth) = depth { let depth = depth as gl::types::GLclampf; flags |= gl::DEPTH_BUFFER_BIT; if ctxt.state.clear_depth!= depth { if ctxt.version >= &Version(Api::Gl, 1, 0) { ctxt.gl.ClearDepth(depth as gl::types::GLclampd); } else if ctxt.version >= &Version(Api::GlEs, 2, 0) { ctxt.gl.ClearDepthf(depth); } else { unreachable!(); } ctxt.state.clear_depth = depth; } if!ctxt.state.depth_mask { ctxt.gl.DepthMask(gl::TRUE); ctxt.state.depth_mask = true; } } if let Some(stencil) = stencil { let stencil = stencil as gl::types::GLint; flags |= gl::STENCIL_BUFFER_BIT; if ctxt.state.clear_stencil!= stencil { ctxt.gl.ClearStencil(stencil); ctxt.state.clear_stencil = stencil; } } ctxt.gl.Clear(flags); } }
random_line_split
clear.rs
use fbo::{self, ValidatedAttachments}; use context::Context; use ContextExt; use Rect; use Surface; use Api; use version::Version; use gl; pub fn
(context: &Context, framebuffer: Option<&ValidatedAttachments>, rect: Option<&Rect>, color: Option<(f32, f32, f32, f32)>, depth: Option<f32>, stencil: Option<i32>) { unsafe { let mut ctxt = context.make_current(); let fbo_id = context.get_framebuffer_objects() .get_framebuffer_for_drawing(framebuffer, &mut ctxt); fbo::bind_framebuffer(&mut ctxt, fbo_id, true, false); if ctxt.state.enabled_rasterizer_discard { ctxt.gl.Disable(gl::RASTERIZER_DISCARD); ctxt.state.enabled_rasterizer_discard = false; } if ctxt.state.color_mask!= (1, 1, 1, 1) { ctxt.state.color_mask = (1, 1, 1, 1); ctxt.gl.ColorMask(1, 1, 1, 1); } if let Some(_) = ctxt.state.conditional_render { if ctxt.version >= &Version(Api::Gl, 3, 0) { ctxt.gl.EndConditionalRender(); } else if ctxt.extensions.gl_nv_conditional_render { ctxt.gl.EndConditionalRenderNV(); } else { unreachable!(); } ctxt.state.conditional_render = None; } if let Some(rect) = rect { let rect = (rect.left as gl::types::GLint, rect.bottom as gl::types::GLint, rect.width as gl::types::GLsizei, rect.height as gl::types::GLsizei); if ctxt.state.scissor!= Some(rect) { ctxt.gl.Scissor(rect.0, rect.1, rect.2, rect.3); ctxt.state.scissor = Some(rect); } if!ctxt.state.enabled_scissor_test { ctxt.gl.Enable(gl::SCISSOR_TEST); ctxt.state.enabled_scissor_test = true; } } else { if ctxt.state.enabled_scissor_test { ctxt.gl.Disable(gl::SCISSOR_TEST); ctxt.state.enabled_scissor_test = false; } } let mut flags = 0; if let Some(color) = color { let color = (color.0 as gl::types::GLclampf, color.1 as gl::types::GLclampf, color.2 as gl::types::GLclampf, color.3 as gl::types::GLclampf); flags |= gl::COLOR_BUFFER_BIT; if ctxt.state.clear_color!= color { ctxt.gl.ClearColor(color.0, color.1, color.2, color.3); ctxt.state.clear_color = color; } } if let Some(depth) = depth { let depth = depth as gl::types::GLclampf; flags |= gl::DEPTH_BUFFER_BIT; if ctxt.state.clear_depth!= depth { if ctxt.version >= &Version(Api::Gl, 1, 0) { ctxt.gl.ClearDepth(depth as gl::types::GLclampd); } else if ctxt.version >= &Version(Api::GlEs, 2, 0) { ctxt.gl.ClearDepthf(depth); } else { unreachable!(); } ctxt.state.clear_depth = depth; } if!ctxt.state.depth_mask { ctxt.gl.DepthMask(gl::TRUE); ctxt.state.depth_mask = true; } } if let Some(stencil) = stencil { let stencil = stencil as gl::types::GLint; flags |= gl::STENCIL_BUFFER_BIT; if ctxt.state.clear_stencil!= stencil { ctxt.gl.ClearStencil(stencil); ctxt.state.clear_stencil = stencil; } } ctxt.gl.Clear(flags); } }
clear
identifier_name
imp.rs
use glib::prelude::*; use glib::subclass::prelude::*; use gst::prelude::*; use gst::subclass::prelude::*; use std::ffi::CString; use std::os::raw::c_char; use std::sync::Mutex; pub use gstreamer_rtp::rtp_buffer::compare_seqnum; pub use gstreamer_rtp::rtp_buffer::RTPBuffer; pub use gstreamer_rtp::rtp_buffer::RTPBufferExt; extern crate gstreamer_video as gstv; use once_cell::sync::Lazy; const DEFAULT_BITRATE: u32 = 1000; // Property value storage #[derive(Debug, Clone)] struct Settings { params: Option<String>, bitrate: u32, } impl Default for Settings { fn default() -> Self { Settings { params: None, bitrate: DEFAULT_BITRATE, } } } // static STREAMTX_PTR: Option<&Screamtxbw> = None; // Struct containing all the element data #[repr(C)] pub struct Screamtxbw { srcpad: gst::Pad, sinkpad: gst::Pad, settings: Mutex<Settings>, } static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| { gst::DebugCategory::new( "screamtxbw", gst::DebugColorFlags::empty(), Some("Screamtxbw Element"), ) }); impl Screamtxbw { // Called whenever a new buffer is passed to our sink pad. Here buffers should be processed and // whenever some output buffer is available have to push it out of the source pad. // Here we just pass through all buffers directly // // See the documentation of gst::Buffer and gst::BufferRef to see what can be done with // buffers. fn sink_chain( &self, _pad: &gst::Pad, _element: &super::Screamtxbw, _buffer: gst::Buffer, ) -> Result<gst::FlowSuccess, gst::FlowError> { glib::bitflags::_core::result::Result::Ok(gst::FlowSuccess::Ok) } // Called whenever an event arrives on the sink pad. It has to be handled accordingly and in // most cases has to be either passed to Pad::event_default() on this pad for default handling, // or Pad::push_event() on all pads with the opposite direction for direct forwarding. // Here we just pass through all events directly to the source pad. // // See the documentation of gst::Event and gst::EventRef to see what can be done with // events, and especially the gst::EventView type for inspecting events. fn sink_event(&self, pad: &gst::Pad, _element: &super::Screamtxbw, event: gst::Event) -> bool { gst_log!( CAT, obj: pad, "gstscream Handling event {:?} {:?}", event, event.type_() ); // println!("gstscream Handling sink event {:?}", event); self.srcpad.push_event(event) } // Called whenever a query is sent to the sink pad. It has to be answered if the element can // handle it, potentially by forwarding the query first to the peer pads of the pads with the // opposite direction, or false has to be returned. Default handling can be achieved with // Pad::query_default() on this pad and forwarding with Pad::peer_query() on the pads with the // opposite direction. // Here we just forward all queries directly to the source pad's peers. // // See the documentation of gst::Query and gst::QueryRef to see what can be done with // queries, and especially the gst::QueryView type for inspecting and modifying queries. fn sink_query( &self, pad: &gst::Pad, _element: &super::Screamtxbw, query: &mut gst::QueryRef, ) -> bool { gst_log!(CAT, obj: pad, "gstscream Handling query {:?}", query); self.srcpad.peer_query(query) } // Called whenever an event arrives on the source pad. It has to be handled accordingly and in // most cases has to be either passed to Pad::event_default() on the same pad for default // handling, or Pad::push_event() on all pads with the opposite direction for direct // forwarding. // Here we just pass through all events directly to the sink pad. // // See the documentation of gst::Event and gst::EventRef to see what can be done with // events, and especially the gst::EventView type for inspecting events. fn src_event(&self, pad: &gst::Pad, _element: &super::Screamtxbw, event: gst::Event) -> bool { if event.structure().unwrap().name() == "GstForceKeyUnit" { unsafe { ScreamTxBwPluginSetForceKeyUnit(); } gst_info!( CAT, obj: pad, "gstscreamtxbw src Handling event {:?} {:?}", event, event.type_() ); } gst_log!( CAT, obj: pad, "gstscream src Handling event {:?} {:?}", event, event.type_() ); self.sinkpad.push_event(event) } // Called whenever a query is sent to the source pad. It has to be answered if the element can // handle it, potentially by forwarding the query first to the peer pads of the pads with the // opposite direction, or false has to be returned. Default handling can be achieved with // Pad::query_default() on this pad and forwarding with Pad::peer_query() on the pads with the // opposite direction. // Here we just forward all queries directly to the sink pad's peers. // // See the documentation of gst::Query and gst::QueryRef to see what can be done with // queries, and especially the gst::QueryView type for inspecting and modifying queries. fn src_query( &self, pad: &gst::Pad, _element: &super::Screamtxbw, query: &mut gst::QueryRef, ) -> bool { gst_log!(CAT, obj: pad, "gstscream Handling src query {:?}", query); self.sinkpad.peer_query(query) } } extern "C" fn callback( stx: *const Screamtxbw, len: u32, seq_nr: u16, ts: u32, pt: u8, is_mark: u8, ssrc: u32, ) { unsafe { let fls = (*stx).srcpad.pad_flags(); gst_trace!(CAT, "creamtxbw Handling buffer from scream len={}, seq_nr {}, ts {}, pt {}, is_mark {}, ssrc {} {:?}", len, seq_nr, ts, pt, is_mark, ssrc, fls); if fls.contains(gst::PadFlags::EOS) { println!("screamtxbw EOS {:?}", fls); return; } else if fls.contains(gst::PadFlags::FLUSHING) { println!("screamtxbw FL {:?}", fls); return; } let mut buffer = gst::Buffer::new_rtp_with_sizes(len, 4, 0).unwrap(); { let buffer = buffer.get_mut().unwrap(); let mut rtp_buffer = RTPBuffer::from_buffer_writable(buffer).unwrap(); rtp_buffer.set_seq(seq_nr); rtp_buffer.set_payload_type(pt); rtp_buffer.set_timestamp(ts); rtp_buffer.set_ssrc(ssrc); rtp_buffer.set_marker(is_mark!= 0); drop(rtp_buffer); } (*stx) .srcpad .push(buffer) .expect("Screamtxbw callback srcpad.push failed"); } } #[link(name = "scream")] extern "C" { #[allow(improper_ctypes)] fn ScreamTxBwPluginInit( s: *const c_char, stx: *const Screamtxbw, cb: extern "C" fn( stx: *const Screamtxbw, len: u32, seq_nr: u16, ts: u32, pt: u8, is_mark: u8, ssrc: u32, ), ); fn ScreamTxBwPluginSetTargetRate(rate: u32); fn ScreamTxBwPluginSetForceKeyUnit(); } // This trait registers our type with the GObject object system and // provides the entry points for creating a new instance and setting // up the class data #[glib::object_subclass] impl ObjectSubclass for Screamtxbw { const NAME: &'static str = "RsScreamtxbw"; type Type = super::Screamtxbw; type ParentType = gst::Element; // Called when a new instance is to be created. We need to return an instance // of our struct here and also get the class struct passed in case it's needed fn with_class(klass: &Self::Class) -> Self { // Create our two pads from the templates that were registered with // the class and set all the functions on them. // // Each function is wrapped in catch_panic_pad_function(), which will // - Catch panics from the pad functions and instead of aborting the process // it will simply convert them into an error message and poison the element // instance // - Extract our Screamtxbw struct from the object instance and pass it to us // // Details about what each function is good for is next to each function definition let templ = klass.pad_template("sink").unwrap(); let sinkpad = gst::Pad::builder_with_template(&templ, Some("sink")) .chain_function(|pad, parent, buffer| { Screamtxbw::catch_panic_pad_function( parent, || Err(gst::FlowError::Error), |screamtxbw, element| screamtxbw.sink_chain(pad, element, buffer), ) }) .event_function(|pad, parent, event| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.sink_event(pad, element, event), ) }) .query_function(|pad, parent, query| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.sink_query(pad, element, query), ) }) .build(); let templ = klass.pad_template("src").unwrap(); let srcpad = gst::Pad::builder_with_template(&templ, Some("src")) .event_function(|pad, parent, event| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.src_event(pad, element, event), ) }) .query_function(|pad, parent, query| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.src_query(pad, element, query), ) }) .build(); let settings = Mutex::new(Default::default()); // Return an instance of our struct and also include our debug category here. // The debug category will be used later whenever we need to put something // into the debug logs Self { srcpad, sinkpad, settings, } } } // Implementation of glib::Object virtual methods impl ObjectImpl for Screamtxbw { // Called right after construction of a new instance fn constructed(&self, obj: &Self::Type) { // Call the parent class' ::constructed() implementation first self.parent_constructed(obj); // Here we actually add the pads we created in Screamtxbw::new() to the // element so that GStreamer is aware of their existence. obj.add_pad(&self.sinkpad).unwrap(); obj.add_pad(&self.srcpad).unwrap(); } // Called whenever a value of a property is changed. It can be called // at any time from any thread. // Metadata for the properties fn properties() -> &'static [glib::ParamSpec] { static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| { vec![ glib::ParamSpec::new_string( "params", "Params", "scream lib command line args", None, glib::ParamFlags::READWRITE, ), glib::ParamSpec::new_uint( "bitrate", "bitrate", "Bitrate in kbit/sec (0 = from NVENC preset)", 0, u32::MAX, DEFAULT_BITRATE, glib::ParamFlags::READWRITE, ), ] }); PROPERTIES.as_ref() } fn set_property( &self, obj: &Self::Type, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec, ) { match pspec.name() { "params" => { let mut settings = self.settings.lock().unwrap(); // self.state.lock().unwrap().is_none() settings.params = match value.get::<String>() { Ok(params) => Some(params), _ => unreachable!("type checked upstream"), }; gst_info!( CAT, obj: obj, "Changing params to {}", settings.params.as_ref().unwrap() ); let s0 = settings.params.as_ref().unwrap().as_str(); let s = CString::new(s0).expect("CString::new failed"); // self.srcpad.to_glib_none() // STREAMTX_PTR = Some(&self); unsafe { ScreamTxBwPluginInit(s.as_ptr(), self, callback); } } "bitrate" => { let mut settings = self.settings.lock().unwrap(); let rate = value.get().expect("type checked upstream"); gst_info!( CAT, obj: obj, "Changing bitrate from {} to {}", settings.bitrate, rate ); settings.bitrate = rate; unsafe { ScreamTxBwPluginSetTargetRate(rate); } } _ => unimplemented!(), } } // Called whenever a value of a property is read. It can be called // at any time from any thread. fn property(&self, _obj: &Self::Type, _id: usize, pspec: &glib::ParamSpec) -> glib::Value { match pspec.name() { "params" => { let settings = self.settings.lock().unwrap(); settings.params.to_value() } "current-max-bitrate" => { let settings = self.settings.lock().unwrap(); settings.bitrate.to_value() } _ => unimplemented!(), } } } // Implementation of gst::Element virtual methods impl GstObjectImpl for Screamtxbw {} impl ElementImpl for Screamtxbw { // Set the element specific metadata. This information is what // is visible from gst-inspect-1.0 and can also be programatically // retrieved from the gst::Registry after initial registration // without having to load the plugin in memory. fn metadata() -> Option<&'static gst::subclass::ElementMetadata> { static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| { gst::subclass::ElementMetadata::new( "Screamtxbw", "Generic", "generate RTP packets", "Jacob Teplitsky <[email protected]>", ) }); Some(&*ELEMENT_METADATA) }
// Create and add pad templates for our sink and source pad. These // are later used for actually creating the pads and beforehand // already provide information to GStreamer about all possible // pads that could exist for this type. // // Actual instances can create pads based on those pad templates fn pad_templates() -> &'static [gst::PadTemplate] { static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| { // Our element can accept any possible caps on both pads let caps = gst::Caps::new_simple("application/x-rtp", &[]); let src_pad_template = gst::PadTemplate::new( "src", gst::PadDirection::Src, gst::PadPresence::Always, &caps, ) .unwrap(); let caps = gst::Caps::new_simple("application/x-rtp", &[]); let sink_pad_template = gst::PadTemplate::new( "sink", gst::PadDirection::Sink, gst::PadPresence::Always, &caps, ) .unwrap(); vec![src_pad_template, sink_pad_template] }); PAD_TEMPLATES.as_ref() } // Called whenever the state of the element should be changed. This allows for // starting up the element, allocating/deallocating resources or shutting down // the element again. fn change_state( &self, element: &Self::Type, transition: gst::StateChange, ) -> Result<gst::StateChangeSuccess, gst::StateChangeError> { gst_info!(CAT, obj: element, "Changing state {:?}", transition); // Call the parent class' implementation of ::change_state() self.parent_change_state(element, transition) } }
random_line_split
imp.rs
use glib::prelude::*; use glib::subclass::prelude::*; use gst::prelude::*; use gst::subclass::prelude::*; use std::ffi::CString; use std::os::raw::c_char; use std::sync::Mutex; pub use gstreamer_rtp::rtp_buffer::compare_seqnum; pub use gstreamer_rtp::rtp_buffer::RTPBuffer; pub use gstreamer_rtp::rtp_buffer::RTPBufferExt; extern crate gstreamer_video as gstv; use once_cell::sync::Lazy; const DEFAULT_BITRATE: u32 = 1000; // Property value storage #[derive(Debug, Clone)] struct Settings { params: Option<String>, bitrate: u32, } impl Default for Settings { fn default() -> Self { Settings { params: None, bitrate: DEFAULT_BITRATE, } } } // static STREAMTX_PTR: Option<&Screamtxbw> = None; // Struct containing all the element data #[repr(C)] pub struct Screamtxbw { srcpad: gst::Pad, sinkpad: gst::Pad, settings: Mutex<Settings>, } static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| { gst::DebugCategory::new( "screamtxbw", gst::DebugColorFlags::empty(), Some("Screamtxbw Element"), ) }); impl Screamtxbw { // Called whenever a new buffer is passed to our sink pad. Here buffers should be processed and // whenever some output buffer is available have to push it out of the source pad. // Here we just pass through all buffers directly // // See the documentation of gst::Buffer and gst::BufferRef to see what can be done with // buffers. fn sink_chain( &self, _pad: &gst::Pad, _element: &super::Screamtxbw, _buffer: gst::Buffer, ) -> Result<gst::FlowSuccess, gst::FlowError> { glib::bitflags::_core::result::Result::Ok(gst::FlowSuccess::Ok) } // Called whenever an event arrives on the sink pad. It has to be handled accordingly and in // most cases has to be either passed to Pad::event_default() on this pad for default handling, // or Pad::push_event() on all pads with the opposite direction for direct forwarding. // Here we just pass through all events directly to the source pad. // // See the documentation of gst::Event and gst::EventRef to see what can be done with // events, and especially the gst::EventView type for inspecting events. fn sink_event(&self, pad: &gst::Pad, _element: &super::Screamtxbw, event: gst::Event) -> bool { gst_log!( CAT, obj: pad, "gstscream Handling event {:?} {:?}", event, event.type_() ); // println!("gstscream Handling sink event {:?}", event); self.srcpad.push_event(event) } // Called whenever a query is sent to the sink pad. It has to be answered if the element can // handle it, potentially by forwarding the query first to the peer pads of the pads with the // opposite direction, or false has to be returned. Default handling can be achieved with // Pad::query_default() on this pad and forwarding with Pad::peer_query() on the pads with the // opposite direction. // Here we just forward all queries directly to the source pad's peers. // // See the documentation of gst::Query and gst::QueryRef to see what can be done with // queries, and especially the gst::QueryView type for inspecting and modifying queries. fn sink_query( &self, pad: &gst::Pad, _element: &super::Screamtxbw, query: &mut gst::QueryRef, ) -> bool { gst_log!(CAT, obj: pad, "gstscream Handling query {:?}", query); self.srcpad.peer_query(query) } // Called whenever an event arrives on the source pad. It has to be handled accordingly and in // most cases has to be either passed to Pad::event_default() on the same pad for default // handling, or Pad::push_event() on all pads with the opposite direction for direct // forwarding. // Here we just pass through all events directly to the sink pad. // // See the documentation of gst::Event and gst::EventRef to see what can be done with // events, and especially the gst::EventView type for inspecting events. fn src_event(&self, pad: &gst::Pad, _element: &super::Screamtxbw, event: gst::Event) -> bool { if event.structure().unwrap().name() == "GstForceKeyUnit" { unsafe { ScreamTxBwPluginSetForceKeyUnit(); } gst_info!( CAT, obj: pad, "gstscreamtxbw src Handling event {:?} {:?}", event, event.type_() ); } gst_log!( CAT, obj: pad, "gstscream src Handling event {:?} {:?}", event, event.type_() ); self.sinkpad.push_event(event) } // Called whenever a query is sent to the source pad. It has to be answered if the element can // handle it, potentially by forwarding the query first to the peer pads of the pads with the // opposite direction, or false has to be returned. Default handling can be achieved with // Pad::query_default() on this pad and forwarding with Pad::peer_query() on the pads with the // opposite direction. // Here we just forward all queries directly to the sink pad's peers. // // See the documentation of gst::Query and gst::QueryRef to see what can be done with // queries, and especially the gst::QueryView type for inspecting and modifying queries. fn src_query( &self, pad: &gst::Pad, _element: &super::Screamtxbw, query: &mut gst::QueryRef, ) -> bool { gst_log!(CAT, obj: pad, "gstscream Handling src query {:?}", query); self.sinkpad.peer_query(query) } } extern "C" fn callback( stx: *const Screamtxbw, len: u32, seq_nr: u16, ts: u32, pt: u8, is_mark: u8, ssrc: u32, ) { unsafe { let fls = (*stx).srcpad.pad_flags(); gst_trace!(CAT, "creamtxbw Handling buffer from scream len={}, seq_nr {}, ts {}, pt {}, is_mark {}, ssrc {} {:?}", len, seq_nr, ts, pt, is_mark, ssrc, fls); if fls.contains(gst::PadFlags::EOS) { println!("screamtxbw EOS {:?}", fls); return; } else if fls.contains(gst::PadFlags::FLUSHING) { println!("screamtxbw FL {:?}", fls); return; } let mut buffer = gst::Buffer::new_rtp_with_sizes(len, 4, 0).unwrap(); { let buffer = buffer.get_mut().unwrap(); let mut rtp_buffer = RTPBuffer::from_buffer_writable(buffer).unwrap(); rtp_buffer.set_seq(seq_nr); rtp_buffer.set_payload_type(pt); rtp_buffer.set_timestamp(ts); rtp_buffer.set_ssrc(ssrc); rtp_buffer.set_marker(is_mark!= 0); drop(rtp_buffer); } (*stx) .srcpad .push(buffer) .expect("Screamtxbw callback srcpad.push failed"); } } #[link(name = "scream")] extern "C" { #[allow(improper_ctypes)] fn ScreamTxBwPluginInit( s: *const c_char, stx: *const Screamtxbw, cb: extern "C" fn( stx: *const Screamtxbw, len: u32, seq_nr: u16, ts: u32, pt: u8, is_mark: u8, ssrc: u32, ), ); fn ScreamTxBwPluginSetTargetRate(rate: u32); fn ScreamTxBwPluginSetForceKeyUnit(); } // This trait registers our type with the GObject object system and // provides the entry points for creating a new instance and setting // up the class data #[glib::object_subclass] impl ObjectSubclass for Screamtxbw { const NAME: &'static str = "RsScreamtxbw"; type Type = super::Screamtxbw; type ParentType = gst::Element; // Called when a new instance is to be created. We need to return an instance // of our struct here and also get the class struct passed in case it's needed fn with_class(klass: &Self::Class) -> Self { // Create our two pads from the templates that were registered with // the class and set all the functions on them. // // Each function is wrapped in catch_panic_pad_function(), which will // - Catch panics from the pad functions and instead of aborting the process // it will simply convert them into an error message and poison the element // instance // - Extract our Screamtxbw struct from the object instance and pass it to us // // Details about what each function is good for is next to each function definition let templ = klass.pad_template("sink").unwrap(); let sinkpad = gst::Pad::builder_with_template(&templ, Some("sink")) .chain_function(|pad, parent, buffer| { Screamtxbw::catch_panic_pad_function( parent, || Err(gst::FlowError::Error), |screamtxbw, element| screamtxbw.sink_chain(pad, element, buffer), ) }) .event_function(|pad, parent, event| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.sink_event(pad, element, event), ) }) .query_function(|pad, parent, query| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.sink_query(pad, element, query), ) }) .build(); let templ = klass.pad_template("src").unwrap(); let srcpad = gst::Pad::builder_with_template(&templ, Some("src")) .event_function(|pad, parent, event| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.src_event(pad, element, event), ) }) .query_function(|pad, parent, query| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.src_query(pad, element, query), ) }) .build(); let settings = Mutex::new(Default::default()); // Return an instance of our struct and also include our debug category here. // The debug category will be used later whenever we need to put something // into the debug logs Self { srcpad, sinkpad, settings, } } } // Implementation of glib::Object virtual methods impl ObjectImpl for Screamtxbw { // Called right after construction of a new instance fn constructed(&self, obj: &Self::Type) { // Call the parent class' ::constructed() implementation first self.parent_constructed(obj); // Here we actually add the pads we created in Screamtxbw::new() to the // element so that GStreamer is aware of their existence. obj.add_pad(&self.sinkpad).unwrap(); obj.add_pad(&self.srcpad).unwrap(); } // Called whenever a value of a property is changed. It can be called // at any time from any thread. // Metadata for the properties fn properties() -> &'static [glib::ParamSpec] { static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| { vec![ glib::ParamSpec::new_string( "params", "Params", "scream lib command line args", None, glib::ParamFlags::READWRITE, ), glib::ParamSpec::new_uint( "bitrate", "bitrate", "Bitrate in kbit/sec (0 = from NVENC preset)", 0, u32::MAX, DEFAULT_BITRATE, glib::ParamFlags::READWRITE, ), ] }); PROPERTIES.as_ref() } fn set_property( &self, obj: &Self::Type, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec, ) { match pspec.name() { "params" => { let mut settings = self.settings.lock().unwrap(); // self.state.lock().unwrap().is_none() settings.params = match value.get::<String>() { Ok(params) => Some(params), _ => unreachable!("type checked upstream"), }; gst_info!( CAT, obj: obj, "Changing params to {}", settings.params.as_ref().unwrap() ); let s0 = settings.params.as_ref().unwrap().as_str(); let s = CString::new(s0).expect("CString::new failed"); // self.srcpad.to_glib_none() // STREAMTX_PTR = Some(&self); unsafe { ScreamTxBwPluginInit(s.as_ptr(), self, callback); } } "bitrate" => { let mut settings = self.settings.lock().unwrap(); let rate = value.get().expect("type checked upstream"); gst_info!( CAT, obj: obj, "Changing bitrate from {} to {}", settings.bitrate, rate ); settings.bitrate = rate; unsafe { ScreamTxBwPluginSetTargetRate(rate); } } _ => unimplemented!(), } } // Called whenever a value of a property is read. It can be called // at any time from any thread. fn property(&self, _obj: &Self::Type, _id: usize, pspec: &glib::ParamSpec) -> glib::Value { match pspec.name() { "params" => { let settings = self.settings.lock().unwrap(); settings.params.to_value() } "current-max-bitrate" => { let settings = self.settings.lock().unwrap(); settings.bitrate.to_value() } _ => unimplemented!(), } } } // Implementation of gst::Element virtual methods impl GstObjectImpl for Screamtxbw {} impl ElementImpl for Screamtxbw { // Set the element specific metadata. This information is what // is visible from gst-inspect-1.0 and can also be programatically // retrieved from the gst::Registry after initial registration // without having to load the plugin in memory. fn metadata() -> Option<&'static gst::subclass::ElementMetadata> { static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| { gst::subclass::ElementMetadata::new( "Screamtxbw", "Generic", "generate RTP packets", "Jacob Teplitsky <[email protected]>", ) }); Some(&*ELEMENT_METADATA) } // Create and add pad templates for our sink and source pad. These // are later used for actually creating the pads and beforehand // already provide information to GStreamer about all possible // pads that could exist for this type. // // Actual instances can create pads based on those pad templates fn pad_templates() -> &'static [gst::PadTemplate] { static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| { // Our element can accept any possible caps on both pads let caps = gst::Caps::new_simple("application/x-rtp", &[]); let src_pad_template = gst::PadTemplate::new( "src", gst::PadDirection::Src, gst::PadPresence::Always, &caps, ) .unwrap(); let caps = gst::Caps::new_simple("application/x-rtp", &[]); let sink_pad_template = gst::PadTemplate::new( "sink", gst::PadDirection::Sink, gst::PadPresence::Always, &caps, ) .unwrap(); vec![src_pad_template, sink_pad_template] }); PAD_TEMPLATES.as_ref() } // Called whenever the state of the element should be changed. This allows for // starting up the element, allocating/deallocating resources or shutting down // the element again. fn change_state( &self, element: &Self::Type, transition: gst::StateChange, ) -> Result<gst::StateChangeSuccess, gst::StateChangeError>
}
{ gst_info!(CAT, obj: element, "Changing state {:?}", transition); // Call the parent class' implementation of ::change_state() self.parent_change_state(element, transition) }
identifier_body
imp.rs
use glib::prelude::*; use glib::subclass::prelude::*; use gst::prelude::*; use gst::subclass::prelude::*; use std::ffi::CString; use std::os::raw::c_char; use std::sync::Mutex; pub use gstreamer_rtp::rtp_buffer::compare_seqnum; pub use gstreamer_rtp::rtp_buffer::RTPBuffer; pub use gstreamer_rtp::rtp_buffer::RTPBufferExt; extern crate gstreamer_video as gstv; use once_cell::sync::Lazy; const DEFAULT_BITRATE: u32 = 1000; // Property value storage #[derive(Debug, Clone)] struct Settings { params: Option<String>, bitrate: u32, } impl Default for Settings { fn default() -> Self { Settings { params: None, bitrate: DEFAULT_BITRATE, } } } // static STREAMTX_PTR: Option<&Screamtxbw> = None; // Struct containing all the element data #[repr(C)] pub struct Screamtxbw { srcpad: gst::Pad, sinkpad: gst::Pad, settings: Mutex<Settings>, } static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| { gst::DebugCategory::new( "screamtxbw", gst::DebugColorFlags::empty(), Some("Screamtxbw Element"), ) }); impl Screamtxbw { // Called whenever a new buffer is passed to our sink pad. Here buffers should be processed and // whenever some output buffer is available have to push it out of the source pad. // Here we just pass through all buffers directly // // See the documentation of gst::Buffer and gst::BufferRef to see what can be done with // buffers. fn sink_chain( &self, _pad: &gst::Pad, _element: &super::Screamtxbw, _buffer: gst::Buffer, ) -> Result<gst::FlowSuccess, gst::FlowError> { glib::bitflags::_core::result::Result::Ok(gst::FlowSuccess::Ok) } // Called whenever an event arrives on the sink pad. It has to be handled accordingly and in // most cases has to be either passed to Pad::event_default() on this pad for default handling, // or Pad::push_event() on all pads with the opposite direction for direct forwarding. // Here we just pass through all events directly to the source pad. // // See the documentation of gst::Event and gst::EventRef to see what can be done with // events, and especially the gst::EventView type for inspecting events. fn sink_event(&self, pad: &gst::Pad, _element: &super::Screamtxbw, event: gst::Event) -> bool { gst_log!( CAT, obj: pad, "gstscream Handling event {:?} {:?}", event, event.type_() ); // println!("gstscream Handling sink event {:?}", event); self.srcpad.push_event(event) } // Called whenever a query is sent to the sink pad. It has to be answered if the element can // handle it, potentially by forwarding the query first to the peer pads of the pads with the // opposite direction, or false has to be returned. Default handling can be achieved with // Pad::query_default() on this pad and forwarding with Pad::peer_query() on the pads with the // opposite direction. // Here we just forward all queries directly to the source pad's peers. // // See the documentation of gst::Query and gst::QueryRef to see what can be done with // queries, and especially the gst::QueryView type for inspecting and modifying queries. fn sink_query( &self, pad: &gst::Pad, _element: &super::Screamtxbw, query: &mut gst::QueryRef, ) -> bool { gst_log!(CAT, obj: pad, "gstscream Handling query {:?}", query); self.srcpad.peer_query(query) } // Called whenever an event arrives on the source pad. It has to be handled accordingly and in // most cases has to be either passed to Pad::event_default() on the same pad for default // handling, or Pad::push_event() on all pads with the opposite direction for direct // forwarding. // Here we just pass through all events directly to the sink pad. // // See the documentation of gst::Event and gst::EventRef to see what can be done with // events, and especially the gst::EventView type for inspecting events. fn src_event(&self, pad: &gst::Pad, _element: &super::Screamtxbw, event: gst::Event) -> bool { if event.structure().unwrap().name() == "GstForceKeyUnit" { unsafe { ScreamTxBwPluginSetForceKeyUnit(); } gst_info!( CAT, obj: pad, "gstscreamtxbw src Handling event {:?} {:?}", event, event.type_() ); } gst_log!( CAT, obj: pad, "gstscream src Handling event {:?} {:?}", event, event.type_() ); self.sinkpad.push_event(event) } // Called whenever a query is sent to the source pad. It has to be answered if the element can // handle it, potentially by forwarding the query first to the peer pads of the pads with the // opposite direction, or false has to be returned. Default handling can be achieved with // Pad::query_default() on this pad and forwarding with Pad::peer_query() on the pads with the // opposite direction. // Here we just forward all queries directly to the sink pad's peers. // // See the documentation of gst::Query and gst::QueryRef to see what can be done with // queries, and especially the gst::QueryView type for inspecting and modifying queries. fn src_query( &self, pad: &gst::Pad, _element: &super::Screamtxbw, query: &mut gst::QueryRef, ) -> bool { gst_log!(CAT, obj: pad, "gstscream Handling src query {:?}", query); self.sinkpad.peer_query(query) } } extern "C" fn callback( stx: *const Screamtxbw, len: u32, seq_nr: u16, ts: u32, pt: u8, is_mark: u8, ssrc: u32, ) { unsafe { let fls = (*stx).srcpad.pad_flags(); gst_trace!(CAT, "creamtxbw Handling buffer from scream len={}, seq_nr {}, ts {}, pt {}, is_mark {}, ssrc {} {:?}", len, seq_nr, ts, pt, is_mark, ssrc, fls); if fls.contains(gst::PadFlags::EOS)
else if fls.contains(gst::PadFlags::FLUSHING) { println!("screamtxbw FL {:?}", fls); return; } let mut buffer = gst::Buffer::new_rtp_with_sizes(len, 4, 0).unwrap(); { let buffer = buffer.get_mut().unwrap(); let mut rtp_buffer = RTPBuffer::from_buffer_writable(buffer).unwrap(); rtp_buffer.set_seq(seq_nr); rtp_buffer.set_payload_type(pt); rtp_buffer.set_timestamp(ts); rtp_buffer.set_ssrc(ssrc); rtp_buffer.set_marker(is_mark!= 0); drop(rtp_buffer); } (*stx) .srcpad .push(buffer) .expect("Screamtxbw callback srcpad.push failed"); } } #[link(name = "scream")] extern "C" { #[allow(improper_ctypes)] fn ScreamTxBwPluginInit( s: *const c_char, stx: *const Screamtxbw, cb: extern "C" fn( stx: *const Screamtxbw, len: u32, seq_nr: u16, ts: u32, pt: u8, is_mark: u8, ssrc: u32, ), ); fn ScreamTxBwPluginSetTargetRate(rate: u32); fn ScreamTxBwPluginSetForceKeyUnit(); } // This trait registers our type with the GObject object system and // provides the entry points for creating a new instance and setting // up the class data #[glib::object_subclass] impl ObjectSubclass for Screamtxbw { const NAME: &'static str = "RsScreamtxbw"; type Type = super::Screamtxbw; type ParentType = gst::Element; // Called when a new instance is to be created. We need to return an instance // of our struct here and also get the class struct passed in case it's needed fn with_class(klass: &Self::Class) -> Self { // Create our two pads from the templates that were registered with // the class and set all the functions on them. // // Each function is wrapped in catch_panic_pad_function(), which will // - Catch panics from the pad functions and instead of aborting the process // it will simply convert them into an error message and poison the element // instance // - Extract our Screamtxbw struct from the object instance and pass it to us // // Details about what each function is good for is next to each function definition let templ = klass.pad_template("sink").unwrap(); let sinkpad = gst::Pad::builder_with_template(&templ, Some("sink")) .chain_function(|pad, parent, buffer| { Screamtxbw::catch_panic_pad_function( parent, || Err(gst::FlowError::Error), |screamtxbw, element| screamtxbw.sink_chain(pad, element, buffer), ) }) .event_function(|pad, parent, event| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.sink_event(pad, element, event), ) }) .query_function(|pad, parent, query| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.sink_query(pad, element, query), ) }) .build(); let templ = klass.pad_template("src").unwrap(); let srcpad = gst::Pad::builder_with_template(&templ, Some("src")) .event_function(|pad, parent, event| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.src_event(pad, element, event), ) }) .query_function(|pad, parent, query| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.src_query(pad, element, query), ) }) .build(); let settings = Mutex::new(Default::default()); // Return an instance of our struct and also include our debug category here. // The debug category will be used later whenever we need to put something // into the debug logs Self { srcpad, sinkpad, settings, } } } // Implementation of glib::Object virtual methods impl ObjectImpl for Screamtxbw { // Called right after construction of a new instance fn constructed(&self, obj: &Self::Type) { // Call the parent class' ::constructed() implementation first self.parent_constructed(obj); // Here we actually add the pads we created in Screamtxbw::new() to the // element so that GStreamer is aware of their existence. obj.add_pad(&self.sinkpad).unwrap(); obj.add_pad(&self.srcpad).unwrap(); } // Called whenever a value of a property is changed. It can be called // at any time from any thread. // Metadata for the properties fn properties() -> &'static [glib::ParamSpec] { static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| { vec![ glib::ParamSpec::new_string( "params", "Params", "scream lib command line args", None, glib::ParamFlags::READWRITE, ), glib::ParamSpec::new_uint( "bitrate", "bitrate", "Bitrate in kbit/sec (0 = from NVENC preset)", 0, u32::MAX, DEFAULT_BITRATE, glib::ParamFlags::READWRITE, ), ] }); PROPERTIES.as_ref() } fn set_property( &self, obj: &Self::Type, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec, ) { match pspec.name() { "params" => { let mut settings = self.settings.lock().unwrap(); // self.state.lock().unwrap().is_none() settings.params = match value.get::<String>() { Ok(params) => Some(params), _ => unreachable!("type checked upstream"), }; gst_info!( CAT, obj: obj, "Changing params to {}", settings.params.as_ref().unwrap() ); let s0 = settings.params.as_ref().unwrap().as_str(); let s = CString::new(s0).expect("CString::new failed"); // self.srcpad.to_glib_none() // STREAMTX_PTR = Some(&self); unsafe { ScreamTxBwPluginInit(s.as_ptr(), self, callback); } } "bitrate" => { let mut settings = self.settings.lock().unwrap(); let rate = value.get().expect("type checked upstream"); gst_info!( CAT, obj: obj, "Changing bitrate from {} to {}", settings.bitrate, rate ); settings.bitrate = rate; unsafe { ScreamTxBwPluginSetTargetRate(rate); } } _ => unimplemented!(), } } // Called whenever a value of a property is read. It can be called // at any time from any thread. fn property(&self, _obj: &Self::Type, _id: usize, pspec: &glib::ParamSpec) -> glib::Value { match pspec.name() { "params" => { let settings = self.settings.lock().unwrap(); settings.params.to_value() } "current-max-bitrate" => { let settings = self.settings.lock().unwrap(); settings.bitrate.to_value() } _ => unimplemented!(), } } } // Implementation of gst::Element virtual methods impl GstObjectImpl for Screamtxbw {} impl ElementImpl for Screamtxbw { // Set the element specific metadata. This information is what // is visible from gst-inspect-1.0 and can also be programatically // retrieved from the gst::Registry after initial registration // without having to load the plugin in memory. fn metadata() -> Option<&'static gst::subclass::ElementMetadata> { static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| { gst::subclass::ElementMetadata::new( "Screamtxbw", "Generic", "generate RTP packets", "Jacob Teplitsky <[email protected]>", ) }); Some(&*ELEMENT_METADATA) } // Create and add pad templates for our sink and source pad. These // are later used for actually creating the pads and beforehand // already provide information to GStreamer about all possible // pads that could exist for this type. // // Actual instances can create pads based on those pad templates fn pad_templates() -> &'static [gst::PadTemplate] { static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| { // Our element can accept any possible caps on both pads let caps = gst::Caps::new_simple("application/x-rtp", &[]); let src_pad_template = gst::PadTemplate::new( "src", gst::PadDirection::Src, gst::PadPresence::Always, &caps, ) .unwrap(); let caps = gst::Caps::new_simple("application/x-rtp", &[]); let sink_pad_template = gst::PadTemplate::new( "sink", gst::PadDirection::Sink, gst::PadPresence::Always, &caps, ) .unwrap(); vec![src_pad_template, sink_pad_template] }); PAD_TEMPLATES.as_ref() } // Called whenever the state of the element should be changed. This allows for // starting up the element, allocating/deallocating resources or shutting down // the element again. fn change_state( &self, element: &Self::Type, transition: gst::StateChange, ) -> Result<gst::StateChangeSuccess, gst::StateChangeError> { gst_info!(CAT, obj: element, "Changing state {:?}", transition); // Call the parent class' implementation of ::change_state() self.parent_change_state(element, transition) } }
{ println!("screamtxbw EOS {:?}", fls); return; }
conditional_block
imp.rs
use glib::prelude::*; use glib::subclass::prelude::*; use gst::prelude::*; use gst::subclass::prelude::*; use std::ffi::CString; use std::os::raw::c_char; use std::sync::Mutex; pub use gstreamer_rtp::rtp_buffer::compare_seqnum; pub use gstreamer_rtp::rtp_buffer::RTPBuffer; pub use gstreamer_rtp::rtp_buffer::RTPBufferExt; extern crate gstreamer_video as gstv; use once_cell::sync::Lazy; const DEFAULT_BITRATE: u32 = 1000; // Property value storage #[derive(Debug, Clone)] struct
{ params: Option<String>, bitrate: u32, } impl Default for Settings { fn default() -> Self { Settings { params: None, bitrate: DEFAULT_BITRATE, } } } // static STREAMTX_PTR: Option<&Screamtxbw> = None; // Struct containing all the element data #[repr(C)] pub struct Screamtxbw { srcpad: gst::Pad, sinkpad: gst::Pad, settings: Mutex<Settings>, } static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| { gst::DebugCategory::new( "screamtxbw", gst::DebugColorFlags::empty(), Some("Screamtxbw Element"), ) }); impl Screamtxbw { // Called whenever a new buffer is passed to our sink pad. Here buffers should be processed and // whenever some output buffer is available have to push it out of the source pad. // Here we just pass through all buffers directly // // See the documentation of gst::Buffer and gst::BufferRef to see what can be done with // buffers. fn sink_chain( &self, _pad: &gst::Pad, _element: &super::Screamtxbw, _buffer: gst::Buffer, ) -> Result<gst::FlowSuccess, gst::FlowError> { glib::bitflags::_core::result::Result::Ok(gst::FlowSuccess::Ok) } // Called whenever an event arrives on the sink pad. It has to be handled accordingly and in // most cases has to be either passed to Pad::event_default() on this pad for default handling, // or Pad::push_event() on all pads with the opposite direction for direct forwarding. // Here we just pass through all events directly to the source pad. // // See the documentation of gst::Event and gst::EventRef to see what can be done with // events, and especially the gst::EventView type for inspecting events. fn sink_event(&self, pad: &gst::Pad, _element: &super::Screamtxbw, event: gst::Event) -> bool { gst_log!( CAT, obj: pad, "gstscream Handling event {:?} {:?}", event, event.type_() ); // println!("gstscream Handling sink event {:?}", event); self.srcpad.push_event(event) } // Called whenever a query is sent to the sink pad. It has to be answered if the element can // handle it, potentially by forwarding the query first to the peer pads of the pads with the // opposite direction, or false has to be returned. Default handling can be achieved with // Pad::query_default() on this pad and forwarding with Pad::peer_query() on the pads with the // opposite direction. // Here we just forward all queries directly to the source pad's peers. // // See the documentation of gst::Query and gst::QueryRef to see what can be done with // queries, and especially the gst::QueryView type for inspecting and modifying queries. fn sink_query( &self, pad: &gst::Pad, _element: &super::Screamtxbw, query: &mut gst::QueryRef, ) -> bool { gst_log!(CAT, obj: pad, "gstscream Handling query {:?}", query); self.srcpad.peer_query(query) } // Called whenever an event arrives on the source pad. It has to be handled accordingly and in // most cases has to be either passed to Pad::event_default() on the same pad for default // handling, or Pad::push_event() on all pads with the opposite direction for direct // forwarding. // Here we just pass through all events directly to the sink pad. // // See the documentation of gst::Event and gst::EventRef to see what can be done with // events, and especially the gst::EventView type for inspecting events. fn src_event(&self, pad: &gst::Pad, _element: &super::Screamtxbw, event: gst::Event) -> bool { if event.structure().unwrap().name() == "GstForceKeyUnit" { unsafe { ScreamTxBwPluginSetForceKeyUnit(); } gst_info!( CAT, obj: pad, "gstscreamtxbw src Handling event {:?} {:?}", event, event.type_() ); } gst_log!( CAT, obj: pad, "gstscream src Handling event {:?} {:?}", event, event.type_() ); self.sinkpad.push_event(event) } // Called whenever a query is sent to the source pad. It has to be answered if the element can // handle it, potentially by forwarding the query first to the peer pads of the pads with the // opposite direction, or false has to be returned. Default handling can be achieved with // Pad::query_default() on this pad and forwarding with Pad::peer_query() on the pads with the // opposite direction. // Here we just forward all queries directly to the sink pad's peers. // // See the documentation of gst::Query and gst::QueryRef to see what can be done with // queries, and especially the gst::QueryView type for inspecting and modifying queries. fn src_query( &self, pad: &gst::Pad, _element: &super::Screamtxbw, query: &mut gst::QueryRef, ) -> bool { gst_log!(CAT, obj: pad, "gstscream Handling src query {:?}", query); self.sinkpad.peer_query(query) } } extern "C" fn callback( stx: *const Screamtxbw, len: u32, seq_nr: u16, ts: u32, pt: u8, is_mark: u8, ssrc: u32, ) { unsafe { let fls = (*stx).srcpad.pad_flags(); gst_trace!(CAT, "creamtxbw Handling buffer from scream len={}, seq_nr {}, ts {}, pt {}, is_mark {}, ssrc {} {:?}", len, seq_nr, ts, pt, is_mark, ssrc, fls); if fls.contains(gst::PadFlags::EOS) { println!("screamtxbw EOS {:?}", fls); return; } else if fls.contains(gst::PadFlags::FLUSHING) { println!("screamtxbw FL {:?}", fls); return; } let mut buffer = gst::Buffer::new_rtp_with_sizes(len, 4, 0).unwrap(); { let buffer = buffer.get_mut().unwrap(); let mut rtp_buffer = RTPBuffer::from_buffer_writable(buffer).unwrap(); rtp_buffer.set_seq(seq_nr); rtp_buffer.set_payload_type(pt); rtp_buffer.set_timestamp(ts); rtp_buffer.set_ssrc(ssrc); rtp_buffer.set_marker(is_mark!= 0); drop(rtp_buffer); } (*stx) .srcpad .push(buffer) .expect("Screamtxbw callback srcpad.push failed"); } } #[link(name = "scream")] extern "C" { #[allow(improper_ctypes)] fn ScreamTxBwPluginInit( s: *const c_char, stx: *const Screamtxbw, cb: extern "C" fn( stx: *const Screamtxbw, len: u32, seq_nr: u16, ts: u32, pt: u8, is_mark: u8, ssrc: u32, ), ); fn ScreamTxBwPluginSetTargetRate(rate: u32); fn ScreamTxBwPluginSetForceKeyUnit(); } // This trait registers our type with the GObject object system and // provides the entry points for creating a new instance and setting // up the class data #[glib::object_subclass] impl ObjectSubclass for Screamtxbw { const NAME: &'static str = "RsScreamtxbw"; type Type = super::Screamtxbw; type ParentType = gst::Element; // Called when a new instance is to be created. We need to return an instance // of our struct here and also get the class struct passed in case it's needed fn with_class(klass: &Self::Class) -> Self { // Create our two pads from the templates that were registered with // the class and set all the functions on them. // // Each function is wrapped in catch_panic_pad_function(), which will // - Catch panics from the pad functions and instead of aborting the process // it will simply convert them into an error message and poison the element // instance // - Extract our Screamtxbw struct from the object instance and pass it to us // // Details about what each function is good for is next to each function definition let templ = klass.pad_template("sink").unwrap(); let sinkpad = gst::Pad::builder_with_template(&templ, Some("sink")) .chain_function(|pad, parent, buffer| { Screamtxbw::catch_panic_pad_function( parent, || Err(gst::FlowError::Error), |screamtxbw, element| screamtxbw.sink_chain(pad, element, buffer), ) }) .event_function(|pad, parent, event| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.sink_event(pad, element, event), ) }) .query_function(|pad, parent, query| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.sink_query(pad, element, query), ) }) .build(); let templ = klass.pad_template("src").unwrap(); let srcpad = gst::Pad::builder_with_template(&templ, Some("src")) .event_function(|pad, parent, event| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.src_event(pad, element, event), ) }) .query_function(|pad, parent, query| { Screamtxbw::catch_panic_pad_function( parent, || false, |screamtxbw, element| screamtxbw.src_query(pad, element, query), ) }) .build(); let settings = Mutex::new(Default::default()); // Return an instance of our struct and also include our debug category here. // The debug category will be used later whenever we need to put something // into the debug logs Self { srcpad, sinkpad, settings, } } } // Implementation of glib::Object virtual methods impl ObjectImpl for Screamtxbw { // Called right after construction of a new instance fn constructed(&self, obj: &Self::Type) { // Call the parent class' ::constructed() implementation first self.parent_constructed(obj); // Here we actually add the pads we created in Screamtxbw::new() to the // element so that GStreamer is aware of their existence. obj.add_pad(&self.sinkpad).unwrap(); obj.add_pad(&self.srcpad).unwrap(); } // Called whenever a value of a property is changed. It can be called // at any time from any thread. // Metadata for the properties fn properties() -> &'static [glib::ParamSpec] { static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| { vec![ glib::ParamSpec::new_string( "params", "Params", "scream lib command line args", None, glib::ParamFlags::READWRITE, ), glib::ParamSpec::new_uint( "bitrate", "bitrate", "Bitrate in kbit/sec (0 = from NVENC preset)", 0, u32::MAX, DEFAULT_BITRATE, glib::ParamFlags::READWRITE, ), ] }); PROPERTIES.as_ref() } fn set_property( &self, obj: &Self::Type, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec, ) { match pspec.name() { "params" => { let mut settings = self.settings.lock().unwrap(); // self.state.lock().unwrap().is_none() settings.params = match value.get::<String>() { Ok(params) => Some(params), _ => unreachable!("type checked upstream"), }; gst_info!( CAT, obj: obj, "Changing params to {}", settings.params.as_ref().unwrap() ); let s0 = settings.params.as_ref().unwrap().as_str(); let s = CString::new(s0).expect("CString::new failed"); // self.srcpad.to_glib_none() // STREAMTX_PTR = Some(&self); unsafe { ScreamTxBwPluginInit(s.as_ptr(), self, callback); } } "bitrate" => { let mut settings = self.settings.lock().unwrap(); let rate = value.get().expect("type checked upstream"); gst_info!( CAT, obj: obj, "Changing bitrate from {} to {}", settings.bitrate, rate ); settings.bitrate = rate; unsafe { ScreamTxBwPluginSetTargetRate(rate); } } _ => unimplemented!(), } } // Called whenever a value of a property is read. It can be called // at any time from any thread. fn property(&self, _obj: &Self::Type, _id: usize, pspec: &glib::ParamSpec) -> glib::Value { match pspec.name() { "params" => { let settings = self.settings.lock().unwrap(); settings.params.to_value() } "current-max-bitrate" => { let settings = self.settings.lock().unwrap(); settings.bitrate.to_value() } _ => unimplemented!(), } } } // Implementation of gst::Element virtual methods impl GstObjectImpl for Screamtxbw {} impl ElementImpl for Screamtxbw { // Set the element specific metadata. This information is what // is visible from gst-inspect-1.0 and can also be programatically // retrieved from the gst::Registry after initial registration // without having to load the plugin in memory. fn metadata() -> Option<&'static gst::subclass::ElementMetadata> { static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| { gst::subclass::ElementMetadata::new( "Screamtxbw", "Generic", "generate RTP packets", "Jacob Teplitsky <[email protected]>", ) }); Some(&*ELEMENT_METADATA) } // Create and add pad templates for our sink and source pad. These // are later used for actually creating the pads and beforehand // already provide information to GStreamer about all possible // pads that could exist for this type. // // Actual instances can create pads based on those pad templates fn pad_templates() -> &'static [gst::PadTemplate] { static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| { // Our element can accept any possible caps on both pads let caps = gst::Caps::new_simple("application/x-rtp", &[]); let src_pad_template = gst::PadTemplate::new( "src", gst::PadDirection::Src, gst::PadPresence::Always, &caps, ) .unwrap(); let caps = gst::Caps::new_simple("application/x-rtp", &[]); let sink_pad_template = gst::PadTemplate::new( "sink", gst::PadDirection::Sink, gst::PadPresence::Always, &caps, ) .unwrap(); vec![src_pad_template, sink_pad_template] }); PAD_TEMPLATES.as_ref() } // Called whenever the state of the element should be changed. This allows for // starting up the element, allocating/deallocating resources or shutting down // the element again. fn change_state( &self, element: &Self::Type, transition: gst::StateChange, ) -> Result<gst::StateChangeSuccess, gst::StateChangeError> { gst_info!(CAT, obj: element, "Changing state {:?}", transition); // Call the parent class' implementation of ::change_state() self.parent_change_state(element, transition) } }
Settings
identifier_name
rustc.rs
use crate::command_prelude::*; use cargo::ops; pub fn
() -> App { subcommand("rustc") .setting(AppSettings::TrailingVarArg) .about("Compile a package, and pass extra options to the compiler") .arg(opt("quiet", "No output printed to stdout").short("q")) .arg(Arg::with_name("args").multiple(true).help("Rustc flags")) .arg_package("Package to build") .arg_jobs() .arg_targets_all( "Build only this package's library", "Build only the specified binary", "Build all binaries", "Build only the specified example", "Build all examples", "Build only the specified test target", "Build all tests", "Build only the specified bench target", "Build all benches", "Build all targets", ) .arg_release("Build artifacts in release mode, with optimizations") .arg_profile("Build artifacts with the specified profile") .arg_features() .arg_target_triple("Target triple which compiles will be for") .arg_target_dir() .arg_manifest_path() .arg_message_format() .arg_unit_graph() .after_help( "\ The specified target for the current package (or package specified by SPEC if provided) will be compiled along with all of its dependencies. The specified <args>... will all be passed to the final compiler invocation, not any of the dependencies. Note that the compiler will still unconditionally receive arguments such as -L, --extern, and --crate-type, and the specified <args>... will simply be added to the compiler invocation. This command requires that only one target is being compiled. If more than one target is available for the current package the filters of --lib, --bin, etc, must be used to select which target is compiled. To pass flags to all compiler processes spawned by Cargo, use the $RUSTFLAGS environment variable or the `build.rustflags` configuration option. ", ) } pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult { let ws = args.workspace(config)?; let mode = match args.value_of("profile") { Some("dev") | None => CompileMode::Build, Some("test") => CompileMode::Test, Some("bench") => CompileMode::Bench, Some("check") => CompileMode::Check { test: false }, Some(mode) => { let err = anyhow::format_err!( "unknown profile: `{}`, use dev, test, or bench", mode ); return Err(CliError::new(err, 101)); } }; let mut compile_opts = args.compile_options_for_single_package( config, mode, Some(&ws), ProfileChecking::Unchecked, )?; let target_args = values(args, "args"); compile_opts.target_rustc_args = if target_args.is_empty() { None } else { Some(target_args) }; ops::compile(&ws, &compile_opts)?; Ok(()) }
cli
identifier_name
rustc.rs
use crate::command_prelude::*; use cargo::ops; pub fn cli() -> App { subcommand("rustc") .setting(AppSettings::TrailingVarArg) .about("Compile a package, and pass extra options to the compiler") .arg(opt("quiet", "No output printed to stdout").short("q")) .arg(Arg::with_name("args").multiple(true).help("Rustc flags")) .arg_package("Package to build") .arg_jobs() .arg_targets_all( "Build only this package's library", "Build only the specified binary", "Build all binaries", "Build only the specified example", "Build all examples", "Build only the specified test target", "Build all tests", "Build only the specified bench target", "Build all benches", "Build all targets", ) .arg_release("Build artifacts in release mode, with optimizations") .arg_profile("Build artifacts with the specified profile") .arg_features() .arg_target_triple("Target triple which compiles will be for") .arg_target_dir() .arg_manifest_path() .arg_message_format() .arg_unit_graph() .after_help( "\ The specified target for the current package (or package specified by SPEC if provided) will be compiled along with all of its dependencies. The specified <args>... will all be passed to the final compiler invocation, not any of the dependencies. Note that the compiler will still unconditionally receive arguments such as -L, --extern, and --crate-type, and the specified <args>... will simply be added to the compiler invocation. This command requires that only one target is being compiled. If more than one target is available for the current package the filters of --lib, --bin, etc, must be used to select which target is compiled. To pass flags to all compiler processes spawned by Cargo, use the $RUSTFLAGS environment variable or the
) } pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult { let ws = args.workspace(config)?; let mode = match args.value_of("profile") { Some("dev") | None => CompileMode::Build, Some("test") => CompileMode::Test, Some("bench") => CompileMode::Bench, Some("check") => CompileMode::Check { test: false }, Some(mode) => { let err = anyhow::format_err!( "unknown profile: `{}`, use dev, test, or bench", mode ); return Err(CliError::new(err, 101)); } }; let mut compile_opts = args.compile_options_for_single_package( config, mode, Some(&ws), ProfileChecking::Unchecked, )?; let target_args = values(args, "args"); compile_opts.target_rustc_args = if target_args.is_empty() { None } else { Some(target_args) }; ops::compile(&ws, &compile_opts)?; Ok(()) }
`build.rustflags` configuration option. ",
random_line_split
rustc.rs
use crate::command_prelude::*; use cargo::ops; pub fn cli() -> App
.arg_release("Build artifacts in release mode, with optimizations") .arg_profile("Build artifacts with the specified profile") .arg_features() .arg_target_triple("Target triple which compiles will be for") .arg_target_dir() .arg_manifest_path() .arg_message_format() .arg_unit_graph() .after_help( "\ The specified target for the current package (or package specified by SPEC if provided) will be compiled along with all of its dependencies. The specified <args>... will all be passed to the final compiler invocation, not any of the dependencies. Note that the compiler will still unconditionally receive arguments such as -L, --extern, and --crate-type, and the specified <args>... will simply be added to the compiler invocation. This command requires that only one target is being compiled. If more than one target is available for the current package the filters of --lib, --bin, etc, must be used to select which target is compiled. To pass flags to all compiler processes spawned by Cargo, use the $RUSTFLAGS environment variable or the `build.rustflags` configuration option. ", ) } pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult { let ws = args.workspace(config)?; let mode = match args.value_of("profile") { Some("dev") | None => CompileMode::Build, Some("test") => CompileMode::Test, Some("bench") => CompileMode::Bench, Some("check") => CompileMode::Check { test: false }, Some(mode) => { let err = anyhow::format_err!( "unknown profile: `{}`, use dev, test, or bench", mode ); return Err(CliError::new(err, 101)); } }; let mut compile_opts = args.compile_options_for_single_package( config, mode, Some(&ws), ProfileChecking::Unchecked, )?; let target_args = values(args, "args"); compile_opts.target_rustc_args = if target_args.is_empty() { None } else { Some(target_args) }; ops::compile(&ws, &compile_opts)?; Ok(()) }
{ subcommand("rustc") .setting(AppSettings::TrailingVarArg) .about("Compile a package, and pass extra options to the compiler") .arg(opt("quiet", "No output printed to stdout").short("q")) .arg(Arg::with_name("args").multiple(true).help("Rustc flags")) .arg_package("Package to build") .arg_jobs() .arg_targets_all( "Build only this package's library", "Build only the specified binary", "Build all binaries", "Build only the specified example", "Build all examples", "Build only the specified test target", "Build all tests", "Build only the specified bench target", "Build all benches", "Build all targets", )
identifier_body
ffi.rs
// Copyright 2014-2015 Sam Doshi ([email protected]) // Copyright 2013-2014 Philippe Delrieu ([email protected]) // // Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed except according to those terms. use libc::{c_char, c_void}; pub type PmDeviceId = i32; pub type PortMidiStream = c_void; #[doc(hidden)] pub type PmMessage = i32; pub type PmTimestamp = u32; pub const PM_NO_DEVICE : PmDeviceId = -1; #[doc(hidden)] #[repr(C)] pub struct PmEvent { pub message : PmMessage, pub timestamp : PmTimestamp, } #[repr(C)] pub struct PmDeviceInfo { pub struct_version: i32, /* < this internal structure version */ pub interf : *const c_char, /* < underlying MIDI API, e.g. MMSystem or DirectX */ pub name : *const c_char, /* < device name, e.g. USB MidiSport 1x1 */ pub input : i32, /* < true iff input is available */ pub output : i32, /* < true iff output is available */ pub opened : i32, /* < used by generic PortMidi code to do error checking on arguments */ } #[derive(Debug)] #[repr(C)] pub enum PmError { PmNoError = 0, PmGotData = 1, /* < A "no error" return that also indicates data available */ PmHostError = -10000, PmInvalidDeviceId = -9999, /* out of range or * output device when input is requested or * input device when output is requested or * device is already opened */ PmInsufficientMemory = -9998, PmBufferTooSmall = -9997, PmBufferOverflow = -9996, PmBadPtr = -9995, /* PortMidiStream parameter is NULL or * stream is not opened or * stream is output when input is required or * stream is input when output is required */ PmBadData = -9994, /* illegal midi data, e.g. missing EOX */ PmInternalError = -9993, PmBufferMaxSize = -9992, /* buffer is already as large as it can be */ } // while we wait for FromPrimitive to stabilise pub fn tmp_from_primitive(i: i32) -> Option<PmError> { match i { 0 => Some(PmError::PmNoError),
-9996 => Some(PmError::PmBufferOverflow), -9995 => Some(PmError::PmBadPtr), -9994 => Some(PmError::PmBadData), -9993 => Some(PmError::PmInternalError), -9992 => Some(PmError::PmBufferMaxSize), _ => None } } #[link(name = "portmidi")] extern "C" { pub fn Pm_Initialize() -> PmError; pub fn Pm_Terminate()-> PmError; pub fn Pm_HasHostError(stream: *const PortMidiStream) -> i32; pub fn Pm_GetErrorText(errorCode: PmError) -> *const c_char; pub fn Pm_GetHostErrorText(msg: *const c_char, len: i32); pub fn Pm_CountDevices() -> i32; pub fn Pm_GetDefaultInputDeviceID() -> PmDeviceId; pub fn Pm_GetDefaultOutputDeviceID() -> PmDeviceId; pub fn Pm_GetDeviceInfo(id: PmDeviceId) -> *const PmDeviceInfo; pub fn Pm_OpenInput(stream: *const *const PortMidiStream, inputDevice: PmDeviceId, inputDriverInfo: *const c_void, bufferSize: i32, time_proc: *const c_void, time_info: *const c_void) -> PmError; pub fn Pm_OpenOutput(stream: *const *const PortMidiStream, outputDevice: PmDeviceId, inputDriverInfo: *const c_void, bufferSize: i32, time_proc: *const c_void, time_info: *const c_void, latency: i32) -> PmError; pub fn Pm_Read(stream: *const PortMidiStream, buffer : *mut PmEvent, length: i32) -> i32; pub fn Pm_Abort(stream: *const PortMidiStream) -> PmError; pub fn Pm_Close(stream: *const PortMidiStream) -> PmError; pub fn Pm_Poll(stream: *const PortMidiStream) -> PmError; pub fn Pm_Write(stream: *const PortMidiStream, buffer: *const PmEvent, length: i32) -> PmError; pub fn Pm_WriteShort(stream: *const PortMidiStream, timestamp: PmTimestamp, message: PmMessage) -> PmError; }
1 => Some(PmError::PmGotData), -10000 => Some(PmError::PmHostError), -9999 => Some(PmError::PmInvalidDeviceId), -9998 => Some(PmError::PmInsufficientMemory), -9997 => Some(PmError::PmBufferTooSmall),
random_line_split
ffi.rs
// Copyright 2014-2015 Sam Doshi ([email protected]) // Copyright 2013-2014 Philippe Delrieu ([email protected]) // // Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed except according to those terms. use libc::{c_char, c_void}; pub type PmDeviceId = i32; pub type PortMidiStream = c_void; #[doc(hidden)] pub type PmMessage = i32; pub type PmTimestamp = u32; pub const PM_NO_DEVICE : PmDeviceId = -1; #[doc(hidden)] #[repr(C)] pub struct
{ pub message : PmMessage, pub timestamp : PmTimestamp, } #[repr(C)] pub struct PmDeviceInfo { pub struct_version: i32, /* < this internal structure version */ pub interf : *const c_char, /* < underlying MIDI API, e.g. MMSystem or DirectX */ pub name : *const c_char, /* < device name, e.g. USB MidiSport 1x1 */ pub input : i32, /* < true iff input is available */ pub output : i32, /* < true iff output is available */ pub opened : i32, /* < used by generic PortMidi code to do error checking on arguments */ } #[derive(Debug)] #[repr(C)] pub enum PmError { PmNoError = 0, PmGotData = 1, /* < A "no error" return that also indicates data available */ PmHostError = -10000, PmInvalidDeviceId = -9999, /* out of range or * output device when input is requested or * input device when output is requested or * device is already opened */ PmInsufficientMemory = -9998, PmBufferTooSmall = -9997, PmBufferOverflow = -9996, PmBadPtr = -9995, /* PortMidiStream parameter is NULL or * stream is not opened or * stream is output when input is required or * stream is input when output is required */ PmBadData = -9994, /* illegal midi data, e.g. missing EOX */ PmInternalError = -9993, PmBufferMaxSize = -9992, /* buffer is already as large as it can be */ } // while we wait for FromPrimitive to stabilise pub fn tmp_from_primitive(i: i32) -> Option<PmError> { match i { 0 => Some(PmError::PmNoError), 1 => Some(PmError::PmGotData), -10000 => Some(PmError::PmHostError), -9999 => Some(PmError::PmInvalidDeviceId), -9998 => Some(PmError::PmInsufficientMemory), -9997 => Some(PmError::PmBufferTooSmall), -9996 => Some(PmError::PmBufferOverflow), -9995 => Some(PmError::PmBadPtr), -9994 => Some(PmError::PmBadData), -9993 => Some(PmError::PmInternalError), -9992 => Some(PmError::PmBufferMaxSize), _ => None } } #[link(name = "portmidi")] extern "C" { pub fn Pm_Initialize() -> PmError; pub fn Pm_Terminate()-> PmError; pub fn Pm_HasHostError(stream: *const PortMidiStream) -> i32; pub fn Pm_GetErrorText(errorCode: PmError) -> *const c_char; pub fn Pm_GetHostErrorText(msg: *const c_char, len: i32); pub fn Pm_CountDevices() -> i32; pub fn Pm_GetDefaultInputDeviceID() -> PmDeviceId; pub fn Pm_GetDefaultOutputDeviceID() -> PmDeviceId; pub fn Pm_GetDeviceInfo(id: PmDeviceId) -> *const PmDeviceInfo; pub fn Pm_OpenInput(stream: *const *const PortMidiStream, inputDevice: PmDeviceId, inputDriverInfo: *const c_void, bufferSize: i32, time_proc: *const c_void, time_info: *const c_void) -> PmError; pub fn Pm_OpenOutput(stream: *const *const PortMidiStream, outputDevice: PmDeviceId, inputDriverInfo: *const c_void, bufferSize: i32, time_proc: *const c_void, time_info: *const c_void, latency: i32) -> PmError; pub fn Pm_Read(stream: *const PortMidiStream, buffer : *mut PmEvent, length: i32) -> i32; pub fn Pm_Abort(stream: *const PortMidiStream) -> PmError; pub fn Pm_Close(stream: *const PortMidiStream) -> PmError; pub fn Pm_Poll(stream: *const PortMidiStream) -> PmError; pub fn Pm_Write(stream: *const PortMidiStream, buffer: *const PmEvent, length: i32) -> PmError; pub fn Pm_WriteShort(stream: *const PortMidiStream, timestamp: PmTimestamp, message: PmMessage) -> PmError; }
PmEvent
identifier_name
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg}; use dom::bindings::cell::DOMRefCell; use dom::bindings::global::GlobalRef; use dom::bindings::str::DOMString; use std::collections::HashMap; use std::collections::hash_map::Entry; use time::{Timespec, get_time}; // https://developer.mozilla.org/en-US/docs/Web/API/Console pub struct
(()); impl Console { fn send_to_devtools(global: GlobalRef, level: LogLevel, message: DOMString) { if let Some(chan) = global.devtools_chan() { let console_message = prepare_message(level, message); let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI( global.pipeline_id(), console_message, global.get_worker_id()); chan.send(devtools_message).unwrap(); } } } impl Console { // https://developer.mozilla.org/en-US/docs/Web/API/Console/log pub fn Log(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console pub fn Debug(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Debug, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/info pub fn Info(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Info, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/warn pub fn Warn(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Warn, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/error pub fn Error(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Error, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/assert pub fn Assert(global: GlobalRef, condition: bool, message: Option<DOMString>) { if!condition { let message = message.unwrap_or_else(|| DOMString::from("no message")); println!("Assertion failed: {}", message); Self::send_to_devtools(global, LogLevel::Error, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/time pub fn Time(global: GlobalRef, label: DOMString) { if let Ok(()) = global.console_timers().time(label.clone()) { let message = DOMString::from(format!("{}: timer started", label)); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd pub fn TimeEnd(global: GlobalRef, label: DOMString) { if let Ok(delta) = global.console_timers().time_end(&label) { let message = DOMString::from( format!("{}: {}ms", label, delta) ); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); }; } } fn timestamp_in_ms(time: Timespec) -> u64 { (time.sec * 1000 + (time.nsec / 1000000) as i64) as u64 } fn prepare_message(log_level: LogLevel, message: DOMString) -> ConsoleMessage { // TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later ConsoleMessage { message: String::from(message), logLevel: log_level, filename: "test".to_owned(), lineNumber: 1, columnNumber: 1, } } #[derive(HeapSizeOf, JSTraceable)] pub struct TimerSet(DOMRefCell<HashMap<DOMString, u64>>); impl TimerSet { pub fn new() -> Self { TimerSet(DOMRefCell::new(Default::default())) } fn time(&self, label: DOMString) -> Result<(), ()> { let mut timers = self.0.borrow_mut(); if timers.len() >= 10000 { return Err(()); } match timers.entry(label) { Entry::Vacant(entry) => { entry.insert(timestamp_in_ms(get_time())); Ok(()) }, Entry::Occupied(_) => Err(()), } } fn time_end(&self, label: &str) -> Result<u64, ()> { self.0.borrow_mut().remove(label).ok_or(()).map(|start| { timestamp_in_ms(get_time()) - start }) } }
Console
identifier_name
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg}; use dom::bindings::cell::DOMRefCell; use dom::bindings::global::GlobalRef; use dom::bindings::str::DOMString; use std::collections::HashMap; use std::collections::hash_map::Entry; use time::{Timespec, get_time}; // https://developer.mozilla.org/en-US/docs/Web/API/Console pub struct Console(()); impl Console { fn send_to_devtools(global: GlobalRef, level: LogLevel, message: DOMString) { if let Some(chan) = global.devtools_chan()
} } impl Console { // https://developer.mozilla.org/en-US/docs/Web/API/Console/log pub fn Log(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console pub fn Debug(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Debug, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/info pub fn Info(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Info, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/warn pub fn Warn(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Warn, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/error pub fn Error(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Error, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/assert pub fn Assert(global: GlobalRef, condition: bool, message: Option<DOMString>) { if!condition { let message = message.unwrap_or_else(|| DOMString::from("no message")); println!("Assertion failed: {}", message); Self::send_to_devtools(global, LogLevel::Error, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/time pub fn Time(global: GlobalRef, label: DOMString) { if let Ok(()) = global.console_timers().time(label.clone()) { let message = DOMString::from(format!("{}: timer started", label)); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd pub fn TimeEnd(global: GlobalRef, label: DOMString) { if let Ok(delta) = global.console_timers().time_end(&label) { let message = DOMString::from( format!("{}: {}ms", label, delta) ); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); }; } } fn timestamp_in_ms(time: Timespec) -> u64 { (time.sec * 1000 + (time.nsec / 1000000) as i64) as u64 } fn prepare_message(log_level: LogLevel, message: DOMString) -> ConsoleMessage { // TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later ConsoleMessage { message: String::from(message), logLevel: log_level, filename: "test".to_owned(), lineNumber: 1, columnNumber: 1, } } #[derive(HeapSizeOf, JSTraceable)] pub struct TimerSet(DOMRefCell<HashMap<DOMString, u64>>); impl TimerSet { pub fn new() -> Self { TimerSet(DOMRefCell::new(Default::default())) } fn time(&self, label: DOMString) -> Result<(), ()> { let mut timers = self.0.borrow_mut(); if timers.len() >= 10000 { return Err(()); } match timers.entry(label) { Entry::Vacant(entry) => { entry.insert(timestamp_in_ms(get_time())); Ok(()) }, Entry::Occupied(_) => Err(()), } } fn time_end(&self, label: &str) -> Result<u64, ()> { self.0.borrow_mut().remove(label).ok_or(()).map(|start| { timestamp_in_ms(get_time()) - start }) } }
{ let console_message = prepare_message(level, message); let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI( global.pipeline_id(), console_message, global.get_worker_id()); chan.send(devtools_message).unwrap(); }
conditional_block
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg}; use dom::bindings::cell::DOMRefCell; use dom::bindings::global::GlobalRef; use dom::bindings::str::DOMString; use std::collections::HashMap; use std::collections::hash_map::Entry; use time::{Timespec, get_time}; // https://developer.mozilla.org/en-US/docs/Web/API/Console pub struct Console(()); impl Console { fn send_to_devtools(global: GlobalRef, level: LogLevel, message: DOMString) { if let Some(chan) = global.devtools_chan() { let console_message = prepare_message(level, message); let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI( global.pipeline_id(),
} impl Console { // https://developer.mozilla.org/en-US/docs/Web/API/Console/log pub fn Log(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console pub fn Debug(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Debug, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/info pub fn Info(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Info, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/warn pub fn Warn(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Warn, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/error pub fn Error(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Error, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/assert pub fn Assert(global: GlobalRef, condition: bool, message: Option<DOMString>) { if!condition { let message = message.unwrap_or_else(|| DOMString::from("no message")); println!("Assertion failed: {}", message); Self::send_to_devtools(global, LogLevel::Error, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/time pub fn Time(global: GlobalRef, label: DOMString) { if let Ok(()) = global.console_timers().time(label.clone()) { let message = DOMString::from(format!("{}: timer started", label)); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd pub fn TimeEnd(global: GlobalRef, label: DOMString) { if let Ok(delta) = global.console_timers().time_end(&label) { let message = DOMString::from( format!("{}: {}ms", label, delta) ); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); }; } } fn timestamp_in_ms(time: Timespec) -> u64 { (time.sec * 1000 + (time.nsec / 1000000) as i64) as u64 } fn prepare_message(log_level: LogLevel, message: DOMString) -> ConsoleMessage { // TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later ConsoleMessage { message: String::from(message), logLevel: log_level, filename: "test".to_owned(), lineNumber: 1, columnNumber: 1, } } #[derive(HeapSizeOf, JSTraceable)] pub struct TimerSet(DOMRefCell<HashMap<DOMString, u64>>); impl TimerSet { pub fn new() -> Self { TimerSet(DOMRefCell::new(Default::default())) } fn time(&self, label: DOMString) -> Result<(), ()> { let mut timers = self.0.borrow_mut(); if timers.len() >= 10000 { return Err(()); } match timers.entry(label) { Entry::Vacant(entry) => { entry.insert(timestamp_in_ms(get_time())); Ok(()) }, Entry::Occupied(_) => Err(()), } } fn time_end(&self, label: &str) -> Result<u64, ()> { self.0.borrow_mut().remove(label).ok_or(()).map(|start| { timestamp_in_ms(get_time()) - start }) } }
console_message, global.get_worker_id()); chan.send(devtools_message).unwrap(); } }
random_line_split
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg}; use dom::bindings::cell::DOMRefCell; use dom::bindings::global::GlobalRef; use dom::bindings::str::DOMString; use std::collections::HashMap; use std::collections::hash_map::Entry; use time::{Timespec, get_time}; // https://developer.mozilla.org/en-US/docs/Web/API/Console pub struct Console(()); impl Console { fn send_to_devtools(global: GlobalRef, level: LogLevel, message: DOMString) { if let Some(chan) = global.devtools_chan() { let console_message = prepare_message(level, message); let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI( global.pipeline_id(), console_message, global.get_worker_id()); chan.send(devtools_message).unwrap(); } } } impl Console { // https://developer.mozilla.org/en-US/docs/Web/API/Console/log pub fn Log(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console pub fn Debug(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Debug, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/info pub fn Info(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Info, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/warn pub fn Warn(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Warn, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/error pub fn Error(global: GlobalRef, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Error, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/assert pub fn Assert(global: GlobalRef, condition: bool, message: Option<DOMString>) { if!condition { let message = message.unwrap_or_else(|| DOMString::from("no message")); println!("Assertion failed: {}", message); Self::send_to_devtools(global, LogLevel::Error, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/time pub fn Time(global: GlobalRef, label: DOMString) { if let Ok(()) = global.console_timers().time(label.clone()) { let message = DOMString::from(format!("{}: timer started", label)); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd pub fn TimeEnd(global: GlobalRef, label: DOMString) { if let Ok(delta) = global.console_timers().time_end(&label) { let message = DOMString::from( format!("{}: {}ms", label, delta) ); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); }; } } fn timestamp_in_ms(time: Timespec) -> u64 { (time.sec * 1000 + (time.nsec / 1000000) as i64) as u64 } fn prepare_message(log_level: LogLevel, message: DOMString) -> ConsoleMessage { // TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later ConsoleMessage { message: String::from(message), logLevel: log_level, filename: "test".to_owned(), lineNumber: 1, columnNumber: 1, } } #[derive(HeapSizeOf, JSTraceable)] pub struct TimerSet(DOMRefCell<HashMap<DOMString, u64>>); impl TimerSet { pub fn new() -> Self { TimerSet(DOMRefCell::new(Default::default())) } fn time(&self, label: DOMString) -> Result<(), ()> { let mut timers = self.0.borrow_mut(); if timers.len() >= 10000 { return Err(()); } match timers.entry(label) { Entry::Vacant(entry) => { entry.insert(timestamp_in_ms(get_time())); Ok(()) }, Entry::Occupied(_) => Err(()), } } fn time_end(&self, label: &str) -> Result<u64, ()>
}
{ self.0.borrow_mut().remove(label).ok_or(()).map(|start| { timestamp_in_ms(get_time()) - start }) }
identifier_body
parser.rs
use crate::plugins; use comrak::{ format_html, nodes::{AstNode, NodeHtmlBlock, NodeValue}, parse_document, ComrakExtensionOptions, ComrakOptions, ComrakParseOptions, ComrakRenderOptions, }; use std::string::FromUtf8Error; use std::{ collections::BTreeMap, sync::{Arc, Mutex}, }; use syntect::{ highlighting::{Color, ThemeSet}, html::highlighted_html_for_string, parsing::SyntaxSet, }; use thiserror::Error; use typed_arena::Arena; use url_path::UrlPath; #[derive(Error, Debug)] pub enum ParseError { #[error("Utf8Error: `{0}`")] Utf8Error(#[from] FromUtf8Error), #[error("Error getting lock from embed file")] EmbedFileLockError, #[error("Error parsing md file")] MdParseError, } #[derive(Debug)] pub struct Html { pub title: Option<String>, pub content: String, } pub struct Settings { /// add a base directory for all links to other md files base_dir: Option<String>, } impl Default for Settings { fn default() -> Self { Settings { base_dir: None } } } pub fn parse(arg: &str) -> Result<Html, ParseError> { let referred_files = pre_parse_get_embedded_files(arg); let embed_files = if let Ok(referred_files) = referred_files { let file_contents = plugins::fetch_file_contents(referred_files); Some(file_contents) } else { None }; parse_with_settings(arg, &embed_files, &Settings::default()) } pub fn parse_with_base_dir( arg: &str, base_dir: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, ) -> Result<Html, ParseError> { let settings = Settings { base_dir: Some(base_dir.to_string()), ..Default::default() }; parse_with_settings(arg, &embed_files, &settings) } pub fn parse_with_settings( arg: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, settings: &Settings, ) -> Result<Html, ParseError> { let html = parse_via_comrak(arg, &embed_files, settings); html } fn get_comrak_options() -> ComrakOptions { ComrakOptions { extension: ComrakExtensionOptions { strikethrough: true, tagfilter: false, table: true, autolink: true, tasklist: true, superscript: false, header_ids: None, footnotes: true, description_lists: true, }, parse: ComrakParseOptions { smart: false, default_info_string: None, }, render: ComrakRenderOptions { hardbreaks: true, github_pre_lang: true, width: 0, unsafe_: true, escape: false, }, } } fn iter_nodes<'a, F>( node: &'a AstNode<'a>, is_heading: Arc<Mutex<bool>>, title: Arc<Mutex<Option<String>>>, f: &F, ) -> Result<(), ParseError> where F: Fn(&'a AstNode<'a>) -> Result<(), ParseError>, { f(node)?; for c in node.children() { iter_nodes(c, is_heading.clone(), title.clone(), f)?; } Ok(()) } fn pre_iter_nodes<'a, F>( node: &'a AstNode<'a>, files: Arc<Mutex<Vec<String>>>, f: &F, ) -> Result<(), ParseError> where F: Fn(&'a AstNode<'a>) -> Result<(), ParseError>, { f(node)?; for c in node.children() { pre_iter_nodes(c, files.clone(), f)?; } Ok(()) } /// /// Extract the embeded files in img image and make it as a lookup pub fn pre_parse_get_embedded_files( arg: &str, ) -> Result<Vec<String>, ParseError> { // The returned nodes are created in the supplied Arena, and are bound by its lifetime. let arena = Arena::new(); let option = get_comrak_options(); let root = parse_document(&arena, arg, &option); let embed_files: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(vec![])); pre_iter_nodes(root, embed_files.clone(), &|node| { let ref mut value = node.data.borrow_mut().value; let new_value = match value { &mut NodeValue::Image(ref link) => { let link_url = String::from_utf8(link.url.clone())?; if let Ok(mut embed_files) = embed_files.lock() { embed_files.push(link_url); } value.clone() } _ => value.clone(), }; *value = new_value; Ok(()) })?; let embedded = match embed_files.lock() { Ok(files) => Ok((*files).to_owned()), Err(_e) => Err(ParseError::EmbedFileLockError), }; embedded } fn parse_via_comrak( arg: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, settings: &Settings, ) -> Result<Html, ParseError> { // The returned nodes are created in the supplied Arena, and are bound by its lifetime. let arena = Arena::new(); let option = get_comrak_options(); let title: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None)); let is_heading: Arc<Mutex<bool>> = Arc::new(Mutex::new(false)); let root = parse_document(&arena, arg, &option); iter_nodes(root, is_heading.clone(), title.clone(), &|node| { let ref mut value = node.data.borrow_mut().value; let new_value = match value { &mut NodeValue::CodeBlock(ref codeblock) => { let codeblock_info = String::from_utf8(codeblock.info.to_owned()) .expect("error converting to string"); let codeblock_literal = String::from_utf8(codeblock.literal.to_owned()) .expect("error converting to string"); if let Ok(out) = plugins::plugin_executor( &codeblock_info, &codeblock_literal, ) { NodeValue::HtmlBlock(NodeHtmlBlock { literal: out.into_bytes(), block_type: 0, }) } else if let Some(code_block_html) = format_source_code(&codeblock_info, &codeblock_literal) { code_block_html } else { value.clone() } } &mut NodeValue::Link(ref nodelink) => { if let Ok(url) = String::from_utf8(nodelink.url.clone()) { if let Some(ref base_dir) = settings.base_dir { let url1 = UrlPath::new(&url); let url2 = url1.normalize(); let url3 = if url1.is_external() { url2 } else if url1.is_absolute() { url2 } else { format!("{}/{}", base_dir, url) }; let url4 = UrlPath::new(&url3); let url5 = url4.normalize(); let url6 = if url4.is_external() &&!url4.is_extension("md")
else { format!("/#{}", url5) }; log::info!("url6: {}", url6); let mut new_nodelink = nodelink.clone(); new_nodelink.url = url6.into_bytes(); NodeValue::Link(new_nodelink) } else { value.clone() } } else { value.clone() } } &mut NodeValue::Heading(ref heading) => { if heading.level == 1 { if let Ok(mut is_heading) = is_heading.lock() { *is_heading = true; } } value.clone() } &mut NodeValue::Text(ref text) => { if let Ok(is_heading) = is_heading.lock() { if *is_heading { let txt = String::from_utf8(text.to_owned()) .expect("Unable to convert to string"); if let Ok(mut title) = title.lock() { if title.is_none() { // only when unset *title = Some(txt.to_string()); } } } } value.clone() } &mut NodeValue::Image(ref link) => { let link_url = String::from_utf8(link.url.clone()) .expect("unable to convert to string"); match plugins::embed_handler(&link_url, embed_files) { Ok(html) => NodeValue::HtmlBlock(NodeHtmlBlock { literal: html.into_bytes(), block_type: 0, }), Err(e) => { log::error!("error: {:#?}", e); value.clone() } } } _ => value.clone(), }; *value = new_value; Ok(()) })?; let mut html = vec![]; if let Ok(()) = format_html(root, &option, &mut html) { let render_html = String::from_utf8(html)?; let title = if let Ok(got) = title.lock() { if let Some(ref got) = *got { Some(got.to_string()) } else { None } } else { None }; Ok(Html { title, content: render_html, }) } else { Err(ParseError::MdParseError) } } fn format_source_code(lang: &str, literal: &str) -> Option<NodeValue> { let lang_name = match lang { "rust" => "Rust", _ => "text", }; let ss = SyntaxSet::load_defaults_newlines(); let ts = ThemeSet::load_defaults(); let theme = &ts.themes["base16-ocean.light"]; let _c = theme.settings.background.unwrap_or(Color::WHITE); if let Some(syntax) = ss.find_syntax_by_name(lang_name) { let html = highlighted_html_for_string(literal, &ss, &syntax, theme); Some(NodeValue::HtmlBlock(NodeHtmlBlock { literal: html.into_bytes(), block_type: 0, })) } else { None } }
{ // leave as it url5 }
conditional_block
parser.rs
use crate::plugins; use comrak::{ format_html, nodes::{AstNode, NodeHtmlBlock, NodeValue}, parse_document, ComrakExtensionOptions, ComrakOptions, ComrakParseOptions, ComrakRenderOptions, }; use std::string::FromUtf8Error; use std::{ collections::BTreeMap, sync::{Arc, Mutex}, }; use syntect::{ highlighting::{Color, ThemeSet}, html::highlighted_html_for_string, parsing::SyntaxSet, }; use thiserror::Error; use typed_arena::Arena; use url_path::UrlPath; #[derive(Error, Debug)] pub enum ParseError { #[error("Utf8Error: `{0}`")] Utf8Error(#[from] FromUtf8Error), #[error("Error getting lock from embed file")] EmbedFileLockError, #[error("Error parsing md file")] MdParseError, } #[derive(Debug)] pub struct Html { pub title: Option<String>, pub content: String, } pub struct Settings { /// add a base directory for all links to other md files base_dir: Option<String>, } impl Default for Settings { fn default() -> Self { Settings { base_dir: None } } } pub fn parse(arg: &str) -> Result<Html, ParseError> { let referred_files = pre_parse_get_embedded_files(arg); let embed_files = if let Ok(referred_files) = referred_files { let file_contents = plugins::fetch_file_contents(referred_files); Some(file_contents) } else { None }; parse_with_settings(arg, &embed_files, &Settings::default()) } pub fn parse_with_base_dir( arg: &str, base_dir: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, ) -> Result<Html, ParseError> { let settings = Settings { base_dir: Some(base_dir.to_string()), ..Default::default() }; parse_with_settings(arg, &embed_files, &settings) } pub fn parse_with_settings( arg: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, settings: &Settings, ) -> Result<Html, ParseError> { let html = parse_via_comrak(arg, &embed_files, settings); html } fn get_comrak_options() -> ComrakOptions { ComrakOptions { extension: ComrakExtensionOptions { strikethrough: true, tagfilter: false, table: true, autolink: true, tasklist: true, superscript: false, header_ids: None, footnotes: true, description_lists: true, }, parse: ComrakParseOptions { smart: false, default_info_string: None, }, render: ComrakRenderOptions { hardbreaks: true, github_pre_lang: true, width: 0, unsafe_: true, escape: false, }, } } fn iter_nodes<'a, F>( node: &'a AstNode<'a>, is_heading: Arc<Mutex<bool>>, title: Arc<Mutex<Option<String>>>, f: &F, ) -> Result<(), ParseError> where F: Fn(&'a AstNode<'a>) -> Result<(), ParseError>, { f(node)?; for c in node.children() { iter_nodes(c, is_heading.clone(), title.clone(), f)?; } Ok(()) } fn pre_iter_nodes<'a, F>( node: &'a AstNode<'a>, files: Arc<Mutex<Vec<String>>>, f: &F, ) -> Result<(), ParseError> where F: Fn(&'a AstNode<'a>) -> Result<(), ParseError>, { f(node)?; for c in node.children() { pre_iter_nodes(c, files.clone(), f)?; } Ok(()) } /// /// Extract the embeded files in img image and make it as a lookup pub fn pre_parse_get_embedded_files( arg: &str, ) -> Result<Vec<String>, ParseError> { // The returned nodes are created in the supplied Arena, and are bound by its lifetime. let arena = Arena::new(); let option = get_comrak_options(); let root = parse_document(&arena, arg, &option); let embed_files: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(vec![])); pre_iter_nodes(root, embed_files.clone(), &|node| { let ref mut value = node.data.borrow_mut().value; let new_value = match value { &mut NodeValue::Image(ref link) => { let link_url = String::from_utf8(link.url.clone())?; if let Ok(mut embed_files) = embed_files.lock() { embed_files.push(link_url); } value.clone() } _ => value.clone(), }; *value = new_value; Ok(()) })?; let embedded = match embed_files.lock() { Ok(files) => Ok((*files).to_owned()), Err(_e) => Err(ParseError::EmbedFileLockError), }; embedded } fn parse_via_comrak( arg: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, settings: &Settings, ) -> Result<Html, ParseError> { // The returned nodes are created in the supplied Arena, and are bound by its lifetime. let arena = Arena::new(); let option = get_comrak_options(); let title: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None)); let is_heading: Arc<Mutex<bool>> = Arc::new(Mutex::new(false)); let root = parse_document(&arena, arg, &option); iter_nodes(root, is_heading.clone(), title.clone(), &|node| { let ref mut value = node.data.borrow_mut().value; let new_value = match value { &mut NodeValue::CodeBlock(ref codeblock) => { let codeblock_info = String::from_utf8(codeblock.info.to_owned()) .expect("error converting to string"); let codeblock_literal = String::from_utf8(codeblock.literal.to_owned()) .expect("error converting to string"); if let Ok(out) = plugins::plugin_executor( &codeblock_info, &codeblock_literal, ) { NodeValue::HtmlBlock(NodeHtmlBlock { literal: out.into_bytes(), block_type: 0, }) } else if let Some(code_block_html) = format_source_code(&codeblock_info, &codeblock_literal) { code_block_html } else { value.clone() } } &mut NodeValue::Link(ref nodelink) => { if let Ok(url) = String::from_utf8(nodelink.url.clone()) { if let Some(ref base_dir) = settings.base_dir { let url1 = UrlPath::new(&url); let url2 = url1.normalize(); let url3 = if url1.is_external() { url2 } else if url1.is_absolute() { url2 } else { format!("{}/{}", base_dir, url) }; let url4 = UrlPath::new(&url3); let url5 = url4.normalize(); let url6 = if url4.is_external() &&!url4.is_extension("md") { // leave as it url5 } else { format!("/#{}", url5) }; log::info!("url6: {}", url6); let mut new_nodelink = nodelink.clone(); new_nodelink.url = url6.into_bytes(); NodeValue::Link(new_nodelink) } else { value.clone() } } else { value.clone() } } &mut NodeValue::Heading(ref heading) => { if heading.level == 1 { if let Ok(mut is_heading) = is_heading.lock() { *is_heading = true; } } value.clone() } &mut NodeValue::Text(ref text) => { if let Ok(is_heading) = is_heading.lock() { if *is_heading { let txt = String::from_utf8(text.to_owned()) .expect("Unable to convert to string"); if let Ok(mut title) = title.lock() { if title.is_none() { // only when unset *title = Some(txt.to_string()); } } } } value.clone() } &mut NodeValue::Image(ref link) => { let link_url = String::from_utf8(link.url.clone()) .expect("unable to convert to string"); match plugins::embed_handler(&link_url, embed_files) { Ok(html) => NodeValue::HtmlBlock(NodeHtmlBlock { literal: html.into_bytes(), block_type: 0, }), Err(e) => { log::error!("error: {:#?}", e); value.clone() } } } _ => value.clone(), }; *value = new_value; Ok(()) })?; let mut html = vec![]; if let Ok(()) = format_html(root, &option, &mut html) { let render_html = String::from_utf8(html)?; let title = if let Ok(got) = title.lock() { if let Some(ref got) = *got { Some(got.to_string()) } else { None } } else { None }; Ok(Html { title, content: render_html, }) } else { Err(ParseError::MdParseError) } } fn
(lang: &str, literal: &str) -> Option<NodeValue> { let lang_name = match lang { "rust" => "Rust", _ => "text", }; let ss = SyntaxSet::load_defaults_newlines(); let ts = ThemeSet::load_defaults(); let theme = &ts.themes["base16-ocean.light"]; let _c = theme.settings.background.unwrap_or(Color::WHITE); if let Some(syntax) = ss.find_syntax_by_name(lang_name) { let html = highlighted_html_for_string(literal, &ss, &syntax, theme); Some(NodeValue::HtmlBlock(NodeHtmlBlock { literal: html.into_bytes(), block_type: 0, })) } else { None } }
format_source_code
identifier_name
parser.rs
use crate::plugins; use comrak::{ format_html, nodes::{AstNode, NodeHtmlBlock, NodeValue}, parse_document, ComrakExtensionOptions, ComrakOptions, ComrakParseOptions, ComrakRenderOptions, }; use std::string::FromUtf8Error; use std::{ collections::BTreeMap, sync::{Arc, Mutex}, }; use syntect::{ highlighting::{Color, ThemeSet}, html::highlighted_html_for_string, parsing::SyntaxSet, }; use thiserror::Error; use typed_arena::Arena; use url_path::UrlPath; #[derive(Error, Debug)] pub enum ParseError { #[error("Utf8Error: `{0}`")] Utf8Error(#[from] FromUtf8Error), #[error("Error getting lock from embed file")] EmbedFileLockError, #[error("Error parsing md file")] MdParseError, } #[derive(Debug)] pub struct Html { pub title: Option<String>, pub content: String, } pub struct Settings { /// add a base directory for all links to other md files base_dir: Option<String>, } impl Default for Settings { fn default() -> Self { Settings { base_dir: None } } } pub fn parse(arg: &str) -> Result<Html, ParseError> { let referred_files = pre_parse_get_embedded_files(arg); let embed_files = if let Ok(referred_files) = referred_files { let file_contents = plugins::fetch_file_contents(referred_files); Some(file_contents) } else { None }; parse_with_settings(arg, &embed_files, &Settings::default()) } pub fn parse_with_base_dir( arg: &str, base_dir: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, ) -> Result<Html, ParseError> { let settings = Settings { base_dir: Some(base_dir.to_string()), ..Default::default() }; parse_with_settings(arg, &embed_files, &settings) } pub fn parse_with_settings( arg: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, settings: &Settings, ) -> Result<Html, ParseError> { let html = parse_via_comrak(arg, &embed_files, settings); html } fn get_comrak_options() -> ComrakOptions { ComrakOptions { extension: ComrakExtensionOptions { strikethrough: true, tagfilter: false, table: true, autolink: true, tasklist: true, superscript: false, header_ids: None, footnotes: true, description_lists: true, }, parse: ComrakParseOptions { smart: false, default_info_string: None, }, render: ComrakRenderOptions { hardbreaks: true, github_pre_lang: true, width: 0, unsafe_: true, escape: false, }, } } fn iter_nodes<'a, F>( node: &'a AstNode<'a>, is_heading: Arc<Mutex<bool>>, title: Arc<Mutex<Option<String>>>, f: &F, ) -> Result<(), ParseError> where F: Fn(&'a AstNode<'a>) -> Result<(), ParseError>, { f(node)?; for c in node.children() { iter_nodes(c, is_heading.clone(), title.clone(), f)?; } Ok(()) } fn pre_iter_nodes<'a, F>( node: &'a AstNode<'a>, files: Arc<Mutex<Vec<String>>>, f: &F, ) -> Result<(), ParseError> where F: Fn(&'a AstNode<'a>) -> Result<(), ParseError>, { f(node)?; for c in node.children() { pre_iter_nodes(c, files.clone(), f)?; } Ok(()) } /// /// Extract the embeded files in img image and make it as a lookup pub fn pre_parse_get_embedded_files( arg: &str, ) -> Result<Vec<String>, ParseError> { // The returned nodes are created in the supplied Arena, and are bound by its lifetime. let arena = Arena::new(); let option = get_comrak_options(); let root = parse_document(&arena, arg, &option); let embed_files: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(vec![])); pre_iter_nodes(root, embed_files.clone(), &|node| { let ref mut value = node.data.borrow_mut().value; let new_value = match value { &mut NodeValue::Image(ref link) => { let link_url = String::from_utf8(link.url.clone())?; if let Ok(mut embed_files) = embed_files.lock() { embed_files.push(link_url); } value.clone() } _ => value.clone(), }; *value = new_value; Ok(()) })?; let embedded = match embed_files.lock() { Ok(files) => Ok((*files).to_owned()), Err(_e) => Err(ParseError::EmbedFileLockError), }; embedded } fn parse_via_comrak( arg: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, settings: &Settings, ) -> Result<Html, ParseError> { // The returned nodes are created in the supplied Arena, and are bound by its lifetime. let arena = Arena::new(); let option = get_comrak_options(); let title: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None)); let is_heading: Arc<Mutex<bool>> = Arc::new(Mutex::new(false)); let root = parse_document(&arena, arg, &option); iter_nodes(root, is_heading.clone(), title.clone(), &|node| { let ref mut value = node.data.borrow_mut().value; let new_value = match value { &mut NodeValue::CodeBlock(ref codeblock) => { let codeblock_info = String::from_utf8(codeblock.info.to_owned()) .expect("error converting to string"); let codeblock_literal = String::from_utf8(codeblock.literal.to_owned()) .expect("error converting to string"); if let Ok(out) = plugins::plugin_executor( &codeblock_info, &codeblock_literal, ) { NodeValue::HtmlBlock(NodeHtmlBlock { literal: out.into_bytes(), block_type: 0, }) } else if let Some(code_block_html) = format_source_code(&codeblock_info, &codeblock_literal) { code_block_html } else { value.clone() } } &mut NodeValue::Link(ref nodelink) => { if let Ok(url) = String::from_utf8(nodelink.url.clone()) { if let Some(ref base_dir) = settings.base_dir { let url1 = UrlPath::new(&url); let url2 = url1.normalize(); let url3 = if url1.is_external() { url2 } else if url1.is_absolute() { url2 } else { format!("{}/{}", base_dir, url) }; let url4 = UrlPath::new(&url3); let url5 = url4.normalize(); let url6 = if url4.is_external() &&!url4.is_extension("md") { // leave as it url5 } else { format!("/#{}", url5) }; log::info!("url6: {}", url6); let mut new_nodelink = nodelink.clone(); new_nodelink.url = url6.into_bytes(); NodeValue::Link(new_nodelink) } else { value.clone() } } else { value.clone() } } &mut NodeValue::Heading(ref heading) => { if heading.level == 1 { if let Ok(mut is_heading) = is_heading.lock() { *is_heading = true; } } value.clone() } &mut NodeValue::Text(ref text) => { if let Ok(is_heading) = is_heading.lock() { if *is_heading { let txt = String::from_utf8(text.to_owned()) .expect("Unable to convert to string"); if let Ok(mut title) = title.lock() { if title.is_none() { // only when unset *title = Some(txt.to_string()); } } } } value.clone() } &mut NodeValue::Image(ref link) => { let link_url = String::from_utf8(link.url.clone()) .expect("unable to convert to string"); match plugins::embed_handler(&link_url, embed_files) { Ok(html) => NodeValue::HtmlBlock(NodeHtmlBlock { literal: html.into_bytes(), block_type: 0, }), Err(e) => { log::error!("error: {:#?}", e); value.clone() } } } _ => value.clone(), }; *value = new_value; Ok(()) })?; let mut html = vec![]; if let Ok(()) = format_html(root, &option, &mut html) { let render_html = String::from_utf8(html)?; let title = if let Ok(got) = title.lock() {
} else { None } } else { None }; Ok(Html { title, content: render_html, }) } else { Err(ParseError::MdParseError) } } fn format_source_code(lang: &str, literal: &str) -> Option<NodeValue> { let lang_name = match lang { "rust" => "Rust", _ => "text", }; let ss = SyntaxSet::load_defaults_newlines(); let ts = ThemeSet::load_defaults(); let theme = &ts.themes["base16-ocean.light"]; let _c = theme.settings.background.unwrap_or(Color::WHITE); if let Some(syntax) = ss.find_syntax_by_name(lang_name) { let html = highlighted_html_for_string(literal, &ss, &syntax, theme); Some(NodeValue::HtmlBlock(NodeHtmlBlock { literal: html.into_bytes(), block_type: 0, })) } else { None } }
if let Some(ref got) = *got { Some(got.to_string())
random_line_split
parser.rs
use crate::plugins; use comrak::{ format_html, nodes::{AstNode, NodeHtmlBlock, NodeValue}, parse_document, ComrakExtensionOptions, ComrakOptions, ComrakParseOptions, ComrakRenderOptions, }; use std::string::FromUtf8Error; use std::{ collections::BTreeMap, sync::{Arc, Mutex}, }; use syntect::{ highlighting::{Color, ThemeSet}, html::highlighted_html_for_string, parsing::SyntaxSet, }; use thiserror::Error; use typed_arena::Arena; use url_path::UrlPath; #[derive(Error, Debug)] pub enum ParseError { #[error("Utf8Error: `{0}`")] Utf8Error(#[from] FromUtf8Error), #[error("Error getting lock from embed file")] EmbedFileLockError, #[error("Error parsing md file")] MdParseError, } #[derive(Debug)] pub struct Html { pub title: Option<String>, pub content: String, } pub struct Settings { /// add a base directory for all links to other md files base_dir: Option<String>, } impl Default for Settings { fn default() -> Self
} pub fn parse(arg: &str) -> Result<Html, ParseError> { let referred_files = pre_parse_get_embedded_files(arg); let embed_files = if let Ok(referred_files) = referred_files { let file_contents = plugins::fetch_file_contents(referred_files); Some(file_contents) } else { None }; parse_with_settings(arg, &embed_files, &Settings::default()) } pub fn parse_with_base_dir( arg: &str, base_dir: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, ) -> Result<Html, ParseError> { let settings = Settings { base_dir: Some(base_dir.to_string()), ..Default::default() }; parse_with_settings(arg, &embed_files, &settings) } pub fn parse_with_settings( arg: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, settings: &Settings, ) -> Result<Html, ParseError> { let html = parse_via_comrak(arg, &embed_files, settings); html } fn get_comrak_options() -> ComrakOptions { ComrakOptions { extension: ComrakExtensionOptions { strikethrough: true, tagfilter: false, table: true, autolink: true, tasklist: true, superscript: false, header_ids: None, footnotes: true, description_lists: true, }, parse: ComrakParseOptions { smart: false, default_info_string: None, }, render: ComrakRenderOptions { hardbreaks: true, github_pre_lang: true, width: 0, unsafe_: true, escape: false, }, } } fn iter_nodes<'a, F>( node: &'a AstNode<'a>, is_heading: Arc<Mutex<bool>>, title: Arc<Mutex<Option<String>>>, f: &F, ) -> Result<(), ParseError> where F: Fn(&'a AstNode<'a>) -> Result<(), ParseError>, { f(node)?; for c in node.children() { iter_nodes(c, is_heading.clone(), title.clone(), f)?; } Ok(()) } fn pre_iter_nodes<'a, F>( node: &'a AstNode<'a>, files: Arc<Mutex<Vec<String>>>, f: &F, ) -> Result<(), ParseError> where F: Fn(&'a AstNode<'a>) -> Result<(), ParseError>, { f(node)?; for c in node.children() { pre_iter_nodes(c, files.clone(), f)?; } Ok(()) } /// /// Extract the embeded files in img image and make it as a lookup pub fn pre_parse_get_embedded_files( arg: &str, ) -> Result<Vec<String>, ParseError> { // The returned nodes are created in the supplied Arena, and are bound by its lifetime. let arena = Arena::new(); let option = get_comrak_options(); let root = parse_document(&arena, arg, &option); let embed_files: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(vec![])); pre_iter_nodes(root, embed_files.clone(), &|node| { let ref mut value = node.data.borrow_mut().value; let new_value = match value { &mut NodeValue::Image(ref link) => { let link_url = String::from_utf8(link.url.clone())?; if let Ok(mut embed_files) = embed_files.lock() { embed_files.push(link_url); } value.clone() } _ => value.clone(), }; *value = new_value; Ok(()) })?; let embedded = match embed_files.lock() { Ok(files) => Ok((*files).to_owned()), Err(_e) => Err(ParseError::EmbedFileLockError), }; embedded } fn parse_via_comrak( arg: &str, embed_files: &Option<BTreeMap<String, Vec<u8>>>, settings: &Settings, ) -> Result<Html, ParseError> { // The returned nodes are created in the supplied Arena, and are bound by its lifetime. let arena = Arena::new(); let option = get_comrak_options(); let title: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None)); let is_heading: Arc<Mutex<bool>> = Arc::new(Mutex::new(false)); let root = parse_document(&arena, arg, &option); iter_nodes(root, is_heading.clone(), title.clone(), &|node| { let ref mut value = node.data.borrow_mut().value; let new_value = match value { &mut NodeValue::CodeBlock(ref codeblock) => { let codeblock_info = String::from_utf8(codeblock.info.to_owned()) .expect("error converting to string"); let codeblock_literal = String::from_utf8(codeblock.literal.to_owned()) .expect("error converting to string"); if let Ok(out) = plugins::plugin_executor( &codeblock_info, &codeblock_literal, ) { NodeValue::HtmlBlock(NodeHtmlBlock { literal: out.into_bytes(), block_type: 0, }) } else if let Some(code_block_html) = format_source_code(&codeblock_info, &codeblock_literal) { code_block_html } else { value.clone() } } &mut NodeValue::Link(ref nodelink) => { if let Ok(url) = String::from_utf8(nodelink.url.clone()) { if let Some(ref base_dir) = settings.base_dir { let url1 = UrlPath::new(&url); let url2 = url1.normalize(); let url3 = if url1.is_external() { url2 } else if url1.is_absolute() { url2 } else { format!("{}/{}", base_dir, url) }; let url4 = UrlPath::new(&url3); let url5 = url4.normalize(); let url6 = if url4.is_external() &&!url4.is_extension("md") { // leave as it url5 } else { format!("/#{}", url5) }; log::info!("url6: {}", url6); let mut new_nodelink = nodelink.clone(); new_nodelink.url = url6.into_bytes(); NodeValue::Link(new_nodelink) } else { value.clone() } } else { value.clone() } } &mut NodeValue::Heading(ref heading) => { if heading.level == 1 { if let Ok(mut is_heading) = is_heading.lock() { *is_heading = true; } } value.clone() } &mut NodeValue::Text(ref text) => { if let Ok(is_heading) = is_heading.lock() { if *is_heading { let txt = String::from_utf8(text.to_owned()) .expect("Unable to convert to string"); if let Ok(mut title) = title.lock() { if title.is_none() { // only when unset *title = Some(txt.to_string()); } } } } value.clone() } &mut NodeValue::Image(ref link) => { let link_url = String::from_utf8(link.url.clone()) .expect("unable to convert to string"); match plugins::embed_handler(&link_url, embed_files) { Ok(html) => NodeValue::HtmlBlock(NodeHtmlBlock { literal: html.into_bytes(), block_type: 0, }), Err(e) => { log::error!("error: {:#?}", e); value.clone() } } } _ => value.clone(), }; *value = new_value; Ok(()) })?; let mut html = vec![]; if let Ok(()) = format_html(root, &option, &mut html) { let render_html = String::from_utf8(html)?; let title = if let Ok(got) = title.lock() { if let Some(ref got) = *got { Some(got.to_string()) } else { None } } else { None }; Ok(Html { title, content: render_html, }) } else { Err(ParseError::MdParseError) } } fn format_source_code(lang: &str, literal: &str) -> Option<NodeValue> { let lang_name = match lang { "rust" => "Rust", _ => "text", }; let ss = SyntaxSet::load_defaults_newlines(); let ts = ThemeSet::load_defaults(); let theme = &ts.themes["base16-ocean.light"]; let _c = theme.settings.background.unwrap_or(Color::WHITE); if let Some(syntax) = ss.find_syntax_by_name(lang_name) { let html = highlighted_html_for_string(literal, &ss, &syntax, theme); Some(NodeValue::HtmlBlock(NodeHtmlBlock { literal: html.into_bytes(), block_type: 0, })) } else { None } }
{ Settings { base_dir: None } }
identifier_body
utils.rs
use std::fmt; use std::path::{Path, PathBuf};
use rustc_serialize::{Encodable, Encoder}; use url::Url; use git2::{self, ObjectType}; use core::GitReference; use util::{CargoResult, ChainError, human, ToUrl, internal}; #[derive(PartialEq, Clone, Debug)] pub struct GitRevision(git2::Oid); impl fmt::Display for GitRevision { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } /// GitRemote represents a remote repository. It gets cloned into a local /// GitDatabase. #[derive(PartialEq,Clone,Debug)] pub struct GitRemote { url: Url, } #[derive(PartialEq,Clone,RustcEncodable)] struct EncodableGitRemote { url: String, } impl Encodable for GitRemote { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitRemote { url: self.url.to_string() }.encode(s) } } /// GitDatabase is a local clone of a remote repository's database. Multiple /// GitCheckouts can be cloned from this GitDatabase. pub struct GitDatabase { remote: GitRemote, path: PathBuf, repo: git2::Repository, } #[derive(RustcEncodable)] pub struct EncodableGitDatabase { remote: GitRemote, path: String, } impl Encodable for GitDatabase { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitDatabase { remote: self.remote.clone(), path: self.path.display().to_string() }.encode(s) } } /// GitCheckout is a local checkout of a particular revision. Calling /// `clone_into` with a reference will resolve the reference into a revision, /// and return a CargoError if no revision for that reference was found. pub struct GitCheckout<'a> { database: &'a GitDatabase, location: PathBuf, revision: GitRevision, repo: git2::Repository, } #[derive(RustcEncodable)] pub struct EncodableGitCheckout { database: EncodableGitDatabase, location: String, revision: String, } impl<'a> Encodable for GitCheckout<'a> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitCheckout { location: self.location.display().to_string(), revision: self.revision.to_string(), database: EncodableGitDatabase { remote: self.database.remote.clone(), path: self.database.path.display().to_string(), }, }.encode(s) } } // Implementations impl GitRemote { pub fn new(url: &Url) -> GitRemote { GitRemote { url: url.clone() } } pub fn url(&self) -> &Url { &self.url } pub fn rev_for(&self, path: &Path, reference: &GitReference) -> CargoResult<GitRevision> { let db = try!(self.db_at(path)); db.rev_for(reference) } pub fn checkout(&self, into: &Path) -> CargoResult<GitDatabase> { let repo = match git2::Repository::open(into) { Ok(repo) => { try!(self.fetch_into(&repo).chain_error(|| { human(format!("failed to fetch into {}", into.display())) })); repo } Err(..) => { try!(self.clone_into(into).chain_error(|| { human(format!("failed to clone into: {}", into.display())) })) } }; Ok(GitDatabase { remote: self.clone(), path: into.to_path_buf(), repo: repo, }) } pub fn db_at(&self, db_path: &Path) -> CargoResult<GitDatabase> { let repo = try!(git2::Repository::open(db_path)); Ok(GitDatabase { remote: self.clone(), path: db_path.to_path_buf(), repo: repo, }) } fn fetch_into(&self, dst: &git2::Repository) -> CargoResult<()> { // Create a local anonymous remote in the repository to fetch the url let url = self.url.to_string(); let refspec = "refs/heads/*:refs/heads/*"; fetch(dst, &url, refspec) } fn clone_into(&self, dst: &Path) -> CargoResult<git2::Repository> { let url = self.url.to_string(); if fs::metadata(&dst).is_ok() { try!(fs::remove_dir_all(dst)); } try!(fs::create_dir_all(dst)); let repo = try!(git2::Repository::init_bare(dst)); try!(fetch(&repo, &url, "refs/heads/*:refs/heads/*")); Ok(repo) } } impl GitDatabase { fn path(&self) -> &Path { &self.path } pub fn copy_to(&self, rev: GitRevision, dest: &Path) -> CargoResult<GitCheckout> { let checkout = match git2::Repository::open(dest) { Ok(repo) => { let checkout = GitCheckout::new(dest, self, rev, repo); if!checkout.is_fresh() { try!(checkout.fetch()); try!(checkout.reset()); assert!(checkout.is_fresh()); } checkout } Err(..) => try!(GitCheckout::clone_into(dest, self, rev)), }; try!(checkout.update_submodules().chain_error(|| { internal("failed to update submodules") })); Ok(checkout) } pub fn rev_for(&self, reference: &GitReference) -> CargoResult<GitRevision> { let id = match *reference { GitReference::Tag(ref s) => { try!((|| { let refname = format!("refs/tags/{}", s); let id = try!(self.repo.refname_to_id(&refname)); let obj = try!(self.repo.find_object(id, None)); let obj = try!(obj.peel(ObjectType::Commit)); Ok(obj.id()) }).chain_error(|| { human(format!("failed to find tag `{}`", s)) })) } GitReference::Branch(ref s) => { try!((|| { let b = try!(self.repo.find_branch(s, git2::BranchType::Local)); b.get().target().chain_error(|| { human(format!("branch `{}` did not have a target", s)) }) }).chain_error(|| { human(format!("failed to find branch `{}`", s)) })) } GitReference::Rev(ref s) => { let obj = try!(self.repo.revparse_single(s)); obj.id() } }; Ok(GitRevision(id)) } pub fn has_ref(&self, reference: &str) -> CargoResult<()> { try!(self.repo.revparse_single(reference)); Ok(()) } } impl<'a> GitCheckout<'a> { fn new(path: &Path, database: &'a GitDatabase, revision: GitRevision, repo: git2::Repository) -> GitCheckout<'a> { GitCheckout { location: path.to_path_buf(), database: database, revision: revision, repo: repo, } } fn clone_into(into: &Path, database: &'a GitDatabase, revision: GitRevision) -> CargoResult<GitCheckout<'a>> { let repo = try!(GitCheckout::clone_repo(database.path(), into)); let checkout = GitCheckout::new(into, database, revision, repo); try!(checkout.reset()); Ok(checkout) } fn clone_repo(source: &Path, into: &Path) -> CargoResult<git2::Repository> { let dirname = into.parent().unwrap(); try!(fs::create_dir_all(&dirname).chain_error(|| { human(format!("Couldn't mkdir {}", dirname.display())) })); if fs::metadata(&into).is_ok() { try!(fs::remove_dir_all(into).chain_error(|| { human(format!("Couldn't rmdir {}", into.display())) })); } let url = try!(source.to_url().map_err(human)); let url = url.to_string(); let repo = try!(git2::Repository::clone(&url, into).chain_error(|| { internal(format!("failed to clone {} into {}", source.display(), into.display())) })); Ok(repo) } fn is_fresh(&self) -> bool { match self.repo.revparse_single("HEAD") { Ok(ref head) if head.id() == self.revision.0 => { // See comments in reset() for why we check this fs::metadata(self.location.join(".cargo-ok")).is_ok() } _ => false, } } fn fetch(&self) -> CargoResult<()> { info!("fetch {}", self.repo.path().display()); let url = try!(self.database.path.to_url().map_err(human)); let url = url.to_string(); let refspec = "refs/heads/*:refs/heads/*"; try!(fetch(&self.repo, &url, refspec)); Ok(()) } fn reset(&self) -> CargoResult<()> { // If we're interrupted while performing this reset (e.g. we die because // of a signal) Cargo needs to be sure to try to check out this repo // again on the next go-round. // // To enable this we have a dummy file in our checkout,.cargo-ok, which // if present means that the repo has been successfully reset and is // ready to go. Hence if we start to do a reset, we make sure this file // *doesn't* exist, and then once we're done we create the file. let ok_file = self.location.join(".cargo-ok"); let _ = fs::remove_file(&ok_file); info!("reset {} to {}", self.repo.path().display(), self.revision); let object = try!(self.repo.find_object(self.revision.0, None)); try!(self.repo.reset(&object, git2::ResetType::Hard, None)); try!(File::create(ok_file)); Ok(()) } fn update_submodules(&self) -> CargoResult<()> { return update_submodules(&self.repo); fn update_submodules(repo: &git2::Repository) -> CargoResult<()> { info!("update submodules for: {:?}", repo.workdir().unwrap()); for mut child in try!(repo.submodules()).into_iter() { try!(child.init(false)); let url = try!(child.url().chain_error(|| { internal("non-utf8 url for submodule") })); // A submodule which is listed in.gitmodules but not actually // checked out will not have a head id, so we should ignore it. let head = match child.head_id() { Some(head) => head, None => continue, }; // If the submodule hasn't been checked out yet, we need to // clone it. If it has been checked out and the head is the same // as the submodule's head, then we can bail out and go to the // next submodule. let head_and_repo = child.open().and_then(|repo| { let target = try!(repo.head()).target(); Ok((target, repo)) }); let repo = match head_and_repo { Ok((head, repo)) => { if child.head_id() == head { continue } repo } Err(..) => { let path = repo.workdir().unwrap().join(child.path()); try!(git2::Repository::clone(url, &path)) } }; // Fetch data from origin and reset to the head commit let refspec = "refs/heads/*:refs/heads/*"; try!(fetch(&repo, url, refspec).chain_error(|| { internal(format!("failed to fetch submodule `{}` from {}", child.name().unwrap_or(""), url)) })); let obj = try!(repo.find_object(head, None)); try!(repo.reset(&obj, git2::ResetType::Hard, None)); try!(update_submodules(&repo)); } Ok(()) } } } fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F) -> CargoResult<T> where F: FnMut(&mut git2::Credentials) -> CargoResult<T> { // Prepare the authentication callbacks. // // We check the `allowed` types of credentials, and we try to do as much as // possible based on that: // // * Prioritize SSH keys from the local ssh agent as they're likely the most // reliable. The username here is prioritized from the credential // callback, then from whatever is configured in git itself, and finally // we fall back to the generic user of `git`. // // * If a username/password is allowed, then we fallback to git2-rs's // implementation of the credential helper. This is what is configured // with `credential.helper` in git, and is the interface for the OSX // keychain, for example. // // * After the above two have failed, we just kinda grapple attempting to // return *something*. // // Note that we keep track of the number of times we've called this callback // because libgit2 will repeatedly give us credentials until we give it a // reason to not do so. If we've been called once and our credentials failed // then we'll be called again, and in this case we assume that the reason // was because the credentials were wrong. let mut cred_helper = git2::CredentialHelper::new(url); cred_helper.config(cfg); let mut called = 0; let res = f(&mut |url, username, allowed| { called += 1; if called >= 2 { return Err(git2::Error::from_str("no authentication available")) } if allowed.contains(git2::SSH_KEY) || allowed.contains(git2::USERNAME) { let user = username.map(|s| s.to_string()) .or_else(|| cred_helper.username.clone()) .unwrap_or("git".to_string()); if allowed.contains(git2::USERNAME) { git2::Cred::username(&user) } else { git2::Cred::ssh_key_from_agent(&user) } } else if allowed.contains(git2::USER_PASS_PLAINTEXT) { git2::Cred::credential_helper(cfg, url, username) } else if allowed.contains(git2::DEFAULT) { git2::Cred::default() } else { Err(git2::Error::from_str("no authentication available")) } }); if called > 0 { res.chain_error(|| { human("failed to authenticate when downloading repository") }) } else { res } } pub fn fetch(repo: &git2::Repository, url: &str, refspec: &str) -> CargoResult<()> { // Create a local anonymous remote in the repository to fetch the url with_authentication(url, &try!(repo.config()), |f| { let mut cb = git2::RemoteCallbacks::new(); cb.credentials(f); let mut remote = try!(repo.remote_anonymous(&url)); let mut opts = git2::FetchOptions::new(); opts.remote_callbacks(cb) .download_tags(git2::AutotagOption::All); try!(remote.fetch(&[refspec], Some(&mut opts), None)); Ok(()) }) }
use std::fs::{self, File};
random_line_split
utils.rs
use std::fmt; use std::path::{Path, PathBuf}; use std::fs::{self, File}; use rustc_serialize::{Encodable, Encoder}; use url::Url; use git2::{self, ObjectType}; use core::GitReference; use util::{CargoResult, ChainError, human, ToUrl, internal}; #[derive(PartialEq, Clone, Debug)] pub struct GitRevision(git2::Oid); impl fmt::Display for GitRevision { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } /// GitRemote represents a remote repository. It gets cloned into a local /// GitDatabase. #[derive(PartialEq,Clone,Debug)] pub struct GitRemote { url: Url, } #[derive(PartialEq,Clone,RustcEncodable)] struct EncodableGitRemote { url: String, } impl Encodable for GitRemote { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitRemote { url: self.url.to_string() }.encode(s) } } /// GitDatabase is a local clone of a remote repository's database. Multiple /// GitCheckouts can be cloned from this GitDatabase. pub struct GitDatabase { remote: GitRemote, path: PathBuf, repo: git2::Repository, } #[derive(RustcEncodable)] pub struct EncodableGitDatabase { remote: GitRemote, path: String, } impl Encodable for GitDatabase { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitDatabase { remote: self.remote.clone(), path: self.path.display().to_string() }.encode(s) } } /// GitCheckout is a local checkout of a particular revision. Calling /// `clone_into` with a reference will resolve the reference into a revision, /// and return a CargoError if no revision for that reference was found. pub struct GitCheckout<'a> { database: &'a GitDatabase, location: PathBuf, revision: GitRevision, repo: git2::Repository, } #[derive(RustcEncodable)] pub struct EncodableGitCheckout { database: EncodableGitDatabase, location: String, revision: String, } impl<'a> Encodable for GitCheckout<'a> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitCheckout { location: self.location.display().to_string(), revision: self.revision.to_string(), database: EncodableGitDatabase { remote: self.database.remote.clone(), path: self.database.path.display().to_string(), }, }.encode(s) } } // Implementations impl GitRemote { pub fn new(url: &Url) -> GitRemote { GitRemote { url: url.clone() } } pub fn url(&self) -> &Url { &self.url } pub fn rev_for(&self, path: &Path, reference: &GitReference) -> CargoResult<GitRevision> { let db = try!(self.db_at(path)); db.rev_for(reference) } pub fn checkout(&self, into: &Path) -> CargoResult<GitDatabase> { let repo = match git2::Repository::open(into) { Ok(repo) => { try!(self.fetch_into(&repo).chain_error(|| { human(format!("failed to fetch into {}", into.display())) })); repo } Err(..) => { try!(self.clone_into(into).chain_error(|| { human(format!("failed to clone into: {}", into.display())) })) } }; Ok(GitDatabase { remote: self.clone(), path: into.to_path_buf(), repo: repo, }) } pub fn db_at(&self, db_path: &Path) -> CargoResult<GitDatabase> { let repo = try!(git2::Repository::open(db_path)); Ok(GitDatabase { remote: self.clone(), path: db_path.to_path_buf(), repo: repo, }) } fn fetch_into(&self, dst: &git2::Repository) -> CargoResult<()> { // Create a local anonymous remote in the repository to fetch the url let url = self.url.to_string(); let refspec = "refs/heads/*:refs/heads/*"; fetch(dst, &url, refspec) } fn clone_into(&self, dst: &Path) -> CargoResult<git2::Repository> { let url = self.url.to_string(); if fs::metadata(&dst).is_ok() { try!(fs::remove_dir_all(dst)); } try!(fs::create_dir_all(dst)); let repo = try!(git2::Repository::init_bare(dst)); try!(fetch(&repo, &url, "refs/heads/*:refs/heads/*")); Ok(repo) } } impl GitDatabase { fn path(&self) -> &Path { &self.path } pub fn copy_to(&self, rev: GitRevision, dest: &Path) -> CargoResult<GitCheckout> { let checkout = match git2::Repository::open(dest) { Ok(repo) => { let checkout = GitCheckout::new(dest, self, rev, repo); if!checkout.is_fresh() { try!(checkout.fetch()); try!(checkout.reset()); assert!(checkout.is_fresh()); } checkout } Err(..) => try!(GitCheckout::clone_into(dest, self, rev)), }; try!(checkout.update_submodules().chain_error(|| { internal("failed to update submodules") })); Ok(checkout) } pub fn rev_for(&self, reference: &GitReference) -> CargoResult<GitRevision> { let id = match *reference { GitReference::Tag(ref s) => { try!((|| { let refname = format!("refs/tags/{}", s); let id = try!(self.repo.refname_to_id(&refname)); let obj = try!(self.repo.find_object(id, None)); let obj = try!(obj.peel(ObjectType::Commit)); Ok(obj.id()) }).chain_error(|| { human(format!("failed to find tag `{}`", s)) })) } GitReference::Branch(ref s) => { try!((|| { let b = try!(self.repo.find_branch(s, git2::BranchType::Local)); b.get().target().chain_error(|| { human(format!("branch `{}` did not have a target", s)) }) }).chain_error(|| { human(format!("failed to find branch `{}`", s)) })) } GitReference::Rev(ref s) => { let obj = try!(self.repo.revparse_single(s)); obj.id() } }; Ok(GitRevision(id)) } pub fn has_ref(&self, reference: &str) -> CargoResult<()> { try!(self.repo.revparse_single(reference)); Ok(()) } } impl<'a> GitCheckout<'a> { fn new(path: &Path, database: &'a GitDatabase, revision: GitRevision, repo: git2::Repository) -> GitCheckout<'a> { GitCheckout { location: path.to_path_buf(), database: database, revision: revision, repo: repo, } } fn clone_into(into: &Path, database: &'a GitDatabase, revision: GitRevision) -> CargoResult<GitCheckout<'a>> { let repo = try!(GitCheckout::clone_repo(database.path(), into)); let checkout = GitCheckout::new(into, database, revision, repo); try!(checkout.reset()); Ok(checkout) } fn clone_repo(source: &Path, into: &Path) -> CargoResult<git2::Repository> { let dirname = into.parent().unwrap(); try!(fs::create_dir_all(&dirname).chain_error(|| { human(format!("Couldn't mkdir {}", dirname.display())) })); if fs::metadata(&into).is_ok() { try!(fs::remove_dir_all(into).chain_error(|| { human(format!("Couldn't rmdir {}", into.display())) })); } let url = try!(source.to_url().map_err(human)); let url = url.to_string(); let repo = try!(git2::Repository::clone(&url, into).chain_error(|| { internal(format!("failed to clone {} into {}", source.display(), into.display())) })); Ok(repo) } fn is_fresh(&self) -> bool { match self.repo.revparse_single("HEAD") { Ok(ref head) if head.id() == self.revision.0 => { // See comments in reset() for why we check this fs::metadata(self.location.join(".cargo-ok")).is_ok() } _ => false, } } fn fetch(&self) -> CargoResult<()> { info!("fetch {}", self.repo.path().display()); let url = try!(self.database.path.to_url().map_err(human)); let url = url.to_string(); let refspec = "refs/heads/*:refs/heads/*"; try!(fetch(&self.repo, &url, refspec)); Ok(()) } fn
(&self) -> CargoResult<()> { // If we're interrupted while performing this reset (e.g. we die because // of a signal) Cargo needs to be sure to try to check out this repo // again on the next go-round. // // To enable this we have a dummy file in our checkout,.cargo-ok, which // if present means that the repo has been successfully reset and is // ready to go. Hence if we start to do a reset, we make sure this file // *doesn't* exist, and then once we're done we create the file. let ok_file = self.location.join(".cargo-ok"); let _ = fs::remove_file(&ok_file); info!("reset {} to {}", self.repo.path().display(), self.revision); let object = try!(self.repo.find_object(self.revision.0, None)); try!(self.repo.reset(&object, git2::ResetType::Hard, None)); try!(File::create(ok_file)); Ok(()) } fn update_submodules(&self) -> CargoResult<()> { return update_submodules(&self.repo); fn update_submodules(repo: &git2::Repository) -> CargoResult<()> { info!("update submodules for: {:?}", repo.workdir().unwrap()); for mut child in try!(repo.submodules()).into_iter() { try!(child.init(false)); let url = try!(child.url().chain_error(|| { internal("non-utf8 url for submodule") })); // A submodule which is listed in.gitmodules but not actually // checked out will not have a head id, so we should ignore it. let head = match child.head_id() { Some(head) => head, None => continue, }; // If the submodule hasn't been checked out yet, we need to // clone it. If it has been checked out and the head is the same // as the submodule's head, then we can bail out and go to the // next submodule. let head_and_repo = child.open().and_then(|repo| { let target = try!(repo.head()).target(); Ok((target, repo)) }); let repo = match head_and_repo { Ok((head, repo)) => { if child.head_id() == head { continue } repo } Err(..) => { let path = repo.workdir().unwrap().join(child.path()); try!(git2::Repository::clone(url, &path)) } }; // Fetch data from origin and reset to the head commit let refspec = "refs/heads/*:refs/heads/*"; try!(fetch(&repo, url, refspec).chain_error(|| { internal(format!("failed to fetch submodule `{}` from {}", child.name().unwrap_or(""), url)) })); let obj = try!(repo.find_object(head, None)); try!(repo.reset(&obj, git2::ResetType::Hard, None)); try!(update_submodules(&repo)); } Ok(()) } } } fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F) -> CargoResult<T> where F: FnMut(&mut git2::Credentials) -> CargoResult<T> { // Prepare the authentication callbacks. // // We check the `allowed` types of credentials, and we try to do as much as // possible based on that: // // * Prioritize SSH keys from the local ssh agent as they're likely the most // reliable. The username here is prioritized from the credential // callback, then from whatever is configured in git itself, and finally // we fall back to the generic user of `git`. // // * If a username/password is allowed, then we fallback to git2-rs's // implementation of the credential helper. This is what is configured // with `credential.helper` in git, and is the interface for the OSX // keychain, for example. // // * After the above two have failed, we just kinda grapple attempting to // return *something*. // // Note that we keep track of the number of times we've called this callback // because libgit2 will repeatedly give us credentials until we give it a // reason to not do so. If we've been called once and our credentials failed // then we'll be called again, and in this case we assume that the reason // was because the credentials were wrong. let mut cred_helper = git2::CredentialHelper::new(url); cred_helper.config(cfg); let mut called = 0; let res = f(&mut |url, username, allowed| { called += 1; if called >= 2 { return Err(git2::Error::from_str("no authentication available")) } if allowed.contains(git2::SSH_KEY) || allowed.contains(git2::USERNAME) { let user = username.map(|s| s.to_string()) .or_else(|| cred_helper.username.clone()) .unwrap_or("git".to_string()); if allowed.contains(git2::USERNAME) { git2::Cred::username(&user) } else { git2::Cred::ssh_key_from_agent(&user) } } else if allowed.contains(git2::USER_PASS_PLAINTEXT) { git2::Cred::credential_helper(cfg, url, username) } else if allowed.contains(git2::DEFAULT) { git2::Cred::default() } else { Err(git2::Error::from_str("no authentication available")) } }); if called > 0 { res.chain_error(|| { human("failed to authenticate when downloading repository") }) } else { res } } pub fn fetch(repo: &git2::Repository, url: &str, refspec: &str) -> CargoResult<()> { // Create a local anonymous remote in the repository to fetch the url with_authentication(url, &try!(repo.config()), |f| { let mut cb = git2::RemoteCallbacks::new(); cb.credentials(f); let mut remote = try!(repo.remote_anonymous(&url)); let mut opts = git2::FetchOptions::new(); opts.remote_callbacks(cb) .download_tags(git2::AutotagOption::All); try!(remote.fetch(&[refspec], Some(&mut opts), None)); Ok(()) }) }
reset
identifier_name
utils.rs
use std::fmt; use std::path::{Path, PathBuf}; use std::fs::{self, File}; use rustc_serialize::{Encodable, Encoder}; use url::Url; use git2::{self, ObjectType}; use core::GitReference; use util::{CargoResult, ChainError, human, ToUrl, internal}; #[derive(PartialEq, Clone, Debug)] pub struct GitRevision(git2::Oid); impl fmt::Display for GitRevision { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } /// GitRemote represents a remote repository. It gets cloned into a local /// GitDatabase. #[derive(PartialEq,Clone,Debug)] pub struct GitRemote { url: Url, } #[derive(PartialEq,Clone,RustcEncodable)] struct EncodableGitRemote { url: String, } impl Encodable for GitRemote { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitRemote { url: self.url.to_string() }.encode(s) } } /// GitDatabase is a local clone of a remote repository's database. Multiple /// GitCheckouts can be cloned from this GitDatabase. pub struct GitDatabase { remote: GitRemote, path: PathBuf, repo: git2::Repository, } #[derive(RustcEncodable)] pub struct EncodableGitDatabase { remote: GitRemote, path: String, } impl Encodable for GitDatabase { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitDatabase { remote: self.remote.clone(), path: self.path.display().to_string() }.encode(s) } } /// GitCheckout is a local checkout of a particular revision. Calling /// `clone_into` with a reference will resolve the reference into a revision, /// and return a CargoError if no revision for that reference was found. pub struct GitCheckout<'a> { database: &'a GitDatabase, location: PathBuf, revision: GitRevision, repo: git2::Repository, } #[derive(RustcEncodable)] pub struct EncodableGitCheckout { database: EncodableGitDatabase, location: String, revision: String, } impl<'a> Encodable for GitCheckout<'a> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitCheckout { location: self.location.display().to_string(), revision: self.revision.to_string(), database: EncodableGitDatabase { remote: self.database.remote.clone(), path: self.database.path.display().to_string(), }, }.encode(s) } } // Implementations impl GitRemote { pub fn new(url: &Url) -> GitRemote { GitRemote { url: url.clone() } } pub fn url(&self) -> &Url { &self.url } pub fn rev_for(&self, path: &Path, reference: &GitReference) -> CargoResult<GitRevision> { let db = try!(self.db_at(path)); db.rev_for(reference) } pub fn checkout(&self, into: &Path) -> CargoResult<GitDatabase> { let repo = match git2::Repository::open(into) { Ok(repo) => { try!(self.fetch_into(&repo).chain_error(|| { human(format!("failed to fetch into {}", into.display())) })); repo } Err(..) => { try!(self.clone_into(into).chain_error(|| { human(format!("failed to clone into: {}", into.display())) })) } }; Ok(GitDatabase { remote: self.clone(), path: into.to_path_buf(), repo: repo, }) } pub fn db_at(&self, db_path: &Path) -> CargoResult<GitDatabase> { let repo = try!(git2::Repository::open(db_path)); Ok(GitDatabase { remote: self.clone(), path: db_path.to_path_buf(), repo: repo, }) } fn fetch_into(&self, dst: &git2::Repository) -> CargoResult<()> { // Create a local anonymous remote in the repository to fetch the url let url = self.url.to_string(); let refspec = "refs/heads/*:refs/heads/*"; fetch(dst, &url, refspec) } fn clone_into(&self, dst: &Path) -> CargoResult<git2::Repository> { let url = self.url.to_string(); if fs::metadata(&dst).is_ok() { try!(fs::remove_dir_all(dst)); } try!(fs::create_dir_all(dst)); let repo = try!(git2::Repository::init_bare(dst)); try!(fetch(&repo, &url, "refs/heads/*:refs/heads/*")); Ok(repo) } } impl GitDatabase { fn path(&self) -> &Path { &self.path } pub fn copy_to(&self, rev: GitRevision, dest: &Path) -> CargoResult<GitCheckout> { let checkout = match git2::Repository::open(dest) { Ok(repo) => { let checkout = GitCheckout::new(dest, self, rev, repo); if!checkout.is_fresh() { try!(checkout.fetch()); try!(checkout.reset()); assert!(checkout.is_fresh()); } checkout } Err(..) => try!(GitCheckout::clone_into(dest, self, rev)), }; try!(checkout.update_submodules().chain_error(|| { internal("failed to update submodules") })); Ok(checkout) } pub fn rev_for(&self, reference: &GitReference) -> CargoResult<GitRevision> { let id = match *reference { GitReference::Tag(ref s) => { try!((|| { let refname = format!("refs/tags/{}", s); let id = try!(self.repo.refname_to_id(&refname)); let obj = try!(self.repo.find_object(id, None)); let obj = try!(obj.peel(ObjectType::Commit)); Ok(obj.id()) }).chain_error(|| { human(format!("failed to find tag `{}`", s)) })) } GitReference::Branch(ref s) => { try!((|| { let b = try!(self.repo.find_branch(s, git2::BranchType::Local)); b.get().target().chain_error(|| { human(format!("branch `{}` did not have a target", s)) }) }).chain_error(|| { human(format!("failed to find branch `{}`", s)) })) } GitReference::Rev(ref s) => { let obj = try!(self.repo.revparse_single(s)); obj.id() } }; Ok(GitRevision(id)) } pub fn has_ref(&self, reference: &str) -> CargoResult<()> { try!(self.repo.revparse_single(reference)); Ok(()) } } impl<'a> GitCheckout<'a> { fn new(path: &Path, database: &'a GitDatabase, revision: GitRevision, repo: git2::Repository) -> GitCheckout<'a> { GitCheckout { location: path.to_path_buf(), database: database, revision: revision, repo: repo, } } fn clone_into(into: &Path, database: &'a GitDatabase, revision: GitRevision) -> CargoResult<GitCheckout<'a>> { let repo = try!(GitCheckout::clone_repo(database.path(), into)); let checkout = GitCheckout::new(into, database, revision, repo); try!(checkout.reset()); Ok(checkout) } fn clone_repo(source: &Path, into: &Path) -> CargoResult<git2::Repository> { let dirname = into.parent().unwrap(); try!(fs::create_dir_all(&dirname).chain_error(|| { human(format!("Couldn't mkdir {}", dirname.display())) })); if fs::metadata(&into).is_ok() { try!(fs::remove_dir_all(into).chain_error(|| { human(format!("Couldn't rmdir {}", into.display())) })); } let url = try!(source.to_url().map_err(human)); let url = url.to_string(); let repo = try!(git2::Repository::clone(&url, into).chain_error(|| { internal(format!("failed to clone {} into {}", source.display(), into.display())) })); Ok(repo) } fn is_fresh(&self) -> bool { match self.repo.revparse_single("HEAD") { Ok(ref head) if head.id() == self.revision.0 => { // See comments in reset() for why we check this fs::metadata(self.location.join(".cargo-ok")).is_ok() } _ => false, } } fn fetch(&self) -> CargoResult<()> { info!("fetch {}", self.repo.path().display()); let url = try!(self.database.path.to_url().map_err(human)); let url = url.to_string(); let refspec = "refs/heads/*:refs/heads/*"; try!(fetch(&self.repo, &url, refspec)); Ok(()) } fn reset(&self) -> CargoResult<()> { // If we're interrupted while performing this reset (e.g. we die because // of a signal) Cargo needs to be sure to try to check out this repo // again on the next go-round. // // To enable this we have a dummy file in our checkout,.cargo-ok, which // if present means that the repo has been successfully reset and is // ready to go. Hence if we start to do a reset, we make sure this file // *doesn't* exist, and then once we're done we create the file. let ok_file = self.location.join(".cargo-ok"); let _ = fs::remove_file(&ok_file); info!("reset {} to {}", self.repo.path().display(), self.revision); let object = try!(self.repo.find_object(self.revision.0, None)); try!(self.repo.reset(&object, git2::ResetType::Hard, None)); try!(File::create(ok_file)); Ok(()) } fn update_submodules(&self) -> CargoResult<()> { return update_submodules(&self.repo); fn update_submodules(repo: &git2::Repository) -> CargoResult<()>
let head_and_repo = child.open().and_then(|repo| { let target = try!(repo.head()).target(); Ok((target, repo)) }); let repo = match head_and_repo { Ok((head, repo)) => { if child.head_id() == head { continue } repo } Err(..) => { let path = repo.workdir().unwrap().join(child.path()); try!(git2::Repository::clone(url, &path)) } }; // Fetch data from origin and reset to the head commit let refspec = "refs/heads/*:refs/heads/*"; try!(fetch(&repo, url, refspec).chain_error(|| { internal(format!("failed to fetch submodule `{}` from {}", child.name().unwrap_or(""), url)) })); let obj = try!(repo.find_object(head, None)); try!(repo.reset(&obj, git2::ResetType::Hard, None)); try!(update_submodules(&repo)); } Ok(()) } } } fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F) -> CargoResult<T> where F: FnMut(&mut git2::Credentials) -> CargoResult<T> { // Prepare the authentication callbacks. // // We check the `allowed` types of credentials, and we try to do as much as // possible based on that: // // * Prioritize SSH keys from the local ssh agent as they're likely the most // reliable. The username here is prioritized from the credential // callback, then from whatever is configured in git itself, and finally // we fall back to the generic user of `git`. // // * If a username/password is allowed, then we fallback to git2-rs's // implementation of the credential helper. This is what is configured // with `credential.helper` in git, and is the interface for the OSX // keychain, for example. // // * After the above two have failed, we just kinda grapple attempting to // return *something*. // // Note that we keep track of the number of times we've called this callback // because libgit2 will repeatedly give us credentials until we give it a // reason to not do so. If we've been called once and our credentials failed // then we'll be called again, and in this case we assume that the reason // was because the credentials were wrong. let mut cred_helper = git2::CredentialHelper::new(url); cred_helper.config(cfg); let mut called = 0; let res = f(&mut |url, username, allowed| { called += 1; if called >= 2 { return Err(git2::Error::from_str("no authentication available")) } if allowed.contains(git2::SSH_KEY) || allowed.contains(git2::USERNAME) { let user = username.map(|s| s.to_string()) .or_else(|| cred_helper.username.clone()) .unwrap_or("git".to_string()); if allowed.contains(git2::USERNAME) { git2::Cred::username(&user) } else { git2::Cred::ssh_key_from_agent(&user) } } else if allowed.contains(git2::USER_PASS_PLAINTEXT) { git2::Cred::credential_helper(cfg, url, username) } else if allowed.contains(git2::DEFAULT) { git2::Cred::default() } else { Err(git2::Error::from_str("no authentication available")) } }); if called > 0 { res.chain_error(|| { human("failed to authenticate when downloading repository") }) } else { res } } pub fn fetch(repo: &git2::Repository, url: &str, refspec: &str) -> CargoResult<()> { // Create a local anonymous remote in the repository to fetch the url with_authentication(url, &try!(repo.config()), |f| { let mut cb = git2::RemoteCallbacks::new(); cb.credentials(f); let mut remote = try!(repo.remote_anonymous(&url)); let mut opts = git2::FetchOptions::new(); opts.remote_callbacks(cb) .download_tags(git2::AutotagOption::All); try!(remote.fetch(&[refspec], Some(&mut opts), None)); Ok(()) }) }
{ info!("update submodules for: {:?}", repo.workdir().unwrap()); for mut child in try!(repo.submodules()).into_iter() { try!(child.init(false)); let url = try!(child.url().chain_error(|| { internal("non-utf8 url for submodule") })); // A submodule which is listed in .gitmodules but not actually // checked out will not have a head id, so we should ignore it. let head = match child.head_id() { Some(head) => head, None => continue, }; // If the submodule hasn't been checked out yet, we need to // clone it. If it has been checked out and the head is the same // as the submodule's head, then we can bail out and go to the // next submodule.
identifier_body
realloc-16687.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // alloc::heap::reallocate test. // // Ideally this would be revised to use no_std, but for now it serves // well enough to reproduce (and illustrate) the bug from #16687. #![feature(alloc)] extern crate alloc; use alloc::heap; use std::ptr; use std::iter::repeat; fn main() { unsafe { assert!(test_triangle()); } } unsafe fn test_triangle() -> bool { static COUNT : usize = 16; let mut ascend = repeat(ptr::null_mut()).take(COUNT).collect::<Vec<_>>(); let ascend = &mut *ascend; static ALIGN : usize = 1; // Checks that `ascend` forms triangle of ascending size formed // from pairs of rows (where each pair of rows is equally sized), // and the elements of the triangle match their row-pair index. unsafe fn sanity_check(ascend: &[*mut u8]) { for i in 0..COUNT / 2 { let (p0, p1, size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); for j in 0..size { assert_eq!(*p0.offset(j as isize), i as u8); assert_eq!(*p1.offset(j as isize), i as u8); } } } static PRINT : bool = false; unsafe fn allocate(size: usize, align: usize) -> *mut u8 { if PRINT { println!("allocate(size={} align={})", size, align); } let ret = heap::allocate(size, align); if ret.is_null() { alloc::oom() } if PRINT { println!("allocate(size={} align={}) ret: 0x{:010x}", size, align, ret as usize); } ret } unsafe fn deallocate(ptr: *mut u8, size: usize, align: usize)
unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 { if PRINT { println!("reallocate(ptr=0x{:010x} old_size={} size={} align={})", ptr as usize, old_size, size, align); } let ret = heap::reallocate(ptr, old_size, size, align); if ret.is_null() { alloc::oom() } if PRINT { println!("reallocate(ptr=0x{:010x} old_size={} size={} align={}) \ ret: 0x{:010x}", ptr as usize, old_size, size, align, ret as usize); } ret } fn idx_to_size(i: usize) -> usize { (i+1) * 10 } // Allocate pairs of rows that form a triangle shape. (Hope is // that at least two rows will be allocated near each other, so // that we trigger the bug (a buffer overrun) in an observable // way.) for i in 0..COUNT / 2 { let size = idx_to_size(i); ascend[2*i] = allocate(size, ALIGN); ascend[2*i+1] = allocate(size, ALIGN); } // Initialize each pair of rows to distinct value. for i in 0..COUNT / 2 { let (p0, p1, size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); for j in 0..size { *p0.offset(j as isize) = i as u8; *p1.offset(j as isize) = i as u8; } } sanity_check(&*ascend); test_1(ascend); // triangle -> square test_2(ascend); // square -> triangle test_3(ascend); // triangle -> square test_4(ascend); // square -> triangle for i in 0..COUNT / 2 { let size = idx_to_size(i); deallocate(ascend[2*i], size, ALIGN); deallocate(ascend[2*i+1], size, ALIGN); } return true; // Test 1: turn the triangle into a square (in terms of // allocation; initialized portion remains a triangle) by // realloc'ing each row from top to bottom, and checking all the // rows as we go. unsafe fn test_1(ascend: &mut [*mut u8]) { let new_size = idx_to_size(COUNT-1); for i in 0..COUNT / 2 { let (p0, p1, old_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(old_size < new_size); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 2: turn the square back into a triangle, top to bottom. unsafe fn test_2(ascend: &mut [*mut u8]) { let old_size = idx_to_size(COUNT-1); for i in 0..COUNT / 2 { let (p0, p1, new_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(new_size < old_size); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 3: turn triangle into a square, bottom to top. unsafe fn test_3(ascend: &mut [*mut u8]) { let new_size = idx_to_size(COUNT-1); for i in (0..COUNT / 2).rev() { let (p0, p1, old_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(old_size < new_size); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 4: turn the square back into a triangle, bottom to top. unsafe fn test_4(ascend: &mut [*mut u8]) { let old_size = idx_to_size(COUNT-1); for i in (0..COUNT / 2).rev() { let (p0, p1, new_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(new_size < old_size); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); } } }
{ if PRINT { println!("deallocate(ptr=0x{:010x} size={} align={})", ptr as usize, size, align); } heap::deallocate(ptr, size, align); }
identifier_body
realloc-16687.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // alloc::heap::reallocate test. // // Ideally this would be revised to use no_std, but for now it serves // well enough to reproduce (and illustrate) the bug from #16687. #![feature(alloc)] extern crate alloc; use alloc::heap; use std::ptr; use std::iter::repeat; fn main() { unsafe { assert!(test_triangle()); } } unsafe fn test_triangle() -> bool { static COUNT : usize = 16; let mut ascend = repeat(ptr::null_mut()).take(COUNT).collect::<Vec<_>>(); let ascend = &mut *ascend; static ALIGN : usize = 1; // Checks that `ascend` forms triangle of ascending size formed // from pairs of rows (where each pair of rows is equally sized), // and the elements of the triangle match their row-pair index. unsafe fn sanity_check(ascend: &[*mut u8]) { for i in 0..COUNT / 2 { let (p0, p1, size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); for j in 0..size { assert_eq!(*p0.offset(j as isize), i as u8); assert_eq!(*p1.offset(j as isize), i as u8); } } } static PRINT : bool = false; unsafe fn allocate(size: usize, align: usize) -> *mut u8 { if PRINT { println!("allocate(size={} align={})", size, align); } let ret = heap::allocate(size, align); if ret.is_null() { alloc::oom() } if PRINT { println!("allocate(size={} align={}) ret: 0x{:010x}", size, align, ret as usize); } ret } unsafe fn deallocate(ptr: *mut u8, size: usize, align: usize) { if PRINT { println!("deallocate(ptr=0x{:010x} size={} align={})", ptr as usize, size, align); } heap::deallocate(ptr, size, align); } unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 { if PRINT { println!("reallocate(ptr=0x{:010x} old_size={} size={} align={})", ptr as usize, old_size, size, align); } let ret = heap::reallocate(ptr, old_size, size, align); if ret.is_null() { alloc::oom() } if PRINT { println!("reallocate(ptr=0x{:010x} old_size={} size={} align={}) \ ret: 0x{:010x}", ptr as usize, old_size, size, align, ret as usize); } ret } fn idx_to_size(i: usize) -> usize { (i+1) * 10 } // Allocate pairs of rows that form a triangle shape. (Hope is // that at least two rows will be allocated near each other, so // that we trigger the bug (a buffer overrun) in an observable // way.) for i in 0..COUNT / 2 { let size = idx_to_size(i); ascend[2*i] = allocate(size, ALIGN); ascend[2*i+1] = allocate(size, ALIGN); } // Initialize each pair of rows to distinct value. for i in 0..COUNT / 2 { let (p0, p1, size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); for j in 0..size { *p0.offset(j as isize) = i as u8; *p1.offset(j as isize) = i as u8; } } sanity_check(&*ascend); test_1(ascend); // triangle -> square test_2(ascend); // square -> triangle test_3(ascend); // triangle -> square test_4(ascend); // square -> triangle for i in 0..COUNT / 2 { let size = idx_to_size(i); deallocate(ascend[2*i], size, ALIGN); deallocate(ascend[2*i+1], size, ALIGN); } return true; // Test 1: turn the triangle into a square (in terms of // allocation; initialized portion remains a triangle) by // realloc'ing each row from top to bottom, and checking all the // rows as we go. unsafe fn test_1(ascend: &mut [*mut u8]) { let new_size = idx_to_size(COUNT-1); for i in 0..COUNT / 2 { let (p0, p1, old_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(old_size < new_size); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); }
} // Test 2: turn the square back into a triangle, top to bottom. unsafe fn test_2(ascend: &mut [*mut u8]) { let old_size = idx_to_size(COUNT-1); for i in 0..COUNT / 2 { let (p0, p1, new_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(new_size < old_size); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 3: turn triangle into a square, bottom to top. unsafe fn test_3(ascend: &mut [*mut u8]) { let new_size = idx_to_size(COUNT-1); for i in (0..COUNT / 2).rev() { let (p0, p1, old_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(old_size < new_size); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 4: turn the square back into a triangle, bottom to top. unsafe fn test_4(ascend: &mut [*mut u8]) { let old_size = idx_to_size(COUNT-1); for i in (0..COUNT / 2).rev() { let (p0, p1, new_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(new_size < old_size); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); } } }
random_line_split
realloc-16687.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // alloc::heap::reallocate test. // // Ideally this would be revised to use no_std, but for now it serves // well enough to reproduce (and illustrate) the bug from #16687. #![feature(alloc)] extern crate alloc; use alloc::heap; use std::ptr; use std::iter::repeat; fn main() { unsafe { assert!(test_triangle()); } } unsafe fn test_triangle() -> bool { static COUNT : usize = 16; let mut ascend = repeat(ptr::null_mut()).take(COUNT).collect::<Vec<_>>(); let ascend = &mut *ascend; static ALIGN : usize = 1; // Checks that `ascend` forms triangle of ascending size formed // from pairs of rows (where each pair of rows is equally sized), // and the elements of the triangle match their row-pair index. unsafe fn sanity_check(ascend: &[*mut u8]) { for i in 0..COUNT / 2 { let (p0, p1, size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); for j in 0..size { assert_eq!(*p0.offset(j as isize), i as u8); assert_eq!(*p1.offset(j as isize), i as u8); } } } static PRINT : bool = false; unsafe fn allocate(size: usize, align: usize) -> *mut u8 { if PRINT { println!("allocate(size={} align={})", size, align); } let ret = heap::allocate(size, align); if ret.is_null() { alloc::oom() } if PRINT { println!("allocate(size={} align={}) ret: 0x{:010x}", size, align, ret as usize); } ret } unsafe fn deallocate(ptr: *mut u8, size: usize, align: usize) { if PRINT { println!("deallocate(ptr=0x{:010x} size={} align={})", ptr as usize, size, align); } heap::deallocate(ptr, size, align); } unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 { if PRINT { println!("reallocate(ptr=0x{:010x} old_size={} size={} align={})", ptr as usize, old_size, size, align); } let ret = heap::reallocate(ptr, old_size, size, align); if ret.is_null()
if PRINT { println!("reallocate(ptr=0x{:010x} old_size={} size={} align={}) \ ret: 0x{:010x}", ptr as usize, old_size, size, align, ret as usize); } ret } fn idx_to_size(i: usize) -> usize { (i+1) * 10 } // Allocate pairs of rows that form a triangle shape. (Hope is // that at least two rows will be allocated near each other, so // that we trigger the bug (a buffer overrun) in an observable // way.) for i in 0..COUNT / 2 { let size = idx_to_size(i); ascend[2*i] = allocate(size, ALIGN); ascend[2*i+1] = allocate(size, ALIGN); } // Initialize each pair of rows to distinct value. for i in 0..COUNT / 2 { let (p0, p1, size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); for j in 0..size { *p0.offset(j as isize) = i as u8; *p1.offset(j as isize) = i as u8; } } sanity_check(&*ascend); test_1(ascend); // triangle -> square test_2(ascend); // square -> triangle test_3(ascend); // triangle -> square test_4(ascend); // square -> triangle for i in 0..COUNT / 2 { let size = idx_to_size(i); deallocate(ascend[2*i], size, ALIGN); deallocate(ascend[2*i+1], size, ALIGN); } return true; // Test 1: turn the triangle into a square (in terms of // allocation; initialized portion remains a triangle) by // realloc'ing each row from top to bottom, and checking all the // rows as we go. unsafe fn test_1(ascend: &mut [*mut u8]) { let new_size = idx_to_size(COUNT-1); for i in 0..COUNT / 2 { let (p0, p1, old_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(old_size < new_size); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 2: turn the square back into a triangle, top to bottom. unsafe fn test_2(ascend: &mut [*mut u8]) { let old_size = idx_to_size(COUNT-1); for i in 0..COUNT / 2 { let (p0, p1, new_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(new_size < old_size); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 3: turn triangle into a square, bottom to top. unsafe fn test_3(ascend: &mut [*mut u8]) { let new_size = idx_to_size(COUNT-1); for i in (0..COUNT / 2).rev() { let (p0, p1, old_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(old_size < new_size); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 4: turn the square back into a triangle, bottom to top. unsafe fn test_4(ascend: &mut [*mut u8]) { let old_size = idx_to_size(COUNT-1); for i in (0..COUNT / 2).rev() { let (p0, p1, new_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(new_size < old_size); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); } } }
{ alloc::oom() }
conditional_block
realloc-16687.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // alloc::heap::reallocate test. // // Ideally this would be revised to use no_std, but for now it serves // well enough to reproduce (and illustrate) the bug from #16687. #![feature(alloc)] extern crate alloc; use alloc::heap; use std::ptr; use std::iter::repeat; fn main() { unsafe { assert!(test_triangle()); } } unsafe fn test_triangle() -> bool { static COUNT : usize = 16; let mut ascend = repeat(ptr::null_mut()).take(COUNT).collect::<Vec<_>>(); let ascend = &mut *ascend; static ALIGN : usize = 1; // Checks that `ascend` forms triangle of ascending size formed // from pairs of rows (where each pair of rows is equally sized), // and the elements of the triangle match their row-pair index. unsafe fn sanity_check(ascend: &[*mut u8]) { for i in 0..COUNT / 2 { let (p0, p1, size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); for j in 0..size { assert_eq!(*p0.offset(j as isize), i as u8); assert_eq!(*p1.offset(j as isize), i as u8); } } } static PRINT : bool = false; unsafe fn allocate(size: usize, align: usize) -> *mut u8 { if PRINT { println!("allocate(size={} align={})", size, align); } let ret = heap::allocate(size, align); if ret.is_null() { alloc::oom() } if PRINT { println!("allocate(size={} align={}) ret: 0x{:010x}", size, align, ret as usize); } ret } unsafe fn deallocate(ptr: *mut u8, size: usize, align: usize) { if PRINT { println!("deallocate(ptr=0x{:010x} size={} align={})", ptr as usize, size, align); } heap::deallocate(ptr, size, align); } unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 { if PRINT { println!("reallocate(ptr=0x{:010x} old_size={} size={} align={})", ptr as usize, old_size, size, align); } let ret = heap::reallocate(ptr, old_size, size, align); if ret.is_null() { alloc::oom() } if PRINT { println!("reallocate(ptr=0x{:010x} old_size={} size={} align={}) \ ret: 0x{:010x}", ptr as usize, old_size, size, align, ret as usize); } ret } fn idx_to_size(i: usize) -> usize { (i+1) * 10 } // Allocate pairs of rows that form a triangle shape. (Hope is // that at least two rows will be allocated near each other, so // that we trigger the bug (a buffer overrun) in an observable // way.) for i in 0..COUNT / 2 { let size = idx_to_size(i); ascend[2*i] = allocate(size, ALIGN); ascend[2*i+1] = allocate(size, ALIGN); } // Initialize each pair of rows to distinct value. for i in 0..COUNT / 2 { let (p0, p1, size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); for j in 0..size { *p0.offset(j as isize) = i as u8; *p1.offset(j as isize) = i as u8; } } sanity_check(&*ascend); test_1(ascend); // triangle -> square test_2(ascend); // square -> triangle test_3(ascend); // triangle -> square test_4(ascend); // square -> triangle for i in 0..COUNT / 2 { let size = idx_to_size(i); deallocate(ascend[2*i], size, ALIGN); deallocate(ascend[2*i+1], size, ALIGN); } return true; // Test 1: turn the triangle into a square (in terms of // allocation; initialized portion remains a triangle) by // realloc'ing each row from top to bottom, and checking all the // rows as we go. unsafe fn
(ascend: &mut [*mut u8]) { let new_size = idx_to_size(COUNT-1); for i in 0..COUNT / 2 { let (p0, p1, old_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(old_size < new_size); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 2: turn the square back into a triangle, top to bottom. unsafe fn test_2(ascend: &mut [*mut u8]) { let old_size = idx_to_size(COUNT-1); for i in 0..COUNT / 2 { let (p0, p1, new_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(new_size < old_size); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 3: turn triangle into a square, bottom to top. unsafe fn test_3(ascend: &mut [*mut u8]) { let new_size = idx_to_size(COUNT-1); for i in (0..COUNT / 2).rev() { let (p0, p1, old_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(old_size < new_size); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); } } // Test 4: turn the square back into a triangle, bottom to top. unsafe fn test_4(ascend: &mut [*mut u8]) { let old_size = idx_to_size(COUNT-1); for i in (0..COUNT / 2).rev() { let (p0, p1, new_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i)); assert!(new_size < old_size); ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN); sanity_check(&*ascend); ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN); sanity_check(&*ascend); } } }
test_1
identifier_name
issue-53789-2.rs
// Regression test for #53789. // // compile-pass #![feature(nll)] #![allow(unused_variables)] use std::collections::BTreeMap; use std::ops::Range; use std::cmp::Ord; macro_rules! valuetree { () => { type ValueTree = <Self::Strategy as $crate::Strategy>::Value; }; } macro_rules! product_unpack { ($factor: pat) => { ($factor,) }; ($($factor: pat),*) => { ( $( $factor ),* ) }; ($($factor: pat),*,) => { ( $( $factor ),* ) }; } macro_rules! product_type { ($factor: ty) => { ($factor,) }; ($($factor: ty),*) => { ( $( $factor, )* ) }; ($($factor: ty),*,) => { ( $( $factor, )* ) }; } macro_rules! default { ($type: ty, $val: expr) => { impl Default for $type { fn default() -> Self { $val.into() } } }; } // Pervasive internal sugar macro_rules! mapfn { ($(#[$meta:meta])* [$($vis:tt)*] fn $name:ident[$($gen:tt)*]($parm:ident: $input:ty) -> $output:ty { $($body:tt)* }) => { $(#[$meta])* #[derive(Clone, Copy)] $($vis)* struct $name; impl $($gen)* statics::MapFn<$input> for $name { type Output = $output; } } } macro_rules! opaque_strategy_wrapper { ($(#[$smeta:meta])* pub struct $stratname:ident [$($sgen:tt)*][$($swhere:tt)*] ($innerstrat:ty) -> $stratvtty:ty; $(#[$vmeta:meta])* pub struct $vtname:ident [$($vgen:tt)*][$($vwhere:tt)*] ($innervt:ty) -> $actualty:ty; ) => { $(#[$smeta])* struct $stratname $($sgen)* (std::marker::PhantomData<(K, V)>) $($swhere)*; $(#[$vmeta])* struct $vtname $($vgen)* ($innervt) $($vwhere)*; impl $($sgen)* Strategy for $stratname $($sgen)* $($swhere)* { type Value = $stratvtty; } impl $($vgen)* ValueTree for $vtname $($vgen)* $($vwhere)* { type Value = $actualty; } } } trait ValueTree { type Value; } trait Strategy { type Value : ValueTree; } #[derive(Clone)] struct VecStrategy<T : Strategy> { element: T, size: Range<usize>, } fn vec<T : Strategy>(element: T, size: Range<usize>) -> VecStrategy<T> { VecStrategy { element: element, size: size, } } type ValueFor<S> = <<S as Strategy>::Value as ValueTree>::Value; trait Arbitrary<'a>: Sized { fn arbitrary_with(args: Self::Parameters) -> Self::Strategy; type Parameters: Default; type Strategy: Strategy<Value = Self::ValueTree>; type ValueTree: ValueTree<Value = Self>; } type StrategyFor<A> = StrategyType<'static, A>; type StrategyType<'a, A> = <A as Arbitrary<'a>>::Strategy; //#[derive(Clone, PartialEq, Eq, Hash, Debug, From, Into)] struct SizeBounds(Range<usize>); default!(SizeBounds, 0..100); impl From<Range<usize>> for SizeBounds { fn from(high: Range<usize>) -> Self { unimplemented!() } } impl From<SizeBounds> for Range<usize> { fn from(high: SizeBounds) -> Self { unimplemented!() } } fn any_with<'a, A: Arbitrary<'a>>(args: A::Parameters) -> StrategyType<'a, A> { unimplemented!() } impl<K: ValueTree, V: ValueTree> Strategy for (K, V) where <K as ValueTree>::Value: Ord { type Value = TupleValueTree<(K, V)>; } impl<K: ValueTree, V: ValueTree> ValueTree for TupleValueTree<(K, V)> where <K as ValueTree>::Value: Ord { type Value = BTreeMapValueTree<K, V>; } #[derive(Clone)] struct VecValueTree<T : ValueTree> { elements: Vec<T>, } #[derive(Clone, Copy)] struct TupleValueTree<T> { tree: T, } opaque_strategy_wrapper! { #[derive(Clone)] pub struct BTreeMapStrategy[<K, V>] [where K : Strategy, V : Strategy, ValueFor<K> : Ord]( statics::Filter<statics::Map<VecStrategy<(K,V)>, VecToBTreeMap>, MinSize>) -> BTreeMapValueTree<K::Value, V::Value>; #[derive(Clone)] pub struct BTreeMapValueTree[<K, V>] [where K : ValueTree, V : ValueTree, K::Value : Ord]( statics::Filter<statics::Map<VecValueTree<TupleValueTree<(K, V)>>, VecToBTreeMap>, MinSize>) -> BTreeMap<K::Value, V::Value>; } type RangedParams2<A, B> = product_type![SizeBounds, A, B]; impl<'a, A, B> Arbitrary<'a> for BTreeMap<A, B> where A: Arbitrary<'static> + Ord, B: Arbitrary<'static>, StrategyFor<A>:'static, StrategyFor<B>:'static, { valuetree!(); type Parameters = RangedParams2<A::Parameters, B::Parameters>; type Strategy = BTreeMapStrategy<A::Strategy, B::Strategy>; fn arbitrary_with(args: Self::Parameters) -> Self::Strategy { let product_unpack![range, a, b] = args; btree_map(any_with::<A>(a), any_with::<B>(b), range.into()) } } #[derive(Clone, Copy)] struct MinSize(usize); mapfn! { [] fn VecToBTreeMap[<K : Ord, V>] (vec: Vec<(K, V)>) -> BTreeMap<K, V> { vec.into_iter().collect() } } fn btree_map<K : Strategy +'static, V : Strategy +'static> (key: K, value: V, size: Range<usize>) -> BTreeMapStrategy<K, V> where ValueFor<K> : Ord { unimplemented!() } mod statics { pub(super) trait MapFn<T> { type Output; } #[derive(Clone)] pub struct Filter<S, F> { source: S, fun: F, } impl<S, F> Filter<S, F> { pub fn new(source: S, whence: String, filter: F) -> Self { unimplemented!() } } #[derive(Clone)] pub struct
<S, F> { source: S, fun: F, } impl<S, F> Map<S, F> { pub fn new(source: S, fun: F) -> Self { unimplemented!() } } } fn main() { }
Map
identifier_name
issue-53789-2.rs
// Regression test for #53789. // // compile-pass #![feature(nll)] #![allow(unused_variables)] use std::collections::BTreeMap; use std::ops::Range; use std::cmp::Ord; macro_rules! valuetree { () => { type ValueTree = <Self::Strategy as $crate::Strategy>::Value; }; } macro_rules! product_unpack { ($factor: pat) => { ($factor,) }; ($($factor: pat),*) => { ( $( $factor ),* ) }; ($($factor: pat),*,) => { ( $( $factor ),* ) }; } macro_rules! product_type { ($factor: ty) => { ($factor,) }; ($($factor: ty),*) => { ( $( $factor, )* ) }; ($($factor: ty),*,) => { ( $( $factor, )* ) }; } macro_rules! default { ($type: ty, $val: expr) => { impl Default for $type { fn default() -> Self { $val.into() } } }; } // Pervasive internal sugar macro_rules! mapfn { ($(#[$meta:meta])* [$($vis:tt)*] fn $name:ident[$($gen:tt)*]($parm:ident: $input:ty) -> $output:ty { $($body:tt)* }) => { $(#[$meta])* #[derive(Clone, Copy)] $($vis)* struct $name; impl $($gen)* statics::MapFn<$input> for $name { type Output = $output; } } } macro_rules! opaque_strategy_wrapper { ($(#[$smeta:meta])* pub struct $stratname:ident [$($sgen:tt)*][$($swhere:tt)*] ($innerstrat:ty) -> $stratvtty:ty; $(#[$vmeta:meta])* pub struct $vtname:ident [$($vgen:tt)*][$($vwhere:tt)*] ($innervt:ty) -> $actualty:ty; ) => { $(#[$smeta])* struct $stratname $($sgen)* (std::marker::PhantomData<(K, V)>) $($swhere)*; $(#[$vmeta])* struct $vtname $($vgen)* ($innervt) $($vwhere)*; impl $($sgen)* Strategy for $stratname $($sgen)* $($swhere)* { type Value = $stratvtty; } impl $($vgen)* ValueTree for $vtname $($vgen)* $($vwhere)* { type Value = $actualty; } } } trait ValueTree { type Value; } trait Strategy { type Value : ValueTree; } #[derive(Clone)] struct VecStrategy<T : Strategy> { element: T, size: Range<usize>, } fn vec<T : Strategy>(element: T, size: Range<usize>) -> VecStrategy<T> { VecStrategy { element: element, size: size, } } type ValueFor<S> = <<S as Strategy>::Value as ValueTree>::Value; trait Arbitrary<'a>: Sized { fn arbitrary_with(args: Self::Parameters) -> Self::Strategy; type Parameters: Default; type Strategy: Strategy<Value = Self::ValueTree>; type ValueTree: ValueTree<Value = Self>; } type StrategyFor<A> = StrategyType<'static, A>; type StrategyType<'a, A> = <A as Arbitrary<'a>>::Strategy; //#[derive(Clone, PartialEq, Eq, Hash, Debug, From, Into)] struct SizeBounds(Range<usize>); default!(SizeBounds, 0..100); impl From<Range<usize>> for SizeBounds { fn from(high: Range<usize>) -> Self { unimplemented!() } } impl From<SizeBounds> for Range<usize> { fn from(high: SizeBounds) -> Self { unimplemented!() } } fn any_with<'a, A: Arbitrary<'a>>(args: A::Parameters) -> StrategyType<'a, A> { unimplemented!() } impl<K: ValueTree, V: ValueTree> Strategy for (K, V) where <K as ValueTree>::Value: Ord { type Value = TupleValueTree<(K, V)>; } impl<K: ValueTree, V: ValueTree> ValueTree for TupleValueTree<(K, V)> where <K as ValueTree>::Value: Ord { type Value = BTreeMapValueTree<K, V>; } #[derive(Clone)] struct VecValueTree<T : ValueTree> { elements: Vec<T>, } #[derive(Clone, Copy)] struct TupleValueTree<T> { tree: T, } opaque_strategy_wrapper! { #[derive(Clone)] pub struct BTreeMapStrategy[<K, V>] [where K : Strategy, V : Strategy, ValueFor<K> : Ord]( statics::Filter<statics::Map<VecStrategy<(K,V)>, VecToBTreeMap>, MinSize>) -> BTreeMapValueTree<K::Value, V::Value>; #[derive(Clone)] pub struct BTreeMapValueTree[<K, V>] [where K : ValueTree, V : ValueTree, K::Value : Ord]( statics::Filter<statics::Map<VecValueTree<TupleValueTree<(K, V)>>, VecToBTreeMap>, MinSize>) -> BTreeMap<K::Value, V::Value>; } type RangedParams2<A, B> = product_type![SizeBounds, A, B]; impl<'a, A, B> Arbitrary<'a> for BTreeMap<A, B> where A: Arbitrary<'static> + Ord, B: Arbitrary<'static>, StrategyFor<A>:'static, StrategyFor<B>:'static, { valuetree!(); type Parameters = RangedParams2<A::Parameters, B::Parameters>; type Strategy = BTreeMapStrategy<A::Strategy, B::Strategy>; fn arbitrary_with(args: Self::Parameters) -> Self::Strategy { let product_unpack![range, a, b] = args; btree_map(any_with::<A>(a), any_with::<B>(b), range.into()) } } #[derive(Clone, Copy)] struct MinSize(usize); mapfn! { [] fn VecToBTreeMap[<K : Ord, V>] (vec: Vec<(K, V)>) -> BTreeMap<K, V> { vec.into_iter().collect() } } fn btree_map<K : Strategy +'static, V : Strategy +'static> (key: K, value: V, size: Range<usize>) -> BTreeMapStrategy<K, V> where ValueFor<K> : Ord { unimplemented!() } mod statics { pub(super) trait MapFn<T> { type Output; } #[derive(Clone)] pub struct Filter<S, F> { source: S, fun: F, } impl<S, F> Filter<S, F> { pub fn new(source: S, whence: String, filter: F) -> Self {
#[derive(Clone)] pub struct Map<S, F> { source: S, fun: F, } impl<S, F> Map<S, F> { pub fn new(source: S, fun: F) -> Self { unimplemented!() } } } fn main() { }
unimplemented!() } }
random_line_split
util.rs
//! Contains utility things used in glium's internals use std::default::Default; use std::hash::Hasher; /// A speedy hash algorithm for node ids and def ids. The hashmap in /// libcollections by default uses SipHash which isn't quite as speedy as we /// want. In the compiler we're not really worried about DOS attempts, so we /// just default to a non-cryptographic hash. /// /// This uses FNV hashing, as described here: /// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// /// Copy-pasted from rustc/util/nodemap.rs pub struct FnvHasher(u64); impl Default for FnvHasher { fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) } }
let FnvHasher(mut hash) = *self; for byte in bytes { hash = hash ^ (*byte as u64); hash = hash * 0x100000001b3; } *self = FnvHasher(hash); } fn finish(&self) -> u64 { self.0 } }
impl Hasher for FnvHasher { fn write(&mut self, bytes: &[u8]) {
random_line_split
util.rs
//! Contains utility things used in glium's internals use std::default::Default; use std::hash::Hasher; /// A speedy hash algorithm for node ids and def ids. The hashmap in /// libcollections by default uses SipHash which isn't quite as speedy as we /// want. In the compiler we're not really worried about DOS attempts, so we /// just default to a non-cryptographic hash. /// /// This uses FNV hashing, as described here: /// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// /// Copy-pasted from rustc/util/nodemap.rs pub struct
(u64); impl Default for FnvHasher { fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) } } impl Hasher for FnvHasher { fn write(&mut self, bytes: &[u8]) { let FnvHasher(mut hash) = *self; for byte in bytes { hash = hash ^ (*byte as u64); hash = hash * 0x100000001b3; } *self = FnvHasher(hash); } fn finish(&self) -> u64 { self.0 } }
FnvHasher
identifier_name
lib.rs
extern crate bazel_protos; extern crate digest; extern crate grpcio; extern crate protobuf; extern crate sha2; use std::collections::BTreeMap; pub mod local; pub mod remote; #[cfg(test)] mod test_server; /// /// A process to be executed. /// #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct ExecuteProcessRequest { /// /// The arguments to execute. /// /// The first argument should be an absolute or relative path to the binary to execute. /// /// No PATH lookup will be performed unless a PATH environment variable is specified. /// /// No shell expansion will take place. /// pub argv: Vec<String>, /// /// The environment variables to set for the execution. /// /// No other environment variables will be set (except possibly for an empty PATH variable). /// pub env: BTreeMap<String, String>, } /// /// The result of running a process. ///
pub stderr: Vec<u8>, pub exit_code: i32, }
#[derive(Clone, Debug, Eq, PartialEq)] pub struct ExecuteProcessResult { pub stdout: Vec<u8>,
random_line_split
lib.rs
extern crate bazel_protos; extern crate digest; extern crate grpcio; extern crate protobuf; extern crate sha2; use std::collections::BTreeMap; pub mod local; pub mod remote; #[cfg(test)] mod test_server; /// /// A process to be executed. /// #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct
{ /// /// The arguments to execute. /// /// The first argument should be an absolute or relative path to the binary to execute. /// /// No PATH lookup will be performed unless a PATH environment variable is specified. /// /// No shell expansion will take place. /// pub argv: Vec<String>, /// /// The environment variables to set for the execution. /// /// No other environment variables will be set (except possibly for an empty PATH variable). /// pub env: BTreeMap<String, String>, } /// /// The result of running a process. /// #[derive(Clone, Debug, Eq, PartialEq)] pub struct ExecuteProcessResult { pub stdout: Vec<u8>, pub stderr: Vec<u8>, pub exit_code: i32, }
ExecuteProcessRequest
identifier_name
udp.rs
extern crate futures; #[macro_use] extern crate tokio_core; use std::io; use std::net::SocketAddr; use futures::{Future, Poll}; use tokio_core::net::UdpSocket; use tokio_core::reactor::Core; macro_rules! t { ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{} failed with {:?}", stringify!($e), e), }) } #[test] fn send_messages()
struct SendMessage { socket: UdpSocket, addr: SocketAddr, } impl Future for SendMessage { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll<(), io::Error> { let n = try_nb!(self.socket.send_to(b"1234", &self.addr)); assert_eq!(n, 4); Ok(().into()) } } struct RecvMessage { socket: UdpSocket, expected_addr: SocketAddr, } impl Future for RecvMessage { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll<(), io::Error> { let mut buf = [0; 32]; let (n, addr) = try_nb!(self.socket.recv_from(&mut buf)); assert_eq!(n, 4); assert_eq!(&buf[..4], b"1234"); assert_eq!(addr, self.expected_addr); Ok(().into()) } }
{ let mut l = t!(Core::new()); let a = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse()), &l.handle())); let b = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse()), &l.handle())); let a_addr = t!(a.local_addr()); let b_addr = t!(b.local_addr()); let send = SendMessage { socket: a, addr: b_addr }; let recv = RecvMessage { socket: b, expected_addr: a_addr }; t!(l.run(send.join(recv))); }
identifier_body
udp.rs
extern crate futures; #[macro_use] extern crate tokio_core; use std::io; use std::net::SocketAddr; use futures::{Future, Poll}; use tokio_core::net::UdpSocket; use tokio_core::reactor::Core; macro_rules! t { ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{} failed with {:?}", stringify!($e), e), }) } #[test] fn send_messages() { let mut l = t!(Core::new()); let a = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse()), &l.handle())); let b = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse()), &l.handle())); let a_addr = t!(a.local_addr()); let b_addr = t!(b.local_addr()); let send = SendMessage { socket: a, addr: b_addr }; let recv = RecvMessage { socket: b, expected_addr: a_addr }; t!(l.run(send.join(recv))); } struct SendMessage { socket: UdpSocket, addr: SocketAddr, } impl Future for SendMessage { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll<(), io::Error> { let n = try_nb!(self.socket.send_to(b"1234", &self.addr)); assert_eq!(n, 4); Ok(().into()) } } struct RecvMessage { socket: UdpSocket, expected_addr: SocketAddr, } impl Future for RecvMessage { type Item = (); type Error = io::Error; fn
(&mut self) -> Poll<(), io::Error> { let mut buf = [0; 32]; let (n, addr) = try_nb!(self.socket.recv_from(&mut buf)); assert_eq!(n, 4); assert_eq!(&buf[..4], b"1234"); assert_eq!(addr, self.expected_addr); Ok(().into()) } }
poll
identifier_name
udp.rs
extern crate futures; #[macro_use] extern crate tokio_core;
use std::io; use std::net::SocketAddr; use futures::{Future, Poll}; use tokio_core::net::UdpSocket; use tokio_core::reactor::Core; macro_rules! t { ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{} failed with {:?}", stringify!($e), e), }) } #[test] fn send_messages() { let mut l = t!(Core::new()); let a = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse()), &l.handle())); let b = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse()), &l.handle())); let a_addr = t!(a.local_addr()); let b_addr = t!(b.local_addr()); let send = SendMessage { socket: a, addr: b_addr }; let recv = RecvMessage { socket: b, expected_addr: a_addr }; t!(l.run(send.join(recv))); } struct SendMessage { socket: UdpSocket, addr: SocketAddr, } impl Future for SendMessage { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll<(), io::Error> { let n = try_nb!(self.socket.send_to(b"1234", &self.addr)); assert_eq!(n, 4); Ok(().into()) } } struct RecvMessage { socket: UdpSocket, expected_addr: SocketAddr, } impl Future for RecvMessage { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll<(), io::Error> { let mut buf = [0; 32]; let (n, addr) = try_nb!(self.socket.recv_from(&mut buf)); assert_eq!(n, 4); assert_eq!(&buf[..4], b"1234"); assert_eq!(addr, self.expected_addr); Ok(().into()) } }
random_line_split
build.rs
extern crate gcc; use std::env; fn main()
} else if cfg!(target_os = "macos") { minidfs_config .include(format!("{}/include/darwin", val)); } // TODO - to be changed to consider a dependent platform. }, Err(e) => { panic!("JAVA_HOME shell environment must be set: {}", e); } } minidfs_config.compile("libminidfs.a"); }
{ // for libhdfs.a match env::var("HADOOP_HOME") { Ok(val) => { println!("cargo:rustc-link-search=native={}/lib/native", val); }, Err(e) => { panic!("HADOOP_HOME shell environment must be set: {}", e); } } // for jvm.h and linking to jni libraries let mut minidfs_config = gcc::Config::new(); minidfs_config.file("src/native/native_mini_dfs.c").include("src/native"); match env::var("JAVA_HOME") { Ok(val) => { minidfs_config.include(format!("{}/include/", val)); if cfg!(target_os = "linux") { minidfs_config .include(format!("{}/include/linux", val));
identifier_body
build.rs
extern crate gcc; use std::env; fn
() { // for libhdfs.a match env::var("HADOOP_HOME") { Ok(val) => { println!("cargo:rustc-link-search=native={}/lib/native", val); }, Err(e) => { panic!("HADOOP_HOME shell environment must be set: {}", e); } } // for jvm.h and linking to jni libraries let mut minidfs_config = gcc::Config::new(); minidfs_config.file("src/native/native_mini_dfs.c").include("src/native"); match env::var("JAVA_HOME") { Ok(val) => { minidfs_config.include(format!("{}/include/", val)); if cfg!(target_os = "linux") { minidfs_config .include(format!("{}/include/linux", val)); } else if cfg!(target_os = "macos") { minidfs_config .include(format!("{}/include/darwin", val)); } // TODO - to be changed to consider a dependent platform. }, Err(e) => { panic!("JAVA_HOME shell environment must be set: {}", e); } } minidfs_config.compile("libminidfs.a"); }
main
identifier_name
build.rs
extern crate gcc; use std::env; fn main() { // for libhdfs.a match env::var("HADOOP_HOME") { Ok(val) => { println!("cargo:rustc-link-search=native={}/lib/native", val); }, Err(e) => { panic!("HADOOP_HOME shell environment must be set: {}", e); } } // for jvm.h and linking to jni libraries let mut minidfs_config = gcc::Config::new(); minidfs_config.file("src/native/native_mini_dfs.c").include("src/native"); match env::var("JAVA_HOME") { Ok(val) => { minidfs_config.include(format!("{}/include/", val)); if cfg!(target_os = "linux") { minidfs_config .include(format!("{}/include/linux", val)); } else if cfg!(target_os = "macos") { minidfs_config .include(format!("{}/include/darwin", val)); } // TODO - to be changed to consider a dependent platform. }, Err(e) => { panic!("JAVA_HOME shell environment must be set: {}", e); } }
minidfs_config.compile("libminidfs.a"); }
random_line_split
build.rs
extern crate gcc; use std::env; fn main() { // for libhdfs.a match env::var("HADOOP_HOME") { Ok(val) => { println!("cargo:rustc-link-search=native={}/lib/native", val); }, Err(e) => { panic!("HADOOP_HOME shell environment must be set: {}", e); } } // for jvm.h and linking to jni libraries let mut minidfs_config = gcc::Config::new(); minidfs_config.file("src/native/native_mini_dfs.c").include("src/native"); match env::var("JAVA_HOME") { Ok(val) => { minidfs_config.include(format!("{}/include/", val)); if cfg!(target_os = "linux") { minidfs_config .include(format!("{}/include/linux", val)); } else if cfg!(target_os = "macos") { minidfs_config .include(format!("{}/include/darwin", val)); } // TODO - to be changed to consider a dependent platform. }, Err(e) =>
} minidfs_config.compile("libminidfs.a"); }
{ panic!("JAVA_HOME shell environment must be set: {}", e); }
conditional_block
service.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details. */ //! The service interface use serialize::{Source, Unmarshallable}; use core::fmt; use core::intrinsics; use kif::syscalls; int_enum! { /// The service calls pub struct Operation : u64 { const OPEN = 0x0; const OBTAIN = 0x1; const DELEGATE = 0x2; const CLOSE = 0x3; const SHUTDOWN = 0x4; } } /// The open request message #[repr(C, packed)] pub struct Open { pub opcode: u64, pub arg: u64, } /// The open reply message #[repr(C, packed)] pub struct OpenReply { pub res: u64, pub sess: u64, } /// The data part of the delegate/obtain request messages #[repr(C, packed)] pub struct ExchangeData { pub caps: u64, pub args: syscalls::ExchangeArgs, } /// The delegate/obtain request message #[repr(C, packed)] pub struct
{ pub opcode: u64, pub sess: u64, pub data: ExchangeData, } /// The delegate/obtain reply message #[repr(C, packed)] pub struct ExchangeReply { pub res: u64, pub data: ExchangeData, } /// The close request message #[repr(C, packed)] pub struct Close { pub opcode: u64, pub sess: u64, } /// The shutdown request message #[repr(C, packed)] pub struct Shutdown { pub opcode: u64, } impl fmt::Debug for ExchangeData { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "ExchangeData[")?; for i in 0..self.args.count { let arg = unsafe { self.args.vals.i[i as usize] }; write!(f, "{}", arg)?; if i + 1 < self.args.count { write!(f, ", ")?; } } write!(f, "]") } } impl Unmarshallable for ExchangeData { fn unmarshall(s: &mut Source) -> Self { let mut res = ExchangeData { caps: s.pop_word(), args: unsafe { intrinsics::uninit() }, }; res.args.count = s.pop_word(); for i in 0..res.args.count { unsafe { res.args.vals.i[i as usize] = s.pop_word(); } } res } }
Exchange
identifier_name
service.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details. */ //! The service interface use serialize::{Source, Unmarshallable}; use core::fmt; use core::intrinsics; use kif::syscalls; int_enum! { /// The service calls pub struct Operation : u64 { const OPEN = 0x0; const OBTAIN = 0x1; const DELEGATE = 0x2; const CLOSE = 0x3; const SHUTDOWN = 0x4; } } /// The open request message #[repr(C, packed)] pub struct Open { pub opcode: u64, pub arg: u64, } /// The open reply message #[repr(C, packed)] pub struct OpenReply { pub res: u64, pub sess: u64, } /// The data part of the delegate/obtain request messages #[repr(C, packed)] pub struct ExchangeData { pub caps: u64, pub args: syscalls::ExchangeArgs, } /// The delegate/obtain request message #[repr(C, packed)] pub struct Exchange { pub opcode: u64, pub sess: u64,
/// The delegate/obtain reply message #[repr(C, packed)] pub struct ExchangeReply { pub res: u64, pub data: ExchangeData, } /// The close request message #[repr(C, packed)] pub struct Close { pub opcode: u64, pub sess: u64, } /// The shutdown request message #[repr(C, packed)] pub struct Shutdown { pub opcode: u64, } impl fmt::Debug for ExchangeData { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "ExchangeData[")?; for i in 0..self.args.count { let arg = unsafe { self.args.vals.i[i as usize] }; write!(f, "{}", arg)?; if i + 1 < self.args.count { write!(f, ", ")?; } } write!(f, "]") } } impl Unmarshallable for ExchangeData { fn unmarshall(s: &mut Source) -> Self { let mut res = ExchangeData { caps: s.pop_word(), args: unsafe { intrinsics::uninit() }, }; res.args.count = s.pop_word(); for i in 0..res.args.count { unsafe { res.args.vals.i[i as usize] = s.pop_word(); } } res } }
pub data: ExchangeData, }
random_line_split
service.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details. */ //! The service interface use serialize::{Source, Unmarshallable}; use core::fmt; use core::intrinsics; use kif::syscalls; int_enum! { /// The service calls pub struct Operation : u64 { const OPEN = 0x0; const OBTAIN = 0x1; const DELEGATE = 0x2; const CLOSE = 0x3; const SHUTDOWN = 0x4; } } /// The open request message #[repr(C, packed)] pub struct Open { pub opcode: u64, pub arg: u64, } /// The open reply message #[repr(C, packed)] pub struct OpenReply { pub res: u64, pub sess: u64, } /// The data part of the delegate/obtain request messages #[repr(C, packed)] pub struct ExchangeData { pub caps: u64, pub args: syscalls::ExchangeArgs, } /// The delegate/obtain request message #[repr(C, packed)] pub struct Exchange { pub opcode: u64, pub sess: u64, pub data: ExchangeData, } /// The delegate/obtain reply message #[repr(C, packed)] pub struct ExchangeReply { pub res: u64, pub data: ExchangeData, } /// The close request message #[repr(C, packed)] pub struct Close { pub opcode: u64, pub sess: u64, } /// The shutdown request message #[repr(C, packed)] pub struct Shutdown { pub opcode: u64, } impl fmt::Debug for ExchangeData { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "ExchangeData[")?; for i in 0..self.args.count { let arg = unsafe { self.args.vals.i[i as usize] }; write!(f, "{}", arg)?; if i + 1 < self.args.count
} write!(f, "]") } } impl Unmarshallable for ExchangeData { fn unmarshall(s: &mut Source) -> Self { let mut res = ExchangeData { caps: s.pop_word(), args: unsafe { intrinsics::uninit() }, }; res.args.count = s.pop_word(); for i in 0..res.args.count { unsafe { res.args.vals.i[i as usize] = s.pop_word(); } } res } }
{ write!(f, ", ")?; }
conditional_block
path.rs
use std::fmt; use std::hash::{Hash, Hasher}; use std::slice::{Iter, IterMut}; #[derive(Clone, PartialEq, Hash, Debug)] pub enum Fragment { Index(usize), Name(String) } impl fmt::Display for Fragment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Fragment::Index(ref index) => write!(f, "{}", index), Fragment::Name(ref name) => write!(f, "{}", name), } } } #[derive(Clone, Debug)] pub struct Path { fragments: Vec<Fragment>, is_relative: bool } impl Path { fn from_fragments(fragments: Vec<Fragment>, is_relative: bool) -> Path { Path { fragments: fragments, is_relative: is_relative } } pub fn is_relative(&self) -> bool { self.is_relative } pub fn first(&self) -> Option<&Fragment> { self.fragments.first() } pub fn last(&self) -> Option<&Fragment> { self.fragments.last() } pub fn iter(&self) -> Iter<Fragment> { self.fragments.iter() } pub fn
(&self) -> usize { self.fragments.len() } pub fn from_str(path: &str) -> Option<Path> { if path.is_empty() { return None; } let is_relative = path.starts_with('.'); // If the path is relative remove the first dot let new_path = if is_relative { let mut iter = path.chars(); iter.next(); iter.as_str() } else { path }; let fragments: Vec<Fragment> = new_path.split('.').map(|ref token| { match token.parse::<usize>() { Ok(index) => Fragment::Index(index), Err(_) => Fragment::Name(token.to_string()), } }).collect(); Some(Path::from_fragments(fragments, is_relative)) } } impl fmt::Display for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.is_relative { try!(write!(f, ".")); } write!(f, "{}", self.fragments.iter().map(|ref fragment| fragment.to_string()).collect::<Vec<_>>().join(".")) } } impl PartialEq for Path { fn eq(&self, other: &Path) -> bool { if self.is_relative!= other.is_relative { return false; } if self.fragments.len()!= other.fragments.len() { return false; } return self.fragments == other.fragments; } } impl Hash for Path { fn hash<H: Hasher>(&self, state: &mut H) { self.to_string().hash(state); } }
len
identifier_name
path.rs
#[derive(Clone, PartialEq, Hash, Debug)] pub enum Fragment { Index(usize), Name(String) } impl fmt::Display for Fragment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Fragment::Index(ref index) => write!(f, "{}", index), Fragment::Name(ref name) => write!(f, "{}", name), } } } #[derive(Clone, Debug)] pub struct Path { fragments: Vec<Fragment>, is_relative: bool } impl Path { fn from_fragments(fragments: Vec<Fragment>, is_relative: bool) -> Path { Path { fragments: fragments, is_relative: is_relative } } pub fn is_relative(&self) -> bool { self.is_relative } pub fn first(&self) -> Option<&Fragment> { self.fragments.first() } pub fn last(&self) -> Option<&Fragment> { self.fragments.last() } pub fn iter(&self) -> Iter<Fragment> { self.fragments.iter() } pub fn len(&self) -> usize { self.fragments.len() } pub fn from_str(path: &str) -> Option<Path> { if path.is_empty() { return None; } let is_relative = path.starts_with('.'); // If the path is relative remove the first dot let new_path = if is_relative { let mut iter = path.chars(); iter.next(); iter.as_str() } else { path }; let fragments: Vec<Fragment> = new_path.split('.').map(|ref token| { match token.parse::<usize>() { Ok(index) => Fragment::Index(index), Err(_) => Fragment::Name(token.to_string()), } }).collect(); Some(Path::from_fragments(fragments, is_relative)) } } impl fmt::Display for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.is_relative { try!(write!(f, ".")); } write!(f, "{}", self.fragments.iter().map(|ref fragment| fragment.to_string()).collect::<Vec<_>>().join(".")) } } impl PartialEq for Path { fn eq(&self, other: &Path) -> bool { if self.is_relative!= other.is_relative { return false; } if self.fragments.len()!= other.fragments.len() { return false; } return self.fragments == other.fragments; } } impl Hash for Path { fn hash<H: Hasher>(&self, state: &mut H) { self.to_string().hash(state); } }
use std::fmt; use std::hash::{Hash, Hasher}; use std::slice::{Iter, IterMut};
random_line_split
path.rs
use std::fmt; use std::hash::{Hash, Hasher}; use std::slice::{Iter, IterMut}; #[derive(Clone, PartialEq, Hash, Debug)] pub enum Fragment { Index(usize), Name(String) } impl fmt::Display for Fragment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Fragment::Index(ref index) => write!(f, "{}", index), Fragment::Name(ref name) => write!(f, "{}", name), } } } #[derive(Clone, Debug)] pub struct Path { fragments: Vec<Fragment>, is_relative: bool } impl Path { fn from_fragments(fragments: Vec<Fragment>, is_relative: bool) -> Path { Path { fragments: fragments, is_relative: is_relative } } pub fn is_relative(&self) -> bool { self.is_relative } pub fn first(&self) -> Option<&Fragment> { self.fragments.first() } pub fn last(&self) -> Option<&Fragment> { self.fragments.last() } pub fn iter(&self) -> Iter<Fragment> { self.fragments.iter() } pub fn len(&self) -> usize { self.fragments.len() } pub fn from_str(path: &str) -> Option<Path> { if path.is_empty() { return None; } let is_relative = path.starts_with('.'); // If the path is relative remove the first dot let new_path = if is_relative { let mut iter = path.chars(); iter.next(); iter.as_str() } else { path }; let fragments: Vec<Fragment> = new_path.split('.').map(|ref token| { match token.parse::<usize>() { Ok(index) => Fragment::Index(index), Err(_) => Fragment::Name(token.to_string()), } }).collect(); Some(Path::from_fragments(fragments, is_relative)) } } impl fmt::Display for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.is_relative { try!(write!(f, ".")); } write!(f, "{}", self.fragments.iter().map(|ref fragment| fragment.to_string()).collect::<Vec<_>>().join(".")) } } impl PartialEq for Path { fn eq(&self, other: &Path) -> bool { if self.is_relative!= other.is_relative { return false; } if self.fragments.len()!= other.fragments.len()
return self.fragments == other.fragments; } } impl Hash for Path { fn hash<H: Hasher>(&self, state: &mut H) { self.to_string().hash(state); } }
{ return false; }
conditional_block
path.rs
use std::fmt; use std::hash::{Hash, Hasher}; use std::slice::{Iter, IterMut}; #[derive(Clone, PartialEq, Hash, Debug)] pub enum Fragment { Index(usize), Name(String) } impl fmt::Display for Fragment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Fragment::Index(ref index) => write!(f, "{}", index), Fragment::Name(ref name) => write!(f, "{}", name), } } } #[derive(Clone, Debug)] pub struct Path { fragments: Vec<Fragment>, is_relative: bool } impl Path { fn from_fragments(fragments: Vec<Fragment>, is_relative: bool) -> Path { Path { fragments: fragments, is_relative: is_relative } } pub fn is_relative(&self) -> bool { self.is_relative } pub fn first(&self) -> Option<&Fragment> { self.fragments.first() } pub fn last(&self) -> Option<&Fragment>
pub fn iter(&self) -> Iter<Fragment> { self.fragments.iter() } pub fn len(&self) -> usize { self.fragments.len() } pub fn from_str(path: &str) -> Option<Path> { if path.is_empty() { return None; } let is_relative = path.starts_with('.'); // If the path is relative remove the first dot let new_path = if is_relative { let mut iter = path.chars(); iter.next(); iter.as_str() } else { path }; let fragments: Vec<Fragment> = new_path.split('.').map(|ref token| { match token.parse::<usize>() { Ok(index) => Fragment::Index(index), Err(_) => Fragment::Name(token.to_string()), } }).collect(); Some(Path::from_fragments(fragments, is_relative)) } } impl fmt::Display for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.is_relative { try!(write!(f, ".")); } write!(f, "{}", self.fragments.iter().map(|ref fragment| fragment.to_string()).collect::<Vec<_>>().join(".")) } } impl PartialEq for Path { fn eq(&self, other: &Path) -> bool { if self.is_relative!= other.is_relative { return false; } if self.fragments.len()!= other.fragments.len() { return false; } return self.fragments == other.fragments; } } impl Hash for Path { fn hash<H: Hasher>(&self, state: &mut H) { self.to_string().hash(state); } }
{ self.fragments.last() }
identifier_body
lib.rs
#![feature(str_checked_slicing)] const DIGITS: [&str; 10] = [ " _ | ||_| ", // 0 " | | ", // 1 " _ _||_ ", // 2 " _ _| _| ", // 3 " |_| | ", // 4 " _ |_ _| ", // 5 " _ |_ |_| ", // 6 " _ | | ", // 7 " _ |_||_| ", // 8 " _ |_| _| ", // 9 ]; const DIGITS_ROWS: usize = 3; const DIGITS_LINES: usize = 4; pub fn
(input: &str) -> Result<String, String> { let v = input.split(|x| x == '\n').collect::<Vec<_>>(); let lines = v.len(); if lines == 0 || lines % DIGITS_LINES!= 0 { return Err("Invalid lines".to_string()); } let rows = v[0].len(); if rows == 0 || rows % DIGITS_ROWS!= 0 { return Err(format!("Invalid {} row at line 1", rows)); } if v.iter().any(|x| x.len()!= rows) { return Err("Invalid rows".to_string()); } let mut result = String::new(); for i in 0..lines / DIGITS_LINES { for j in 0..rows / DIGITS_ROWS { let row = j * DIGITS_ROWS; let line = i * DIGITS_LINES; let number = format!( "{}{}{}{}", v[line].get(row..row + DIGITS_ROWS).unwrap(), v[line + 1].get(row..row + DIGITS_ROWS).unwrap(), v[line + 2].get(row..row + DIGITS_ROWS).unwrap(), v[line + 3].get(row..row + DIGITS_ROWS).unwrap() ); let index: u8 = DIGITS .iter() .position(|&x| x == number) .map_or_else(|| b'?', |v| v as u8 + b'0'); result.push(index as char); } result.push(','); } result.pop(); Ok(result) }
convert
identifier_name
lib.rs
#![feature(str_checked_slicing)] const DIGITS: [&str; 10] = [ " _ | ||_| ", // 0 " | | ", // 1 " _ _||_ ", // 2 " _ _| _| ", // 3 " |_| | ", // 4 " _ |_ _| ", // 5 " _ |_ |_| ", // 6 " _ | | ", // 7 " _ |_||_| ", // 8 " _ |_| _| ", // 9 ]; const DIGITS_ROWS: usize = 3; const DIGITS_LINES: usize = 4; pub fn convert(input: &str) -> Result<String, String>
let line = i * DIGITS_LINES; let number = format!( "{}{}{}{}", v[line].get(row..row + DIGITS_ROWS).unwrap(), v[line + 1].get(row..row + DIGITS_ROWS).unwrap(), v[line + 2].get(row..row + DIGITS_ROWS).unwrap(), v[line + 3].get(row..row + DIGITS_ROWS).unwrap() ); let index: u8 = DIGITS .iter() .position(|&x| x == number) .map_or_else(|| b'?', |v| v as u8 + b'0'); result.push(index as char); } result.push(','); } result.pop(); Ok(result) }
{ let v = input.split(|x| x == '\n').collect::<Vec<_>>(); let lines = v.len(); if lines == 0 || lines % DIGITS_LINES != 0 { return Err("Invalid lines".to_string()); } let rows = v[0].len(); if rows == 0 || rows % DIGITS_ROWS != 0 { return Err(format!("Invalid {} row at line 1", rows)); } if v.iter().any(|x| x.len() != rows) { return Err("Invalid rows".to_string()); } let mut result = String::new(); for i in 0..lines / DIGITS_LINES { for j in 0..rows / DIGITS_ROWS { let row = j * DIGITS_ROWS;
identifier_body
lib.rs
#![feature(str_checked_slicing)] const DIGITS: [&str; 10] = [ " _ | ||_| ", // 0 " | | ", // 1 " _ _||_ ", // 2 " _ _| _| ", // 3 " |_| | ", // 4 " _ |_ _| ", // 5 " _ |_ |_| ", // 6 " _ | | ", // 7 " _ |_||_| ", // 8 " _ |_| _| ", // 9 ]; const DIGITS_ROWS: usize = 3; const DIGITS_LINES: usize = 4; pub fn convert(input: &str) -> Result<String, String> { let v = input.split(|x| x == '\n').collect::<Vec<_>>(); let lines = v.len(); if lines == 0 || lines % DIGITS_LINES!= 0 { return Err("Invalid lines".to_string()); } let rows = v[0].len(); if rows == 0 || rows % DIGITS_ROWS!= 0
if v.iter().any(|x| x.len()!= rows) { return Err("Invalid rows".to_string()); } let mut result = String::new(); for i in 0..lines / DIGITS_LINES { for j in 0..rows / DIGITS_ROWS { let row = j * DIGITS_ROWS; let line = i * DIGITS_LINES; let number = format!( "{}{}{}{}", v[line].get(row..row + DIGITS_ROWS).unwrap(), v[line + 1].get(row..row + DIGITS_ROWS).unwrap(), v[line + 2].get(row..row + DIGITS_ROWS).unwrap(), v[line + 3].get(row..row + DIGITS_ROWS).unwrap() ); let index: u8 = DIGITS .iter() .position(|&x| x == number) .map_or_else(|| b'?', |v| v as u8 + b'0'); result.push(index as char); } result.push(','); } result.pop(); Ok(result) }
{ return Err(format!("Invalid {} row at line 1", rows)); }
conditional_block
lib.rs
#![feature(str_checked_slicing)] const DIGITS: [&str; 10] = [ " _ | ||_| ", // 0 " | | ", // 1 " _ _||_ ", // 2 " _ _| _| ", // 3 " |_| | ", // 4 " _ |_ _| ", // 5 " _ |_ |_| ", // 6
const DIGITS_ROWS: usize = 3; const DIGITS_LINES: usize = 4; pub fn convert(input: &str) -> Result<String, String> { let v = input.split(|x| x == '\n').collect::<Vec<_>>(); let lines = v.len(); if lines == 0 || lines % DIGITS_LINES!= 0 { return Err("Invalid lines".to_string()); } let rows = v[0].len(); if rows == 0 || rows % DIGITS_ROWS!= 0 { return Err(format!("Invalid {} row at line 1", rows)); } if v.iter().any(|x| x.len()!= rows) { return Err("Invalid rows".to_string()); } let mut result = String::new(); for i in 0..lines / DIGITS_LINES { for j in 0..rows / DIGITS_ROWS { let row = j * DIGITS_ROWS; let line = i * DIGITS_LINES; let number = format!( "{}{}{}{}", v[line].get(row..row + DIGITS_ROWS).unwrap(), v[line + 1].get(row..row + DIGITS_ROWS).unwrap(), v[line + 2].get(row..row + DIGITS_ROWS).unwrap(), v[line + 3].get(row..row + DIGITS_ROWS).unwrap() ); let index: u8 = DIGITS .iter() .position(|&x| x == number) .map_or_else(|| b'?', |v| v as u8 + b'0'); result.push(index as char); } result.push(','); } result.pop(); Ok(result) }
" _ | | ", // 7 " _ |_||_| ", // 8 " _ |_| _| ", // 9 ];
random_line_split
mod.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License.
// // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // pub mod grep; pub mod length;
random_line_split
lib.rs
/*! This crate provides a number of conversion traits with more specific semantics than those provided by `as` or `From`/`Into`. The goal with the traits provided here is to be more specific about what generic code can rely on, as well as provide reasonably self-describing alternatives to the standard `From`/`Into` traits. For example, the although `T: From<U>` might be satisfied, it imposes no restrictions on the *kind* of conversion being implemented. As such, the traits in this crate try to be very specific about what conversions are allowed. This makes them less generally applicable, but more useful where they *do* apply. In addition, `From`/`Into` requires all conversions to succeed or panic. All conversion traits in this crate define an associated error type, allowing code to react to failed conversions as appropriate. # API Stability Notice The API of this crate is still not entirely decided. In particular, errors may change in the future to carry the value that failed to convert (allowing it to be recovered). # Overview The following traits are used to define various conversion semantics: - [`ApproxFrom`](./trait.ApproxFrom.html)/[`ApproxInto`](./trait.ApproxInto.html) - approximate conversions, with selectable approximation scheme (see [`ApproxScheme`](./trait.ApproxScheme.html)). - [`TryFrom`](./trait.TryFrom.html)/[`TryInto`](./trait.TryInto.html) - general, potentially failing value conversions. - [`ValueFrom`](./trait.ValueFrom.html)/[`ValueInto`](./trait.ValueInto.html) - exact, value-preserving conversions. These extension methods are provided to help with some common cases: - [`ApproxWith::approx`](./trait.ApproxWith.html#method.approx) - calls `ApproxInto::approx_into` with the `DefaultApprox` scheme. - [`ApproxWith::approx_with<S>`](./trait.ApproxWith.html#method.approx_with) - calls `ApproxInto::approx_into` with the `S` approximation scheme. - [`UnwrapOk::unwrap_ok`](./errors/trait.UnwrapOk.html#tymethod.unwrap_ok) - unwraps results from conversions that cannot fail. - [`UnwrapOrInf::unwrap_or_inf`](./errors/trait.UnwrapOrInf.html#tymethod.unwrap_or_inf) - saturates to ±∞ on failure. - [`UnwrapOrInvalid::unwrap_or_invalid`](./errors/trait.UnwrapOrInvalid.html#tymethod.unwrap_or_invalid) - substitutes the target type's "invalid" sentinel value on failure. - [`UnwrapOrSaturate::unwrap_or_saturate`](./errors/trait.UnwrapOrSaturate.html#tymethod.unwrap_or_saturate) - saturates to the maximum or minimum value of the target type on failure. A macro is provided to assist in implementing conversions: - [`TryFrom!`](./macros/index.html#tryfrom!) - derives an implementation of [`TryFrom`](./trait.TryFrom.html). If you are implementing your own types, you may also be interested in the traits contained in the [`misc`](./misc/index.html) module. ## Provided Implementations The crate provides several blanket implementations: - `*From<A> for A` (all types can be converted from and into themselves). - `*Into<Dst> for Src where Dst: *From<Src>` (`*From` implementations imply a matching `*Into` implementation). Conversions for the builtin numeric (integer and floating point) types are provided. In general, `ValueFrom` conversions exist for all pairs except for float → integer (since such a conversion is generally unlikely to *exactly* succeed) and `f64 → f32` (for the same reason). `ApproxFrom` conversions with the `DefaultApprox` scheme exist between all pairs. `ApproxFrom` with the `Wrapping` scheme exist between integers. ## Errors A number of error types are defined in the [`errors`](./errors/index.html) module. Generally, conversions use whichever error type most *narrowly* defines the kinds of failures that can occur. For example: - `ValueFrom<u8> for u16` cannot possibly fail, and as such it uses `NoError`. - `ValueFrom<i8> for u16` can *only* fail with an underflow, thus it uses the `Underflow` type. - `ValueFrom<i32> for u16` can underflow *or* overflow, hence it uses `RangeError`. - Finally, `ApproxFrom<f32> for u16` can underflow, overflow, or attempt to convert NaN; `FloatError` covers those three cases. Because there are *numerous* error types, the `GeneralError` enum is provided. `From<E> for GeneralError` exists for each error type `E` defined by this crate (even for `NoError`!), allowing errors to be translated automatically by `try!`. In fact, all errors can be "expanded" to *all* more general forms (*e.g.* `NoError` → `Underflow`, `Overflow` → `RangeError` → `FloatError`). The reason for not just using `GeneralError` in the first place is to statically reduce the number of potential error cases you need to deal with. It also allows the `Unwrap*` extension traits to be defined *without* the possibility for runtime failure (*e.g.* you cannot use `unwrap_or_saturate` with a `FloatError`, because what do you do if the error is `NotANumber`; saturate to max or to min? Or panic?).
# Examples ``` # extern crate conv; # use conv::*; # fn main() { // This *cannot* fail, so we can use `unwrap_ok` to discard the `Result`. assert_eq!(u8::value_from(0u8).unwrap_ok(), 0u8); // This *can* fail. Specifically, it can underflow. assert_eq!(u8::value_from(0i8), Ok(0u8)); assert_eq!(u8::value_from(-1i8), Err(Underflow)); // This can underflow *and* overflow; hence the change to `RangeError`. assert_eq!(u8::value_from(-1i16), Err(RangeError::Underflow)); assert_eq!(u8::value_from(0i16), Ok(0u8)); assert_eq!(u8::value_from(256i16), Err(RangeError::Overflow)); // We can use the extension traits to simplify this a little. assert_eq!(u8::value_from(-1i16).unwrap_or_saturate(), 0u8); assert_eq!(u8::value_from(0i16).unwrap_or_saturate(), 0u8); assert_eq!(u8::value_from(256i16).unwrap_or_saturate(), 255u8); // Obviously, all integers can be "approximated" using the default scheme (it // doesn't *do* anything), but they can *also* be approximated with the // `Wrapping` scheme. assert_eq!( <u8 as ApproxFrom<_, DefaultApprox>>::approx_from(400u16), Err(Overflow)); assert_eq!( <u8 as ApproxFrom<_, Wrapping>>::approx_from(400u16), Ok(144u8)); // This is rather inconvenient; as such, provided the return type can be // inferred, you can use `ApproxWith::approx` (for the default scheme) and // `ApproxWith::approx_with`. assert_eq!(400u16.approx(), Err::<u8, _>(Overflow)); assert_eq!(400u16.approx_with::<Wrapping>(), Ok::<u8, _>(144u8)); // Integer -> float conversions *can* fail due to limited precision. // Once the continuous range of exactly representable integers is exceeded, the // provided implementations fail with over/underflow errors. assert_eq!(f32::value_from(16_777_216i32), Ok(16_777_216.0f32)); assert_eq!(f32::value_from(16_777_217i32), Err(RangeError::Overflow)); // Float -> integer conversions have to be done using approximations. Although // exact conversions are *possible*, "advertising" this with an implementation // is misleading. // // Note that `DefaultApprox` for float -> integer uses whatever rounding // mode is currently active (*i.e.* whatever `as` would do). assert_eq!(41.0f32.approx(), Ok(41u8)); assert_eq!(41.3f32.approx(), Ok(41u8)); assert_eq!(41.5f32.approx(), Ok(41u8)); assert_eq!(41.8f32.approx(), Ok(41u8)); assert_eq!(42.0f32.approx(), Ok(42u8)); assert_eq!(255.0f32.approx(), Ok(255u8)); assert_eq!(256.0f32.approx(), Err::<u8, _>(FloatError::Overflow)); // If you really don't care about the specific kind of error, you can just rely // on automatic conversion to `GeneralError`. fn too_many_errors() -> Result<(), GeneralError> { assert_eq!({let r: u8 = try!(0u8.value_into()); r}, 0u8); assert_eq!({let r: u8 = try!(0i8.value_into()); r}, 0u8); assert_eq!({let r: u8 = try!(0i16.value_into()); r}, 0u8); assert_eq!({let r: u8 = try!(0.0f32.approx()); r}, 0u8); Ok(()) } # let _ = too_many_errors(); # } ``` */ #![deny(missing_docs)] // Exported macros. pub mod macros; pub use errors::{ NoError, GeneralError, Unrepresentable, Underflow, Overflow, FloatError, RangeError, UnwrapOk, UnwrapOrInf, UnwrapOrInvalid, UnwrapOrSaturate, }; /** Publicly re-exports the most generally useful set of items. Usage of the prelude should be considered **unstable**. Although items will likely *not* be removed without bumping the major version, new items *may* be added, which could potentially cause name conflicts in user code. */ pub mod prelude { pub use super::{ ApproxFrom, ApproxInto, ApproxWith, ValueFrom, ValueInto, UnwrapOk, UnwrapOrInf, UnwrapOrInvalid, UnwrapOrSaturate, }; } macro_rules! as_item { ($($i:item)*) => {$($i)*}; } macro_rules! item_for_each { ( $( ($($arg:tt)*) ),* $(,)* => { $($exp:tt)* } ) => { macro_rules! body { $($exp)* } $( body! { $($arg)* } )* }; } pub mod errors; pub mod misc; mod impls; /** This trait is used to perform a conversion that is permitted to approximate the result, but *not* to wrap or saturate the result to fit into the destination type's representable range. # Details All implementations of this trait must provide a conversion that can be separated into two logical steps: an approximation transform, and a representation transform. The "approximation transform" step involves transforming the input value into an approximately equivalent value which is supported by the target type *without* taking the target type's representable range into account. For example, this might involve rounding or truncating a floating point value to an integer, or reducing the accuracy of a floating point value. The "representation transform" step *exactly* rewrites the value from the source type's binary representation into the destination type's binary representation. This step *may not* transform the value in any way. If the result of the approximation is not representable, the conversion *must* fail. The major reason for this formulation is to exactly define what happens when converting between floating point and integer types. Often, it is unclear what happens to floating point values beyond the range of the target integer type. Do they saturate, wrap, or cause a failure? With this formulation, it is well-defined: if a floating point value is outside the representable range, the conversion fails. This allows users to distinguish between approximation and range violation, and act accordingly. */ pub trait ApproxFrom<Src, Scheme=DefaultApprox> where Scheme: ApproxScheme { /// The error type produced by a failed conversion. type Err; /// Convert the given value into an approximately equivalent representation. fn approx_from(src: Src) -> Result<Self, Self::Err>; } impl<Src, Scheme> ApproxFrom<Src, Scheme> for Src where Scheme: ApproxScheme { type Err = NoError; fn approx_from(src: Src) -> Result<Self, Self::Err> { Ok(src) } } /** This is the dual of `ApproxFrom`; see that trait for information. */ pub trait ApproxInto<Dst, Scheme=DefaultApprox> where Scheme: ApproxScheme { /// The error type produced by a failed conversion. type Err; /// Convert the subject into an approximately equivalent representation. fn approx_into(self) -> Result<Dst, Self::Err>; } impl<Dst, Src, Scheme> ApproxInto<Dst, Scheme> for Src where Dst: ApproxFrom<Src, Scheme>, Scheme: ApproxScheme, { type Err = Dst::Err; fn approx_into(self) -> Result<Dst, Self::Err> { ApproxFrom::approx_from(self) } } /** This extension trait exists to simplify using approximation implementations. If there is more than one `ApproxFrom` implementation for a given type, a simple call to `approx_into` may not be uniquely resolvable. Due to the position of the scheme parameter (on the trait itself), it is cumbersome to specify which scheme you wanted. Hence this trait. > **Note**: There appears to be a bug in `rustdoc`'s output. This trait is implemented *for all* types. */ pub trait ApproxWith<Dst> { /// Approximate the subject with the default scheme. fn approx(self) -> Result<Dst, Self::Err> where Self: Sized + ApproxInto<Dst> { self.approx_into() } /// Approximate the subject with a specific scheme. fn approx_with<Scheme=DefaultApprox>(self) -> Result<Dst, Self::Err> where Self: Sized + ApproxInto<Dst, Scheme>, Scheme: ApproxScheme, { self.approx_into() } } impl<T, Dst> ApproxWith<Dst> for T {} /** This trait is used to mark approximation scheme types. */ pub trait ApproxScheme {} /** The "default" approximation scheme. This scheme does whatever would generally be expected of a lossy conversion, assuming no additional context or instruction is given. This is a double-edged sword: it has the loosest semantics, but is far more likely to exist than more complicated approximation schemes. */ pub enum DefaultApprox {} impl ApproxScheme for DefaultApprox {} /** This scheme is used to convert a value by "wrapping" it into a narrower range. In abstract, this can be viewed as the opposite of rounding: rather than preserving the most significant bits of a value, it preserves the *least* significant bits of a value. */ pub enum Wrapping {} impl ApproxScheme for Wrapping {} // TODO: RoundToNearest, RoundToPosInf, RoundToNegInf, RoundToZero /** This trait is used to perform a conversion between different semantic types which might fail. # Details Typically, this should be used in cases where you are converting between values whose ranges and/or representations only partially overlap. That the conversion may fail should be a reasonably expected outcome. A standard example of this is converting from integers to enums of unitary variants. */ pub trait TryFrom<Src> { /// The error type produced by a failed conversion. type Err; /// Convert the given value into the subject type. fn try_from(src: Src) -> Result<Self, Self::Err>; } impl<Src> TryFrom<Src> for Src { type Err = NoError; fn try_from(src: Src) -> Result<Self, Self::Err> { Ok(src) } } /** This is the dual of `TryFrom`; see that trait for information. */ pub trait TryInto<Dst> { /// The error type produced by a failed conversion. type Err; /// Convert the subject into the destination type. fn try_into(self) -> Result<Dst, Self::Err>; } impl<Src, Dst> TryInto<Dst> for Src where Dst: TryFrom<Src> { type Err = Dst::Err; fn try_into(self) -> Result<Dst, Self::Err> { TryFrom::try_from(self) } } /** This trait is used to perform an exact, value-preserving conversion. # Details Implementations of this trait should be reflexive, associative and commutative (in the absence of conversion errors). That is, all possible cycles of `ValueFrom` conversions (for which each "step" has a defined implementation) should produce the same result, with a given value either being "round-tripped" exactly, or an error being produced. */ pub trait ValueFrom<Src> { /// The error type produced by a failed conversion. type Err; /// Convert the given value into an exactly equivalent representation. fn value_from(src: Src) -> Result<Self, Self::Err>; } impl<Src> ValueFrom<Src> for Src { type Err = NoError; fn value_from(src: Src) -> Result<Self, Self::Err> { Ok(src) } } /** This is the dual of `ValueFrom`; see that trait for information. */ pub trait ValueInto<Dst> { /// The error type produced by a failed conversion. type Err; /// Convert the subject into an exactly equivalent representation. fn value_into(self) -> Result<Dst, Self::Err>; } impl<Src, Dst> ValueInto<Dst> for Src where Dst: ValueFrom<Src> { type Err = Dst::Err; fn value_into(self) -> Result<Dst, Self::Err> { ValueFrom::value_from(self) } }
random_line_split
lib.rs
/*! This crate provides a number of conversion traits with more specific semantics than those provided by `as` or `From`/`Into`. The goal with the traits provided here is to be more specific about what generic code can rely on, as well as provide reasonably self-describing alternatives to the standard `From`/`Into` traits. For example, the although `T: From<U>` might be satisfied, it imposes no restrictions on the *kind* of conversion being implemented. As such, the traits in this crate try to be very specific about what conversions are allowed. This makes them less generally applicable, but more useful where they *do* apply. In addition, `From`/`Into` requires all conversions to succeed or panic. All conversion traits in this crate define an associated error type, allowing code to react to failed conversions as appropriate. # API Stability Notice The API of this crate is still not entirely decided. In particular, errors may change in the future to carry the value that failed to convert (allowing it to be recovered). # Overview The following traits are used to define various conversion semantics: - [`ApproxFrom`](./trait.ApproxFrom.html)/[`ApproxInto`](./trait.ApproxInto.html) - approximate conversions, with selectable approximation scheme (see [`ApproxScheme`](./trait.ApproxScheme.html)). - [`TryFrom`](./trait.TryFrom.html)/[`TryInto`](./trait.TryInto.html) - general, potentially failing value conversions. - [`ValueFrom`](./trait.ValueFrom.html)/[`ValueInto`](./trait.ValueInto.html) - exact, value-preserving conversions. These extension methods are provided to help with some common cases: - [`ApproxWith::approx`](./trait.ApproxWith.html#method.approx) - calls `ApproxInto::approx_into` with the `DefaultApprox` scheme. - [`ApproxWith::approx_with<S>`](./trait.ApproxWith.html#method.approx_with) - calls `ApproxInto::approx_into` with the `S` approximation scheme. - [`UnwrapOk::unwrap_ok`](./errors/trait.UnwrapOk.html#tymethod.unwrap_ok) - unwraps results from conversions that cannot fail. - [`UnwrapOrInf::unwrap_or_inf`](./errors/trait.UnwrapOrInf.html#tymethod.unwrap_or_inf) - saturates to ±∞ on failure. - [`UnwrapOrInvalid::unwrap_or_invalid`](./errors/trait.UnwrapOrInvalid.html#tymethod.unwrap_or_invalid) - substitutes the target type's "invalid" sentinel value on failure. - [`UnwrapOrSaturate::unwrap_or_saturate`](./errors/trait.UnwrapOrSaturate.html#tymethod.unwrap_or_saturate) - saturates to the maximum or minimum value of the target type on failure. A macro is provided to assist in implementing conversions: - [`TryFrom!`](./macros/index.html#tryfrom!) - derives an implementation of [`TryFrom`](./trait.TryFrom.html). If you are implementing your own types, you may also be interested in the traits contained in the [`misc`](./misc/index.html) module. ## Provided Implementations The crate provides several blanket implementations: - `*From<A> for A` (all types can be converted from and into themselves). - `*Into<Dst> for Src where Dst: *From<Src>` (`*From` implementations imply a matching `*Into` implementation). Conversions for the builtin numeric (integer and floating point) types are provided. In general, `ValueFrom` conversions exist for all pairs except for float → integer (since such a conversion is generally unlikely to *exactly* succeed) and `f64 → f32` (for the same reason). `ApproxFrom` conversions with the `DefaultApprox` scheme exist between all pairs. `ApproxFrom` with the `Wrapping` scheme exist between integers. ## Errors A number of error types are defined in the [`errors`](./errors/index.html) module. Generally, conversions use whichever error type most *narrowly* defines the kinds of failures that can occur. For example: - `ValueFrom<u8> for u16` cannot possibly fail, and as such it uses `NoError`. - `ValueFrom<i8> for u16` can *only* fail with an underflow, thus it uses the `Underflow` type. - `ValueFrom<i32> for u16` can underflow *or* overflow, hence it uses `RangeError`. - Finally, `ApproxFrom<f32> for u16` can underflow, overflow, or attempt to convert NaN; `FloatError` covers those three cases. Because there are *numerous* error types, the `GeneralError` enum is provided. `From<E> for GeneralError` exists for each error type `E` defined by this crate (even for `NoError`!), allowing errors to be translated automatically by `try!`. In fact, all errors can be "expanded" to *all* more general forms (*e.g.* `NoError` → `Underflow`, `Overflow` → `RangeError` → `FloatError`). The reason for not just using `GeneralError` in the first place is to statically reduce the number of potential error cases you need to deal with. It also allows the `Unwrap*` extension traits to be defined *without* the possibility for runtime failure (*e.g.* you cannot use `unwrap_or_saturate` with a `FloatError`, because what do you do if the error is `NotANumber`; saturate to max or to min? Or panic?). # Examples ``` # extern crate conv; # use conv::*; # fn main() { // This *cannot* fail, so we can use `unwrap_ok` to discard the `Result`. assert_eq!(u8::value_from(0u8).unwrap_ok(), 0u8); // This *can* fail. Specifically, it can underflow. assert_eq!(u8::value_from(0i8), Ok(0u8)); assert_eq!(u8::value_from(-1i8), Err(Underflow)); // This can underflow *and* overflow; hence the change to `RangeError`. assert_eq!(u8::value_from(-1i16), Err(RangeError::Underflow)); assert_eq!(u8::value_from(0i16), Ok(0u8)); assert_eq!(u8::value_from(256i16), Err(RangeError::Overflow)); // We can use the extension traits to simplify this a little. assert_eq!(u8::value_from(-1i16).unwrap_or_saturate(), 0u8); assert_eq!(u8::value_from(0i16).unwrap_or_saturate(), 0u8); assert_eq!(u8::value_from(256i16).unwrap_or_saturate(), 255u8); // Obviously, all integers can be "approximated" using the default scheme (it // doesn't *do* anything), but they can *also* be approximated with the // `Wrapping` scheme. assert_eq!( <u8 as ApproxFrom<_, DefaultApprox>>::approx_from(400u16), Err(Overflow)); assert_eq!( <u8 as ApproxFrom<_, Wrapping>>::approx_from(400u16), Ok(144u8)); // This is rather inconvenient; as such, provided the return type can be // inferred, you can use `ApproxWith::approx` (for the default scheme) and // `ApproxWith::approx_with`. assert_eq!(400u16.approx(), Err::<u8, _>(Overflow)); assert_eq!(400u16.approx_with::<Wrapping>(), Ok::<u8, _>(144u8)); // Integer -> float conversions *can* fail due to limited precision. // Once the continuous range of exactly representable integers is exceeded, the // provided implementations fail with over/underflow errors. assert_eq!(f32::value_from(16_777_216i32), Ok(16_777_216.0f32)); assert_eq!(f32::value_from(16_777_217i32), Err(RangeError::Overflow)); // Float -> integer conversions have to be done using approximations. Although // exact conversions are *possible*, "advertising" this with an implementation // is misleading. // // Note that `DefaultApprox` for float -> integer uses whatever rounding // mode is currently active (*i.e.* whatever `as` would do). assert_eq!(41.0f32.approx(), Ok(41u8)); assert_eq!(41.3f32.approx(), Ok(41u8)); assert_eq!(41.5f32.approx(), Ok(41u8)); assert_eq!(41.8f32.approx(), Ok(41u8)); assert_eq!(42.0f32.approx(), Ok(42u8)); assert_eq!(255.0f32.approx(), Ok(255u8)); assert_eq!(256.0f32.approx(), Err::<u8, _>(FloatError::Overflow)); // If you really don't care about the specific kind of error, you can just rely // on automatic conversion to `GeneralError`. fn too_many_errors() -> Result<(), GeneralError> { assert_eq!({let r: u8 = try!(0u8.value_into()); r}, 0u8); assert_eq!({let r: u8 = try!(0i8.value_into()); r}, 0u8); assert_eq!({let r: u8 = try!(0i16.value_into()); r}, 0u8); assert_eq!({let r: u8 = try!(0.0f32.approx()); r}, 0u8); Ok(()) } # let _ = too_many_errors(); # } ``` */ #![deny(missing_docs)] // Exported macros. pub mod macros; pub use errors::{ NoError, GeneralError, Unrepresentable, Underflow, Overflow, FloatError, RangeError, UnwrapOk, UnwrapOrInf, UnwrapOrInvalid, UnwrapOrSaturate, }; /** Publicly re-exports the most generally useful set of items. Usage of the prelude should be considered **unstable**. Although items will likely *not* be removed without bumping the major version, new items *may* be added, which could potentially cause name conflicts in user code. */ pub mod prelude { pub use super::{ ApproxFrom, ApproxInto, ApproxWith, ValueFrom, ValueInto, UnwrapOk, UnwrapOrInf, UnwrapOrInvalid, UnwrapOrSaturate, }; } macro_rules! as_item { ($($i:item)*) => {$($i)*}; } macro_rules! item_for_each { ( $( ($($arg:tt)*) ),* $(,)* => { $($exp:tt)* } ) => { macro_rules! body { $($exp)* } $( body! { $($arg)* } )* }; } pub mod errors; pub mod misc; mod impls; /** This trait is used to perform a conversion that is permitted to approximate the result, but *not* to wrap or saturate the result to fit into the destination type's representable range. # Details All implementations of this trait must provide a conversion that can be separated into two logical steps: an approximation transform, and a representation transform. The "approximation transform" step involves transforming the input value into an approximately equivalent value which is supported by the target type *without* taking the target type's representable range into account. For example, this might involve rounding or truncating a floating point value to an integer, or reducing the accuracy of a floating point value. The "representation transform" step *exactly* rewrites the value from the source type's binary representation into the destination type's binary representation. This step *may not* transform the value in any way. If the result of the approximation is not representable, the conversion *must* fail. The major reason for this formulation is to exactly define what happens when converting between floating point and integer types. Often, it is unclear what happens to floating point values beyond the range of the target integer type. Do they saturate, wrap, or cause a failure? With this formulation, it is well-defined: if a floating point value is outside the representable range, the conversion fails. This allows users to distinguish between approximation and range violation, and act accordingly. */ pub trait ApproxFrom<Src, Scheme=DefaultApprox> where Scheme: ApproxScheme { /// The error type produced by a failed conversion. type Err; /// Convert the given value into an approximately equivalent representation. fn approx_from(src: Src) -> Result<Self, Self::Err>; } impl<Src, Scheme> ApproxFrom<Src, Scheme> for Src where Scheme: ApproxScheme { type Err = NoError; fn approx_from(src: Src) -> Result<Self, Self::Err> { Ok(src) } } /** This is the dual of `ApproxFrom`; see that trait for information. */ pub trait ApproxInto<Dst, Scheme=DefaultApprox> where Scheme: ApproxScheme { /// The error type produced by a failed conversion. type Err; /// Convert the subject into an approximately equivalent representation. fn approx_into(self) -> Result<Dst, Self::Err>; } impl<Dst, Src, Scheme> ApproxInto<Dst, Scheme> for Src where Dst: ApproxFrom<Src, Scheme>, Scheme: ApproxScheme, { type Err = Dst::Err; fn approx_into(self) -> Result<Dst, Self::Err> { ApproxFrom::approx_from(self) } } /** This extension trait exists to simplify using approximation implementations. If there is more than one `ApproxFrom` implementation for a given type, a simple call to `approx_into` may not be uniquely resolvable. Due to the position of the scheme parameter (on the trait itself), it is cumbersome to specify which scheme you wanted. Hence this trait. > **Note**: There appears to be a bug in `rustdoc`'s output. This trait is implemented *for all* types. */ pub trait ApproxWith<Dst> { /// Approximate the subject with the default scheme. fn approx(self) -> Result<Dst, Self::Err> where Self: Sized + ApproxInto<Dst> { self.approx_into() } /// Approximate the subject with a specific scheme. fn approx_with<Scheme=DefaultApprox>(self) -> Result<Dst, Self::Err> where Self: Sized + ApproxInto<Dst, Scheme>, Scheme: ApproxScheme, { self.approx_into() } } impl<T, Dst> ApproxWith<Dst> for T {} /** This trait is used to mark approximation scheme types. */ pub trait ApproxScheme {} /** The "default" approximation scheme. This scheme does whatever would generally be expected of a lossy conversion, assuming no additional context or instruction is given. This is a double-edged sword: it has the loosest semantics, but is far more likely to exist than more complicated approximation schemes. */ pub enum DefaultApprox {} impl ApproxScheme for DefaultApprox {} /** This scheme is used to convert a value by "wrapping" it into a narrower range. In abstract, this can be viewed as the opposite of rounding: rather than preserving the most significant bits of a value, it preserves the *least* significant bits of a value. */ pub enum Wrapping {} i
oxScheme for Wrapping {} // TODO: RoundToNearest, RoundToPosInf, RoundToNegInf, RoundToZero /** This trait is used to perform a conversion between different semantic types which might fail. # Details Typically, this should be used in cases where you are converting between values whose ranges and/or representations only partially overlap. That the conversion may fail should be a reasonably expected outcome. A standard example of this is converting from integers to enums of unitary variants. */ pub trait TryFrom<Src> { /// The error type produced by a failed conversion. type Err; /// Convert the given value into the subject type. fn try_from(src: Src) -> Result<Self, Self::Err>; } impl<Src> TryFrom<Src> for Src { type Err = NoError; fn try_from(src: Src) -> Result<Self, Self::Err> { Ok(src) } } /** This is the dual of `TryFrom`; see that trait for information. */ pub trait TryInto<Dst> { /// The error type produced by a failed conversion. type Err; /// Convert the subject into the destination type. fn try_into(self) -> Result<Dst, Self::Err>; } impl<Src, Dst> TryInto<Dst> for Src where Dst: TryFrom<Src> { type Err = Dst::Err; fn try_into(self) -> Result<Dst, Self::Err> { TryFrom::try_from(self) } } /** This trait is used to perform an exact, value-preserving conversion. # Details Implementations of this trait should be reflexive, associative and commutative (in the absence of conversion errors). That is, all possible cycles of `ValueFrom` conversions (for which each "step" has a defined implementation) should produce the same result, with a given value either being "round-tripped" exactly, or an error being produced. */ pub trait ValueFrom<Src> { /// The error type produced by a failed conversion. type Err; /// Convert the given value into an exactly equivalent representation. fn value_from(src: Src) -> Result<Self, Self::Err>; } impl<Src> ValueFrom<Src> for Src { type Err = NoError; fn value_from(src: Src) -> Result<Self, Self::Err> { Ok(src) } } /** This is the dual of `ValueFrom`; see that trait for information. */ pub trait ValueInto<Dst> { /// The error type produced by a failed conversion. type Err; /// Convert the subject into an exactly equivalent representation. fn value_into(self) -> Result<Dst, Self::Err>; } impl<Src, Dst> ValueInto<Dst> for Src where Dst: ValueFrom<Src> { type Err = Dst::Err; fn value_into(self) -> Result<Dst, Self::Err> { ValueFrom::value_from(self) } }
mpl Appr
identifier_name
lib.rs
/*! This crate provides a number of conversion traits with more specific semantics than those provided by `as` or `From`/`Into`. The goal with the traits provided here is to be more specific about what generic code can rely on, as well as provide reasonably self-describing alternatives to the standard `From`/`Into` traits. For example, the although `T: From<U>` might be satisfied, it imposes no restrictions on the *kind* of conversion being implemented. As such, the traits in this crate try to be very specific about what conversions are allowed. This makes them less generally applicable, but more useful where they *do* apply. In addition, `From`/`Into` requires all conversions to succeed or panic. All conversion traits in this crate define an associated error type, allowing code to react to failed conversions as appropriate. # API Stability Notice The API of this crate is still not entirely decided. In particular, errors may change in the future to carry the value that failed to convert (allowing it to be recovered). # Overview The following traits are used to define various conversion semantics: - [`ApproxFrom`](./trait.ApproxFrom.html)/[`ApproxInto`](./trait.ApproxInto.html) - approximate conversions, with selectable approximation scheme (see [`ApproxScheme`](./trait.ApproxScheme.html)). - [`TryFrom`](./trait.TryFrom.html)/[`TryInto`](./trait.TryInto.html) - general, potentially failing value conversions. - [`ValueFrom`](./trait.ValueFrom.html)/[`ValueInto`](./trait.ValueInto.html) - exact, value-preserving conversions. These extension methods are provided to help with some common cases: - [`ApproxWith::approx`](./trait.ApproxWith.html#method.approx) - calls `ApproxInto::approx_into` with the `DefaultApprox` scheme. - [`ApproxWith::approx_with<S>`](./trait.ApproxWith.html#method.approx_with) - calls `ApproxInto::approx_into` with the `S` approximation scheme. - [`UnwrapOk::unwrap_ok`](./errors/trait.UnwrapOk.html#tymethod.unwrap_ok) - unwraps results from conversions that cannot fail. - [`UnwrapOrInf::unwrap_or_inf`](./errors/trait.UnwrapOrInf.html#tymethod.unwrap_or_inf) - saturates to ±∞ on failure. - [`UnwrapOrInvalid::unwrap_or_invalid`](./errors/trait.UnwrapOrInvalid.html#tymethod.unwrap_or_invalid) - substitutes the target type's "invalid" sentinel value on failure. - [`UnwrapOrSaturate::unwrap_or_saturate`](./errors/trait.UnwrapOrSaturate.html#tymethod.unwrap_or_saturate) - saturates to the maximum or minimum value of the target type on failure. A macro is provided to assist in implementing conversions: - [`TryFrom!`](./macros/index.html#tryfrom!) - derives an implementation of [`TryFrom`](./trait.TryFrom.html). If you are implementing your own types, you may also be interested in the traits contained in the [`misc`](./misc/index.html) module. ## Provided Implementations The crate provides several blanket implementations: - `*From<A> for A` (all types can be converted from and into themselves). - `*Into<Dst> for Src where Dst: *From<Src>` (`*From` implementations imply a matching `*Into` implementation). Conversions for the builtin numeric (integer and floating point) types are provided. In general, `ValueFrom` conversions exist for all pairs except for float → integer (since such a conversion is generally unlikely to *exactly* succeed) and `f64 → f32` (for the same reason). `ApproxFrom` conversions with the `DefaultApprox` scheme exist between all pairs. `ApproxFrom` with the `Wrapping` scheme exist between integers. ## Errors A number of error types are defined in the [`errors`](./errors/index.html) module. Generally, conversions use whichever error type most *narrowly* defines the kinds of failures that can occur. For example: - `ValueFrom<u8> for u16` cannot possibly fail, and as such it uses `NoError`. - `ValueFrom<i8> for u16` can *only* fail with an underflow, thus it uses the `Underflow` type. - `ValueFrom<i32> for u16` can underflow *or* overflow, hence it uses `RangeError`. - Finally, `ApproxFrom<f32> for u16` can underflow, overflow, or attempt to convert NaN; `FloatError` covers those three cases. Because there are *numerous* error types, the `GeneralError` enum is provided. `From<E> for GeneralError` exists for each error type `E` defined by this crate (even for `NoError`!), allowing errors to be translated automatically by `try!`. In fact, all errors can be "expanded" to *all* more general forms (*e.g.* `NoError` → `Underflow`, `Overflow` → `RangeError` → `FloatError`). The reason for not just using `GeneralError` in the first place is to statically reduce the number of potential error cases you need to deal with. It also allows the `Unwrap*` extension traits to be defined *without* the possibility for runtime failure (*e.g.* you cannot use `unwrap_or_saturate` with a `FloatError`, because what do you do if the error is `NotANumber`; saturate to max or to min? Or panic?). # Examples ``` # extern crate conv; # use conv::*; # fn main() { // This *cannot* fail, so we can use `unwrap_ok` to discard the `Result`. assert_eq!(u8::value_from(0u8).unwrap_ok(), 0u8); // This *can* fail. Specifically, it can underflow. assert_eq!(u8::value_from(0i8), Ok(0u8)); assert_eq!(u8::value_from(-1i8), Err(Underflow)); // This can underflow *and* overflow; hence the change to `RangeError`. assert_eq!(u8::value_from(-1i16), Err(RangeError::Underflow)); assert_eq!(u8::value_from(0i16), Ok(0u8)); assert_eq!(u8::value_from(256i16), Err(RangeError::Overflow)); // We can use the extension traits to simplify this a little. assert_eq!(u8::value_from(-1i16).unwrap_or_saturate(), 0u8); assert_eq!(u8::value_from(0i16).unwrap_or_saturate(), 0u8); assert_eq!(u8::value_from(256i16).unwrap_or_saturate(), 255u8); // Obviously, all integers can be "approximated" using the default scheme (it // doesn't *do* anything), but they can *also* be approximated with the // `Wrapping` scheme. assert_eq!( <u8 as ApproxFrom<_, DefaultApprox>>::approx_from(400u16), Err(Overflow)); assert_eq!( <u8 as ApproxFrom<_, Wrapping>>::approx_from(400u16), Ok(144u8)); // This is rather inconvenient; as such, provided the return type can be // inferred, you can use `ApproxWith::approx` (for the default scheme) and // `ApproxWith::approx_with`. assert_eq!(400u16.approx(), Err::<u8, _>(Overflow)); assert_eq!(400u16.approx_with::<Wrapping>(), Ok::<u8, _>(144u8)); // Integer -> float conversions *can* fail due to limited precision. // Once the continuous range of exactly representable integers is exceeded, the // provided implementations fail with over/underflow errors. assert_eq!(f32::value_from(16_777_216i32), Ok(16_777_216.0f32)); assert_eq!(f32::value_from(16_777_217i32), Err(RangeError::Overflow)); // Float -> integer conversions have to be done using approximations. Although // exact conversions are *possible*, "advertising" this with an implementation // is misleading. // // Note that `DefaultApprox` for float -> integer uses whatever rounding // mode is currently active (*i.e.* whatever `as` would do). assert_eq!(41.0f32.approx(), Ok(41u8)); assert_eq!(41.3f32.approx(), Ok(41u8)); assert_eq!(41.5f32.approx(), Ok(41u8)); assert_eq!(41.8f32.approx(), Ok(41u8)); assert_eq!(42.0f32.approx(), Ok(42u8)); assert_eq!(255.0f32.approx(), Ok(255u8)); assert_eq!(256.0f32.approx(), Err::<u8, _>(FloatError::Overflow)); // If you really don't care about the specific kind of error, you can just rely // on automatic conversion to `GeneralError`. fn too_many_errors() -> Result<(), GeneralError> { assert_eq!({let r: u8 = try!(0u8.value_into()); r}, 0u8); assert_eq!({let r: u8 = try!(0i8.value_into()); r}, 0u8); assert_eq!({let r: u8 = try!(0i16.value_into()); r}, 0u8); assert_eq!({let r: u8 = try!(0.0f32.approx()); r}, 0u8); Ok(()) } # let _ = too_many_errors(); # } ``` */ #![deny(missing_docs)] // Exported macros. pub mod macros; pub use errors::{ NoError, GeneralError, Unrepresentable, Underflow, Overflow, FloatError, RangeError, UnwrapOk, UnwrapOrInf, UnwrapOrInvalid, UnwrapOrSaturate, }; /** Publicly re-exports the most generally useful set of items. Usage of the prelude should be considered **unstable**. Although items will likely *not* be removed without bumping the major version, new items *may* be added, which could potentially cause name conflicts in user code. */ pub mod prelude { pub use super::{ ApproxFrom, ApproxInto, ApproxWith, ValueFrom, ValueInto, UnwrapOk, UnwrapOrInf, UnwrapOrInvalid, UnwrapOrSaturate, }; } macro_rules! as_item { ($($i:item)*) => {$($i)*}; } macro_rules! item_for_each { ( $( ($($arg:tt)*) ),* $(,)* => { $($exp:tt)* } ) => { macro_rules! body { $($exp)* } $( body! { $($arg)* } )* }; } pub mod errors; pub mod misc; mod impls; /** This trait is used to perform a conversion that is permitted to approximate the result, but *not* to wrap or saturate the result to fit into the destination type's representable range. # Details All implementations of this trait must provide a conversion that can be separated into two logical steps: an approximation transform, and a representation transform. The "approximation transform" step involves transforming the input value into an approximately equivalent value which is supported by the target type *without* taking the target type's representable range into account. For example, this might involve rounding or truncating a floating point value to an integer, or reducing the accuracy of a floating point value. The "representation transform" step *exactly* rewrites the value from the source type's binary representation into the destination type's binary representation. This step *may not* transform the value in any way. If the result of the approximation is not representable, the conversion *must* fail. The major reason for this formulation is to exactly define what happens when converting between floating point and integer types. Often, it is unclear what happens to floating point values beyond the range of the target integer type. Do they saturate, wrap, or cause a failure? With this formulation, it is well-defined: if a floating point value is outside the representable range, the conversion fails. This allows users to distinguish between approximation and range violation, and act accordingly. */ pub trait ApproxFrom<Src, Scheme=DefaultApprox> where Scheme: ApproxScheme { /// The error type produced by a failed conversion. type Err; /// Convert the given value into an approximately equivalent representation. fn approx_from(src: Src) -> Result<Self, Self::Err>; } impl<Src, Scheme> ApproxFrom<Src, Scheme> for Src where Scheme: ApproxScheme { type Err = NoError; fn approx_from(src: Src) -> Result<Self, Self::Err> { Ok(
is the dual of `ApproxFrom`; see that trait for information. */ pub trait ApproxInto<Dst, Scheme=DefaultApprox> where Scheme: ApproxScheme { /// The error type produced by a failed conversion. type Err; /// Convert the subject into an approximately equivalent representation. fn approx_into(self) -> Result<Dst, Self::Err>; } impl<Dst, Src, Scheme> ApproxInto<Dst, Scheme> for Src where Dst: ApproxFrom<Src, Scheme>, Scheme: ApproxScheme, { type Err = Dst::Err; fn approx_into(self) -> Result<Dst, Self::Err> { ApproxFrom::approx_from(self) } } /** This extension trait exists to simplify using approximation implementations. If there is more than one `ApproxFrom` implementation for a given type, a simple call to `approx_into` may not be uniquely resolvable. Due to the position of the scheme parameter (on the trait itself), it is cumbersome to specify which scheme you wanted. Hence this trait. > **Note**: There appears to be a bug in `rustdoc`'s output. This trait is implemented *for all* types. */ pub trait ApproxWith<Dst> { /// Approximate the subject with the default scheme. fn approx(self) -> Result<Dst, Self::Err> where Self: Sized + ApproxInto<Dst> { self.approx_into() } /// Approximate the subject with a specific scheme. fn approx_with<Scheme=DefaultApprox>(self) -> Result<Dst, Self::Err> where Self: Sized + ApproxInto<Dst, Scheme>, Scheme: ApproxScheme, { self.approx_into() } } impl<T, Dst> ApproxWith<Dst> for T {} /** This trait is used to mark approximation scheme types. */ pub trait ApproxScheme {} /** The "default" approximation scheme. This scheme does whatever would generally be expected of a lossy conversion, assuming no additional context or instruction is given. This is a double-edged sword: it has the loosest semantics, but is far more likely to exist than more complicated approximation schemes. */ pub enum DefaultApprox {} impl ApproxScheme for DefaultApprox {} /** This scheme is used to convert a value by "wrapping" it into a narrower range. In abstract, this can be viewed as the opposite of rounding: rather than preserving the most significant bits of a value, it preserves the *least* significant bits of a value. */ pub enum Wrapping {} impl ApproxScheme for Wrapping {} // TODO: RoundToNearest, RoundToPosInf, RoundToNegInf, RoundToZero /** This trait is used to perform a conversion between different semantic types which might fail. # Details Typically, this should be used in cases where you are converting between values whose ranges and/or representations only partially overlap. That the conversion may fail should be a reasonably expected outcome. A standard example of this is converting from integers to enums of unitary variants. */ pub trait TryFrom<Src> { /// The error type produced by a failed conversion. type Err; /// Convert the given value into the subject type. fn try_from(src: Src) -> Result<Self, Self::Err>; } impl<Src> TryFrom<Src> for Src { type Err = NoError; fn try_from(src: Src) -> Result<Self, Self::Err> { Ok(src) } } /** This is the dual of `TryFrom`; see that trait for information. */ pub trait TryInto<Dst> { /// The error type produced by a failed conversion. type Err; /// Convert the subject into the destination type. fn try_into(self) -> Result<Dst, Self::Err>; } impl<Src, Dst> TryInto<Dst> for Src where Dst: TryFrom<Src> { type Err = Dst::Err; fn try_into(self) -> Result<Dst, Self::Err> { TryFrom::try_from(self) } } /** This trait is used to perform an exact, value-preserving conversion. # Details Implementations of this trait should be reflexive, associative and commutative (in the absence of conversion errors). That is, all possible cycles of `ValueFrom` conversions (for which each "step" has a defined implementation) should produce the same result, with a given value either being "round-tripped" exactly, or an error being produced. */ pub trait ValueFrom<Src> { /// The error type produced by a failed conversion. type Err; /// Convert the given value into an exactly equivalent representation. fn value_from(src: Src) -> Result<Self, Self::Err>; } impl<Src> ValueFrom<Src> for Src { type Err = NoError; fn value_from(src: Src) -> Result<Self, Self::Err> { Ok(src) } } /** This is the dual of `ValueFrom`; see that trait for information. */ pub trait ValueInto<Dst> { /// The error type produced by a failed conversion. type Err; /// Convert the subject into an exactly equivalent representation. fn value_into(self) -> Result<Dst, Self::Err>; } impl<Src, Dst> ValueInto<Dst> for Src where Dst: ValueFrom<Src> { type Err = Dst::Err; fn value_into(self) -> Result<Dst, Self::Err> { ValueFrom::value_from(self) } }
src) } } /** This
identifier_body
stmt.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use build::scope::BreakableScope; use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; use hair::*; use rustc::mir::*; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Builds a block of MIR statements to evaluate the HAIR `expr`. /// If the original expression was an AST statement, /// (e.g., `some().code(&here());`) then `opt_stmt_span` is the /// span of that statement (including its semicolon, if any). /// Diagnostics use this span (which may be larger than that of /// `expr`) to identify when statement temporaries are dropped. pub fn
(&mut self, mut block: BasicBlock, expr: Expr<'tcx>, opt_stmt_span: Option<StatementSpan>) -> BlockAnd<()> { let this = self; let expr_span = expr.span; let source_info = this.source_info(expr.span); // Handle a number of expressions that don't need a destination at all. This // avoids needing a mountain of temporary `()` variables. let expr2 = expr.clone(); match expr.kind { ExprKind::Scope { region_scope, lint_level, value, } => { let value = this.hir.mirror(value); this.in_scope((region_scope, source_info), lint_level, block, |this| { this.stmt_expr(block, value, opt_stmt_span) }) } ExprKind::Assign { lhs, rhs } => { let lhs = this.hir.mirror(lhs); let rhs = this.hir.mirror(rhs); let lhs_span = lhs.span; // Note: we evaluate assignments right-to-left. This // is better for borrowck interaction with overloaded // operators like x[j] = x[i]. debug!("stmt_expr Assign block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); // Generate better code for things that don't need to be // dropped. if this.hir.needs_drop(lhs.ty) { let rhs = unpack!(block = this.as_local_operand(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); unpack!(block = this.build_drop_and_replace(block, lhs_span, lhs, rhs)); } else { let rhs = unpack!(block = this.as_local_rvalue(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); this.cfg.push_assign(block, source_info, &lhs, rhs); } this.block_context.pop(); block.unit() } ExprKind::AssignOp { op, lhs, rhs } => { // FIXME(#28160) there is an interesting semantics // question raised here -- should we "freeze" the // value of the lhs here? I'm inclined to think not, // since it seems closer to the semantics of the // overloaded version, which takes `&mut self`. This // only affects weird things like `x += {x += 1; x}` // -- is that equal to `x + (x + 1)` or `2*(x+1)`? let lhs = this.hir.mirror(lhs); let lhs_ty = lhs.ty; debug!("stmt_expr AssignOp block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); // As above, RTL. let rhs = unpack!(block = this.as_local_operand(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); // we don't have to drop prior contents or anything // because AssignOp is only legal for Copy types // (overloaded ops should be desugared into a call). let result = unpack!( block = this.build_binary_op( block, op, expr_span, lhs_ty, Operand::Copy(lhs.clone()), rhs ) ); this.cfg.push_assign(block, source_info, &lhs, result); this.block_context.pop(); block.unit() } ExprKind::Continue { label } => { let BreakableScope { continue_block, region_scope, .. } = *this.find_breakable_scope(expr_span, label); let continue_block = continue_block .expect("Attempted to continue in non-continuable breakable block"); this.exit_scope( expr_span, (region_scope, source_info), block, continue_block, ); this.cfg.start_new_block().unit() } ExprKind::Break { label, value } => { let (break_block, region_scope, destination) = { let BreakableScope { break_block, region_scope, ref break_destination, .. } = *this.find_breakable_scope(expr_span, label); (break_block, region_scope, break_destination.clone()) }; if let Some(value) = value { debug!("stmt_expr Break val block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); unpack!(block = this.into(&destination, block, value)); this.block_context.pop(); } else { this.cfg.push_assign_unit(block, source_info, &destination) } this.exit_scope(expr_span, (region_scope, source_info), block, break_block); this.cfg.start_new_block().unit() } ExprKind::Return { value } => { block = match value { Some(value) => { debug!("stmt_expr Return val block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); let result = unpack!(this.into(&Place::Local(RETURN_PLACE), block, value)); this.block_context.pop(); result } None => { this.cfg .push_assign_unit(block, source_info, &Place::Local(RETURN_PLACE)); block } }; let region_scope = this.region_scope_of_return_scope(); let return_block = this.return_block(); this.exit_scope(expr_span, (region_scope, source_info), block, return_block); this.cfg.start_new_block().unit() } ExprKind::InlineAsm { asm, outputs, inputs, } => { debug!("stmt_expr InlineAsm block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); let outputs = outputs .into_iter() .map(|output| unpack!(block = this.as_place(block, output))) .collect::<Vec<_>>() .into_boxed_slice(); let inputs = inputs .into_iter() .map(|input| { ( input.span(), unpack!(block = this.as_local_operand(block, input)), ) }).collect::<Vec<_>>() .into_boxed_slice(); this.cfg.push( block, Statement { source_info, kind: StatementKind::InlineAsm { asm: box asm.clone(), outputs, inputs, }, }, ); this.block_context.pop(); block.unit() } _ => { let expr_ty = expr.ty; // Issue #54382: When creating temp for the value of // expression like: // // `{ side_effects(); { let l = stuff(); the_value } }` // // it is usually better to focus on `the_value` rather // than the entirety of block(s) surrounding it. let mut temp_span = expr_span; let mut temp_in_tail_of_block = false; if let ExprKind::Block { body } = expr.kind { if let Some(tail_expr) = &body.expr { let mut expr = tail_expr; while let rustc::hir::ExprKind::Block(subblock, _label) = &expr.node { if let Some(subtail_expr) = &subblock.expr { expr = subtail_expr } else { break; } } temp_span = expr.span; temp_in_tail_of_block = true; } } let temp = { let mut local_decl = LocalDecl::new_temp(expr.ty.clone(), temp_span); if temp_in_tail_of_block { if this.block_context.currently_ignores_tail_results() { local_decl = local_decl.block_tail(BlockTailInfo { tail_result_is_ignored: true }); } } let temp = this.local_decls.push(local_decl); let place = Place::Local(temp); debug!("created temp {:?} for expr {:?} in block_context: {:?}", temp, expr, this.block_context); place }; unpack!(block = this.into(&temp, block, expr)); // Attribute drops of the statement's temps to the // semicolon at the statement's end. let drop_point = this.hir.tcx().sess.source_map().end_point(match opt_stmt_span { None => expr_span, Some(StatementSpan(span)) => span, }); unpack!(block = this.build_drop(block, drop_point, temp, expr_ty)); block.unit() } } } }
stmt_expr
identifier_name
stmt.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use build::scope::BreakableScope; use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; use hair::*; use rustc::mir::*; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Builds a block of MIR statements to evaluate the HAIR `expr`. /// If the original expression was an AST statement, /// (e.g., `some().code(&here());`) then `opt_stmt_span` is the /// span of that statement (including its semicolon, if any). /// Diagnostics use this span (which may be larger than that of /// `expr`) to identify when statement temporaries are dropped. pub fn stmt_expr(&mut self, mut block: BasicBlock, expr: Expr<'tcx>, opt_stmt_span: Option<StatementSpan>) -> BlockAnd<()>
let rhs = this.hir.mirror(rhs); let lhs_span = lhs.span; // Note: we evaluate assignments right-to-left. This // is better for borrowck interaction with overloaded // operators like x[j] = x[i]. debug!("stmt_expr Assign block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); // Generate better code for things that don't need to be // dropped. if this.hir.needs_drop(lhs.ty) { let rhs = unpack!(block = this.as_local_operand(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); unpack!(block = this.build_drop_and_replace(block, lhs_span, lhs, rhs)); } else { let rhs = unpack!(block = this.as_local_rvalue(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); this.cfg.push_assign(block, source_info, &lhs, rhs); } this.block_context.pop(); block.unit() } ExprKind::AssignOp { op, lhs, rhs } => { // FIXME(#28160) there is an interesting semantics // question raised here -- should we "freeze" the // value of the lhs here? I'm inclined to think not, // since it seems closer to the semantics of the // overloaded version, which takes `&mut self`. This // only affects weird things like `x += {x += 1; x}` // -- is that equal to `x + (x + 1)` or `2*(x+1)`? let lhs = this.hir.mirror(lhs); let lhs_ty = lhs.ty; debug!("stmt_expr AssignOp block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); // As above, RTL. let rhs = unpack!(block = this.as_local_operand(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); // we don't have to drop prior contents or anything // because AssignOp is only legal for Copy types // (overloaded ops should be desugared into a call). let result = unpack!( block = this.build_binary_op( block, op, expr_span, lhs_ty, Operand::Copy(lhs.clone()), rhs ) ); this.cfg.push_assign(block, source_info, &lhs, result); this.block_context.pop(); block.unit() } ExprKind::Continue { label } => { let BreakableScope { continue_block, region_scope, .. } = *this.find_breakable_scope(expr_span, label); let continue_block = continue_block .expect("Attempted to continue in non-continuable breakable block"); this.exit_scope( expr_span, (region_scope, source_info), block, continue_block, ); this.cfg.start_new_block().unit() } ExprKind::Break { label, value } => { let (break_block, region_scope, destination) = { let BreakableScope { break_block, region_scope, ref break_destination, .. } = *this.find_breakable_scope(expr_span, label); (break_block, region_scope, break_destination.clone()) }; if let Some(value) = value { debug!("stmt_expr Break val block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); unpack!(block = this.into(&destination, block, value)); this.block_context.pop(); } else { this.cfg.push_assign_unit(block, source_info, &destination) } this.exit_scope(expr_span, (region_scope, source_info), block, break_block); this.cfg.start_new_block().unit() } ExprKind::Return { value } => { block = match value { Some(value) => { debug!("stmt_expr Return val block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); let result = unpack!(this.into(&Place::Local(RETURN_PLACE), block, value)); this.block_context.pop(); result } None => { this.cfg .push_assign_unit(block, source_info, &Place::Local(RETURN_PLACE)); block } }; let region_scope = this.region_scope_of_return_scope(); let return_block = this.return_block(); this.exit_scope(expr_span, (region_scope, source_info), block, return_block); this.cfg.start_new_block().unit() } ExprKind::InlineAsm { asm, outputs, inputs, } => { debug!("stmt_expr InlineAsm block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); let outputs = outputs .into_iter() .map(|output| unpack!(block = this.as_place(block, output))) .collect::<Vec<_>>() .into_boxed_slice(); let inputs = inputs .into_iter() .map(|input| { ( input.span(), unpack!(block = this.as_local_operand(block, input)), ) }).collect::<Vec<_>>() .into_boxed_slice(); this.cfg.push( block, Statement { source_info, kind: StatementKind::InlineAsm { asm: box asm.clone(), outputs, inputs, }, }, ); this.block_context.pop(); block.unit() } _ => { let expr_ty = expr.ty; // Issue #54382: When creating temp for the value of // expression like: // // `{ side_effects(); { let l = stuff(); the_value } }` // // it is usually better to focus on `the_value` rather // than the entirety of block(s) surrounding it. let mut temp_span = expr_span; let mut temp_in_tail_of_block = false; if let ExprKind::Block { body } = expr.kind { if let Some(tail_expr) = &body.expr { let mut expr = tail_expr; while let rustc::hir::ExprKind::Block(subblock, _label) = &expr.node { if let Some(subtail_expr) = &subblock.expr { expr = subtail_expr } else { break; } } temp_span = expr.span; temp_in_tail_of_block = true; } } let temp = { let mut local_decl = LocalDecl::new_temp(expr.ty.clone(), temp_span); if temp_in_tail_of_block { if this.block_context.currently_ignores_tail_results() { local_decl = local_decl.block_tail(BlockTailInfo { tail_result_is_ignored: true }); } } let temp = this.local_decls.push(local_decl); let place = Place::Local(temp); debug!("created temp {:?} for expr {:?} in block_context: {:?}", temp, expr, this.block_context); place }; unpack!(block = this.into(&temp, block, expr)); // Attribute drops of the statement's temps to the // semicolon at the statement's end. let drop_point = this.hir.tcx().sess.source_map().end_point(match opt_stmt_span { None => expr_span, Some(StatementSpan(span)) => span, }); unpack!(block = this.build_drop(block, drop_point, temp, expr_ty)); block.unit() } } } }
{ let this = self; let expr_span = expr.span; let source_info = this.source_info(expr.span); // Handle a number of expressions that don't need a destination at all. This // avoids needing a mountain of temporary `()` variables. let expr2 = expr.clone(); match expr.kind { ExprKind::Scope { region_scope, lint_level, value, } => { let value = this.hir.mirror(value); this.in_scope((region_scope, source_info), lint_level, block, |this| { this.stmt_expr(block, value, opt_stmt_span) }) } ExprKind::Assign { lhs, rhs } => { let lhs = this.hir.mirror(lhs);
identifier_body
stmt.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use build::scope::BreakableScope; use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; use hair::*; use rustc::mir::*; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Builds a block of MIR statements to evaluate the HAIR `expr`. /// If the original expression was an AST statement, /// (e.g., `some().code(&here());`) then `opt_stmt_span` is the /// span of that statement (including its semicolon, if any). /// Diagnostics use this span (which may be larger than that of /// `expr`) to identify when statement temporaries are dropped. pub fn stmt_expr(&mut self, mut block: BasicBlock, expr: Expr<'tcx>, opt_stmt_span: Option<StatementSpan>) -> BlockAnd<()> { let this = self; let expr_span = expr.span; let source_info = this.source_info(expr.span); // Handle a number of expressions that don't need a destination at all. This // avoids needing a mountain of temporary `()` variables. let expr2 = expr.clone(); match expr.kind { ExprKind::Scope { region_scope, lint_level, value, } => { let value = this.hir.mirror(value); this.in_scope((region_scope, source_info), lint_level, block, |this| { this.stmt_expr(block, value, opt_stmt_span) }) } ExprKind::Assign { lhs, rhs } => { let lhs = this.hir.mirror(lhs); let rhs = this.hir.mirror(rhs); let lhs_span = lhs.span; // Note: we evaluate assignments right-to-left. This // is better for borrowck interaction with overloaded // operators like x[j] = x[i]. debug!("stmt_expr Assign block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); // Generate better code for things that don't need to be // dropped. if this.hir.needs_drop(lhs.ty) { let rhs = unpack!(block = this.as_local_operand(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); unpack!(block = this.build_drop_and_replace(block, lhs_span, lhs, rhs)); } else { let rhs = unpack!(block = this.as_local_rvalue(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); this.cfg.push_assign(block, source_info, &lhs, rhs); } this.block_context.pop(); block.unit() } ExprKind::AssignOp { op, lhs, rhs } => { // FIXME(#28160) there is an interesting semantics // question raised here -- should we "freeze" the // value of the lhs here? I'm inclined to think not, // since it seems closer to the semantics of the // overloaded version, which takes `&mut self`. This // only affects weird things like `x += {x += 1; x}` // -- is that equal to `x + (x + 1)` or `2*(x+1)`? let lhs = this.hir.mirror(lhs); let lhs_ty = lhs.ty; debug!("stmt_expr AssignOp block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); // As above, RTL. let rhs = unpack!(block = this.as_local_operand(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); // we don't have to drop prior contents or anything // because AssignOp is only legal for Copy types // (overloaded ops should be desugared into a call). let result = unpack!( block = this.build_binary_op( block, op, expr_span, lhs_ty, Operand::Copy(lhs.clone()), rhs ) ); this.cfg.push_assign(block, source_info, &lhs, result); this.block_context.pop(); block.unit() } ExprKind::Continue { label } => { let BreakableScope { continue_block, region_scope, .. } = *this.find_breakable_scope(expr_span, label); let continue_block = continue_block .expect("Attempted to continue in non-continuable breakable block"); this.exit_scope( expr_span, (region_scope, source_info), block, continue_block, ); this.cfg.start_new_block().unit() } ExprKind::Break { label, value } => { let (break_block, region_scope, destination) = { let BreakableScope { break_block, region_scope, ref break_destination, .. } = *this.find_breakable_scope(expr_span, label); (break_block, region_scope, break_destination.clone()) }; if let Some(value) = value { debug!("stmt_expr Break val block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); unpack!(block = this.into(&destination, block, value)); this.block_context.pop(); } else { this.cfg.push_assign_unit(block, source_info, &destination) } this.exit_scope(expr_span, (region_scope, source_info), block, break_block); this.cfg.start_new_block().unit() } ExprKind::Return { value } => { block = match value { Some(value) =>
None => { this.cfg .push_assign_unit(block, source_info, &Place::Local(RETURN_PLACE)); block } }; let region_scope = this.region_scope_of_return_scope(); let return_block = this.return_block(); this.exit_scope(expr_span, (region_scope, source_info), block, return_block); this.cfg.start_new_block().unit() } ExprKind::InlineAsm { asm, outputs, inputs, } => { debug!("stmt_expr InlineAsm block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); let outputs = outputs .into_iter() .map(|output| unpack!(block = this.as_place(block, output))) .collect::<Vec<_>>() .into_boxed_slice(); let inputs = inputs .into_iter() .map(|input| { ( input.span(), unpack!(block = this.as_local_operand(block, input)), ) }).collect::<Vec<_>>() .into_boxed_slice(); this.cfg.push( block, Statement { source_info, kind: StatementKind::InlineAsm { asm: box asm.clone(), outputs, inputs, }, }, ); this.block_context.pop(); block.unit() } _ => { let expr_ty = expr.ty; // Issue #54382: When creating temp for the value of // expression like: // // `{ side_effects(); { let l = stuff(); the_value } }` // // it is usually better to focus on `the_value` rather // than the entirety of block(s) surrounding it. let mut temp_span = expr_span; let mut temp_in_tail_of_block = false; if let ExprKind::Block { body } = expr.kind { if let Some(tail_expr) = &body.expr { let mut expr = tail_expr; while let rustc::hir::ExprKind::Block(subblock, _label) = &expr.node { if let Some(subtail_expr) = &subblock.expr { expr = subtail_expr } else { break; } } temp_span = expr.span; temp_in_tail_of_block = true; } } let temp = { let mut local_decl = LocalDecl::new_temp(expr.ty.clone(), temp_span); if temp_in_tail_of_block { if this.block_context.currently_ignores_tail_results() { local_decl = local_decl.block_tail(BlockTailInfo { tail_result_is_ignored: true }); } } let temp = this.local_decls.push(local_decl); let place = Place::Local(temp); debug!("created temp {:?} for expr {:?} in block_context: {:?}", temp, expr, this.block_context); place }; unpack!(block = this.into(&temp, block, expr)); // Attribute drops of the statement's temps to the // semicolon at the statement's end. let drop_point = this.hir.tcx().sess.source_map().end_point(match opt_stmt_span { None => expr_span, Some(StatementSpan(span)) => span, }); unpack!(block = this.build_drop(block, drop_point, temp, expr_ty)); block.unit() } } } }
{ debug!("stmt_expr Return val block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); let result = unpack!(this.into(&Place::Local(RETURN_PLACE), block, value)); this.block_context.pop(); result }
conditional_block
stmt.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use build::scope::BreakableScope; use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; use hair::*; use rustc::mir::*; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Builds a block of MIR statements to evaluate the HAIR `expr`. /// If the original expression was an AST statement, /// (e.g., `some().code(&here());`) then `opt_stmt_span` is the /// span of that statement (including its semicolon, if any). /// Diagnostics use this span (which may be larger than that of /// `expr`) to identify when statement temporaries are dropped. pub fn stmt_expr(&mut self, mut block: BasicBlock, expr: Expr<'tcx>, opt_stmt_span: Option<StatementSpan>) -> BlockAnd<()> { let this = self; let expr_span = expr.span; let source_info = this.source_info(expr.span); // Handle a number of expressions that don't need a destination at all. This // avoids needing a mountain of temporary `()` variables. let expr2 = expr.clone(); match expr.kind { ExprKind::Scope { region_scope, lint_level, value, } => { let value = this.hir.mirror(value); this.in_scope((region_scope, source_info), lint_level, block, |this| { this.stmt_expr(block, value, opt_stmt_span) }) } ExprKind::Assign { lhs, rhs } => { let lhs = this.hir.mirror(lhs); let rhs = this.hir.mirror(rhs); let lhs_span = lhs.span; // Note: we evaluate assignments right-to-left. This // is better for borrowck interaction with overloaded // operators like x[j] = x[i]. debug!("stmt_expr Assign block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); // Generate better code for things that don't need to be // dropped. if this.hir.needs_drop(lhs.ty) { let rhs = unpack!(block = this.as_local_operand(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); unpack!(block = this.build_drop_and_replace(block, lhs_span, lhs, rhs)); } else { let rhs = unpack!(block = this.as_local_rvalue(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); this.cfg.push_assign(block, source_info, &lhs, rhs); } this.block_context.pop(); block.unit() } ExprKind::AssignOp { op, lhs, rhs } => { // FIXME(#28160) there is an interesting semantics // question raised here -- should we "freeze" the // value of the lhs here? I'm inclined to think not, // since it seems closer to the semantics of the // overloaded version, which takes `&mut self`. This // only affects weird things like `x += {x += 1; x}` // -- is that equal to `x + (x + 1)` or `2*(x+1)`? let lhs = this.hir.mirror(lhs); let lhs_ty = lhs.ty; debug!("stmt_expr AssignOp block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); // As above, RTL. let rhs = unpack!(block = this.as_local_operand(block, rhs)); let lhs = unpack!(block = this.as_place(block, lhs)); // we don't have to drop prior contents or anything // because AssignOp is only legal for Copy types // (overloaded ops should be desugared into a call). let result = unpack!( block = this.build_binary_op( block, op, expr_span, lhs_ty, Operand::Copy(lhs.clone()), rhs ) ); this.cfg.push_assign(block, source_info, &lhs, result); this.block_context.pop(); block.unit() } ExprKind::Continue { label } => { let BreakableScope { continue_block, region_scope, .. } = *this.find_breakable_scope(expr_span, label); let continue_block = continue_block .expect("Attempted to continue in non-continuable breakable block"); this.exit_scope( expr_span, (region_scope, source_info), block, continue_block, ); this.cfg.start_new_block().unit() } ExprKind::Break { label, value } => { let (break_block, region_scope, destination) = { let BreakableScope { break_block, region_scope, ref break_destination, .. } = *this.find_breakable_scope(expr_span, label); (break_block, region_scope, break_destination.clone()) }; if let Some(value) = value { debug!("stmt_expr Break val block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); unpack!(block = this.into(&destination, block, value)); this.block_context.pop(); } else { this.cfg.push_assign_unit(block, source_info, &destination) } this.exit_scope(expr_span, (region_scope, source_info), block, break_block); this.cfg.start_new_block().unit() } ExprKind::Return { value } => { block = match value { Some(value) => { debug!("stmt_expr Return val block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); let result = unpack!(this.into(&Place::Local(RETURN_PLACE), block, value)); this.block_context.pop(); result } None => { this.cfg .push_assign_unit(block, source_info, &Place::Local(RETURN_PLACE)); block } }; let region_scope = this.region_scope_of_return_scope(); let return_block = this.return_block(); this.exit_scope(expr_span, (region_scope, source_info), block, return_block); this.cfg.start_new_block().unit() } ExprKind::InlineAsm { asm, outputs, inputs, } => {
.collect::<Vec<_>>() .into_boxed_slice(); let inputs = inputs .into_iter() .map(|input| { ( input.span(), unpack!(block = this.as_local_operand(block, input)), ) }).collect::<Vec<_>>() .into_boxed_slice(); this.cfg.push( block, Statement { source_info, kind: StatementKind::InlineAsm { asm: box asm.clone(), outputs, inputs, }, }, ); this.block_context.pop(); block.unit() } _ => { let expr_ty = expr.ty; // Issue #54382: When creating temp for the value of // expression like: // // `{ side_effects(); { let l = stuff(); the_value } }` // // it is usually better to focus on `the_value` rather // than the entirety of block(s) surrounding it. let mut temp_span = expr_span; let mut temp_in_tail_of_block = false; if let ExprKind::Block { body } = expr.kind { if let Some(tail_expr) = &body.expr { let mut expr = tail_expr; while let rustc::hir::ExprKind::Block(subblock, _label) = &expr.node { if let Some(subtail_expr) = &subblock.expr { expr = subtail_expr } else { break; } } temp_span = expr.span; temp_in_tail_of_block = true; } } let temp = { let mut local_decl = LocalDecl::new_temp(expr.ty.clone(), temp_span); if temp_in_tail_of_block { if this.block_context.currently_ignores_tail_results() { local_decl = local_decl.block_tail(BlockTailInfo { tail_result_is_ignored: true }); } } let temp = this.local_decls.push(local_decl); let place = Place::Local(temp); debug!("created temp {:?} for expr {:?} in block_context: {:?}", temp, expr, this.block_context); place }; unpack!(block = this.into(&temp, block, expr)); // Attribute drops of the statement's temps to the // semicolon at the statement's end. let drop_point = this.hir.tcx().sess.source_map().end_point(match opt_stmt_span { None => expr_span, Some(StatementSpan(span)) => span, }); unpack!(block = this.build_drop(block, drop_point, temp, expr_ty)); block.unit() } } } }
debug!("stmt_expr InlineAsm block_context.push(SubExpr) : {:?}", expr2); this.block_context.push(BlockFrame::SubExpr); let outputs = outputs .into_iter() .map(|output| unpack!(block = this.as_place(block, output)))
random_line_split
thread.rs
use alloc::boxed::Box; use syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, CLONE_VM, CLONE_FS, CLONE_FILES, TimeSpec}; use time::Duration; //TODO: Mutex the result pub struct JoinHandle<T> { result_ptr: *mut Option<T>, } impl<T> JoinHandle<T> { pub fn join(self) -> Option<T> { unsafe { while (*self.result_ptr).is_none() {
sys_yield(); } * Box::from_raw(self.result_ptr) } } } // Sleep for a duration pub fn sleep(duration: Duration) { let req = TimeSpec { tv_sec: duration.secs, tv_nsec: duration.nanos, }; let mut rem = TimeSpec { tv_sec: 0, tv_nsec: 0 }; unsafe { sys_nanosleep(&req, &mut rem) }; //Duration::new(rem.tv_sec, rem.tv_nsec) } // Sleep for a number of milliseconds pub fn sleep_ms(ms: u32) { let secs = ms as i64 / 1000; let nanos = (ms % 1000) as i32 * 1000000; sleep(Duration::new(secs, nanos)) } //TODO: Catch panic pub fn spawn<F, T>(f: F) -> JoinHandle<T> where F: FnOnce() -> T, F: Send +'static, T: Send +'static { unsafe { let result_ptr: *mut Option<T> = Box::into_raw(box None); if sys_clone(CLONE_VM | CLONE_FS | CLONE_FILES) == 0 { *result_ptr = Some(f()); sys_exit(0); } JoinHandle { result_ptr: result_ptr } } }
random_line_split
thread.rs
use alloc::boxed::Box; use syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, CLONE_VM, CLONE_FS, CLONE_FILES, TimeSpec}; use time::Duration; //TODO: Mutex the result pub struct JoinHandle<T> { result_ptr: *mut Option<T>, } impl<T> JoinHandle<T> { pub fn join(self) -> Option<T> { unsafe { while (*self.result_ptr).is_none() { sys_yield(); } * Box::from_raw(self.result_ptr) } } } // Sleep for a duration pub fn sleep(duration: Duration) { let req = TimeSpec { tv_sec: duration.secs, tv_nsec: duration.nanos, }; let mut rem = TimeSpec { tv_sec: 0, tv_nsec: 0 }; unsafe { sys_nanosleep(&req, &mut rem) }; //Duration::new(rem.tv_sec, rem.tv_nsec) } // Sleep for a number of milliseconds pub fn sleep_ms(ms: u32) { let secs = ms as i64 / 1000; let nanos = (ms % 1000) as i32 * 1000000; sleep(Duration::new(secs, nanos)) } //TODO: Catch panic pub fn spawn<F, T>(f: F) -> JoinHandle<T> where F: FnOnce() -> T, F: Send +'static, T: Send +'static { unsafe { let result_ptr: *mut Option<T> = Box::into_raw(box None); if sys_clone(CLONE_VM | CLONE_FS | CLONE_FILES) == 0
JoinHandle { result_ptr: result_ptr } } }
{ *result_ptr = Some(f()); sys_exit(0); }
conditional_block
thread.rs
use alloc::boxed::Box; use syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, CLONE_VM, CLONE_FS, CLONE_FILES, TimeSpec}; use time::Duration; //TODO: Mutex the result pub struct JoinHandle<T> { result_ptr: *mut Option<T>, } impl<T> JoinHandle<T> { pub fn join(self) -> Option<T> { unsafe { while (*self.result_ptr).is_none() { sys_yield(); } * Box::from_raw(self.result_ptr) } } } // Sleep for a duration pub fn sleep(duration: Duration)
// Sleep for a number of milliseconds pub fn sleep_ms(ms: u32) { let secs = ms as i64 / 1000; let nanos = (ms % 1000) as i32 * 1000000; sleep(Duration::new(secs, nanos)) } //TODO: Catch panic pub fn spawn<F, T>(f: F) -> JoinHandle<T> where F: FnOnce() -> T, F: Send +'static, T: Send +'static { unsafe { let result_ptr: *mut Option<T> = Box::into_raw(box None); if sys_clone(CLONE_VM | CLONE_FS | CLONE_FILES) == 0 { *result_ptr = Some(f()); sys_exit(0); } JoinHandle { result_ptr: result_ptr } } }
{ let req = TimeSpec { tv_sec: duration.secs, tv_nsec: duration.nanos, }; let mut rem = TimeSpec { tv_sec: 0, tv_nsec: 0 }; unsafe { sys_nanosleep(&req, &mut rem) }; //Duration::new(rem.tv_sec, rem.tv_nsec) }
identifier_body
thread.rs
use alloc::boxed::Box; use syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, CLONE_VM, CLONE_FS, CLONE_FILES, TimeSpec}; use time::Duration; //TODO: Mutex the result pub struct JoinHandle<T> { result_ptr: *mut Option<T>, } impl<T> JoinHandle<T> { pub fn join(self) -> Option<T> { unsafe { while (*self.result_ptr).is_none() { sys_yield(); } * Box::from_raw(self.result_ptr) } } } // Sleep for a duration pub fn sleep(duration: Duration) { let req = TimeSpec { tv_sec: duration.secs, tv_nsec: duration.nanos, }; let mut rem = TimeSpec { tv_sec: 0, tv_nsec: 0 }; unsafe { sys_nanosleep(&req, &mut rem) }; //Duration::new(rem.tv_sec, rem.tv_nsec) } // Sleep for a number of milliseconds pub fn
(ms: u32) { let secs = ms as i64 / 1000; let nanos = (ms % 1000) as i32 * 1000000; sleep(Duration::new(secs, nanos)) } //TODO: Catch panic pub fn spawn<F, T>(f: F) -> JoinHandle<T> where F: FnOnce() -> T, F: Send +'static, T: Send +'static { unsafe { let result_ptr: *mut Option<T> = Box::into_raw(box None); if sys_clone(CLONE_VM | CLONE_FS | CLONE_FILES) == 0 { *result_ptr = Some(f()); sys_exit(0); } JoinHandle { result_ptr: result_ptr } } }
sleep_ms
identifier_name
schedule.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Cost schedule and other parameterisations for the EVM. /// Definition of the cost schedule and other parameterisations for the EVM. pub struct Schedule { /// Does it support exceptional failed code deposit pub exceptional_failed_code_deposit: bool, /// Does it have a delegate cal pub have_delegate_call: bool, /// VM stack limit pub stack_limit: usize, /// Max number of nested calls/creates pub max_depth: usize, /// Gas prices for instructions in all tiers pub tier_step_gas: [usize; 8], /// Gas price for `EXP` opcode pub exp_gas: usize, /// Additional gas for `EXP` opcode for each byte of exponent pub exp_byte_gas: usize, /// Gas price for `SHA3` opcode pub sha3_gas: usize, /// Additional gas for `SHA3` opcode for each word of hashed memory pub sha3_word_gas: usize, /// Gas price for loading from storage pub sload_gas: usize, /// Gas price for setting new value to storage (`storage==0`, `new!=0`) pub sstore_set_gas: usize, /// Gas price for altering value in storage pub sstore_reset_gas: usize, /// Gas refund for `SSTORE` clearing (when `storage!=0`, `new==0`) pub sstore_refund_gas: usize, /// Gas price for `JUMPDEST` opcode pub jumpdest_gas: usize, /// Gas price for `LOG*` pub log_gas: usize, /// Additional gas for data in `LOG*` pub log_data_gas: usize, /// Additional gas for each topic in `LOG*` pub log_topic_gas: usize, /// Gas price for `CREATE` opcode pub create_gas: usize, /// Gas price for `*CALL*` opcodes pub call_gas: usize, /// Stipend for transfer for `CALL|CALLCODE` opcode when `value>0` pub call_stipend: usize, /// Additional gas required for value transfer (`CALL|CALLCODE`) pub call_value_transfer_gas: usize, /// Additional gas for creating new account (`CALL|CALLCODE`) pub call_new_account_gas: usize, /// Refund for SUICIDE pub suicide_refund_gas: usize, /// Gas for used memory pub memory_gas: usize, /// Coefficient used to convert memory size to gas price for memory pub quad_coeff_div: usize, /// Cost for contract length when executing `CREATE` pub create_data_gas: usize, /// Maximum code size when creating a contract. pub create_data_limit: usize, /// Transaction cost pub tx_gas: usize, /// `CREATE` transaction cost pub tx_create_gas: usize, /// Additional cost for empty data transaction pub tx_data_zero_gas: usize, /// Aditional cost for non-empty data transaction pub tx_data_non_zero_gas: usize, /// Gas price for copying memory pub copy_gas: usize, /// Price of EXTCODESIZE pub extcodesize_gas: usize, /// Base price of EXTCODECOPY pub extcodecopy_base_gas: usize, /// Price of BALANCE pub balance_gas: usize, /// Price of SUICIDE pub suicide_gas: usize, /// Amount of additional gas to pay when SUICIDE credits a non-existant account pub suicide_to_new_account_cost: usize, /// If Some(x): let limit = GAS * (x - 1) / x; let CALL's gas = min(requested, limit). let CREATE's gas = limit. /// If None: let CALL's gas = (requested > GAS? [OOG] : GAS). let CREATE's gas = GAS pub sub_gas_cap_divisor: Option<usize>, /// Don't ever make empty accounts; contracts start with nonce=1. Also, don't charge 25k when sending/suicide zero-value. pub no_empty: bool, /// Kill empty accounts if touched. pub kill_empty: bool, } impl Schedule { /// Schedule for the Frontier-era of the Ethereum main net. pub fn new_frontier() -> Schedule { Self::new(false, false, 21000) } /// Schedule for the Homestead-era of the Ethereum main net. pub fn new_homestead() -> Schedule { Self::new(true, true, 53000) } /// Schedule for the post-EIP-150-era of the Ethereum main net. pub fn new_post_eip150(max_code_size: usize, fix_exp: bool, no_empty: bool, kill_empty: bool) -> Schedule { Schedule { exceptional_failed_code_deposit: true, have_delegate_call: true, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], exp_gas: 10, exp_byte_gas: if fix_exp
else { 10 }, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 200, sstore_set_gas: 20000, sstore_reset_gas: 5000, sstore_refund_gas: 15000, jumpdest_gas: 1, log_gas: 375, log_data_gas: 8, log_topic_gas: 375, create_gas: 32000, call_gas: 700, call_stipend: 2300, call_value_transfer_gas: 9000, call_new_account_gas: 25000, suicide_refund_gas: 24000, memory_gas: 3, quad_coeff_div: 512, create_data_gas: 200, create_data_limit: max_code_size, tx_gas: 21000, tx_create_gas: 53000, tx_data_zero_gas: 4, tx_data_non_zero_gas: 68, copy_gas: 3, extcodesize_gas: 700, extcodecopy_base_gas: 700, balance_gas: 400, suicide_gas: 5000, suicide_to_new_account_cost: 25000, sub_gas_cap_divisor: Some(64), no_empty: no_empty, kill_empty: kill_empty, } } fn new(efcd: bool, hdc: bool, tcg: usize) -> Schedule { Schedule { exceptional_failed_code_deposit: efcd, have_delegate_call: hdc, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], exp_gas: 10, exp_byte_gas: 10, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 50, sstore_set_gas: 20000, sstore_reset_gas: 5000, sstore_refund_gas: 15000, jumpdest_gas: 1, log_gas: 375, log_data_gas: 8, log_topic_gas: 375, create_gas: 32000, call_gas: 40, call_stipend: 2300, call_value_transfer_gas: 9000, call_new_account_gas: 25000, suicide_refund_gas: 24000, memory_gas: 3, quad_coeff_div: 512, create_data_gas: 200, create_data_limit: usize::max_value(), tx_gas: 21000, tx_create_gas: tcg, tx_data_zero_gas: 4, tx_data_non_zero_gas: 68, copy_gas: 3, extcodesize_gas: 20, extcodecopy_base_gas: 20, balance_gas: 20, suicide_gas: 0, suicide_to_new_account_cost: 0, sub_gas_cap_divisor: None, no_empty: false, kill_empty: false, } } } #[test] #[cfg(test)] fn schedule_evm_assumptions() { let s1 = Schedule::new_frontier(); let s2 = Schedule::new_homestead(); // To optimize division we assume 2**9 for quad_coeff_div assert_eq!(s1.quad_coeff_div, 512); assert_eq!(s2.quad_coeff_div, 512); }
{ 50 }
conditional_block
schedule.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Cost schedule and other parameterisations for the EVM. /// Definition of the cost schedule and other parameterisations for the EVM. pub struct Schedule { /// Does it support exceptional failed code deposit pub exceptional_failed_code_deposit: bool, /// Does it have a delegate cal pub have_delegate_call: bool, /// VM stack limit pub stack_limit: usize, /// Max number of nested calls/creates pub max_depth: usize, /// Gas prices for instructions in all tiers pub tier_step_gas: [usize; 8], /// Gas price for `EXP` opcode pub exp_gas: usize, /// Additional gas for `EXP` opcode for each byte of exponent pub exp_byte_gas: usize, /// Gas price for `SHA3` opcode pub sha3_gas: usize, /// Additional gas for `SHA3` opcode for each word of hashed memory pub sha3_word_gas: usize, /// Gas price for loading from storage pub sload_gas: usize, /// Gas price for setting new value to storage (`storage==0`, `new!=0`) pub sstore_set_gas: usize, /// Gas price for altering value in storage pub sstore_reset_gas: usize, /// Gas refund for `SSTORE` clearing (when `storage!=0`, `new==0`) pub sstore_refund_gas: usize, /// Gas price for `JUMPDEST` opcode pub jumpdest_gas: usize, /// Gas price for `LOG*` pub log_gas: usize, /// Additional gas for data in `LOG*` pub log_data_gas: usize, /// Additional gas for each topic in `LOG*` pub log_topic_gas: usize, /// Gas price for `CREATE` opcode pub create_gas: usize, /// Gas price for `*CALL*` opcodes pub call_gas: usize, /// Stipend for transfer for `CALL|CALLCODE` opcode when `value>0` pub call_stipend: usize, /// Additional gas required for value transfer (`CALL|CALLCODE`) pub call_value_transfer_gas: usize, /// Additional gas for creating new account (`CALL|CALLCODE`) pub call_new_account_gas: usize, /// Refund for SUICIDE pub suicide_refund_gas: usize, /// Gas for used memory pub memory_gas: usize, /// Coefficient used to convert memory size to gas price for memory pub quad_coeff_div: usize, /// Cost for contract length when executing `CREATE` pub create_data_gas: usize, /// Maximum code size when creating a contract. pub create_data_limit: usize, /// Transaction cost pub tx_gas: usize, /// `CREATE` transaction cost pub tx_create_gas: usize, /// Additional cost for empty data transaction pub tx_data_zero_gas: usize, /// Aditional cost for non-empty data transaction pub tx_data_non_zero_gas: usize, /// Gas price for copying memory pub copy_gas: usize, /// Price of EXTCODESIZE pub extcodesize_gas: usize, /// Base price of EXTCODECOPY pub extcodecopy_base_gas: usize, /// Price of BALANCE pub balance_gas: usize, /// Price of SUICIDE pub suicide_gas: usize, /// Amount of additional gas to pay when SUICIDE credits a non-existant account pub suicide_to_new_account_cost: usize, /// If Some(x): let limit = GAS * (x - 1) / x; let CALL's gas = min(requested, limit). let CREATE's gas = limit. /// If None: let CALL's gas = (requested > GAS? [OOG] : GAS). let CREATE's gas = GAS pub sub_gas_cap_divisor: Option<usize>, /// Don't ever make empty accounts; contracts start with nonce=1. Also, don't charge 25k when sending/suicide zero-value. pub no_empty: bool, /// Kill empty accounts if touched. pub kill_empty: bool, } impl Schedule { /// Schedule for the Frontier-era of the Ethereum main net. pub fn new_frontier() -> Schedule { Self::new(false, false, 21000) } /// Schedule for the Homestead-era of the Ethereum main net. pub fn new_homestead() -> Schedule { Self::new(true, true, 53000) } /// Schedule for the post-EIP-150-era of the Ethereum main net. pub fn new_post_eip150(max_code_size: usize, fix_exp: bool, no_empty: bool, kill_empty: bool) -> Schedule { Schedule { exceptional_failed_code_deposit: true, have_delegate_call: true, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], exp_gas: 10, exp_byte_gas: if fix_exp { 50 } else { 10 }, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 200, sstore_set_gas: 20000, sstore_reset_gas: 5000, sstore_refund_gas: 15000, jumpdest_gas: 1, log_gas: 375, log_data_gas: 8, log_topic_gas: 375, create_gas: 32000, call_gas: 700, call_stipend: 2300, call_value_transfer_gas: 9000, call_new_account_gas: 25000, suicide_refund_gas: 24000, memory_gas: 3, quad_coeff_div: 512,
create_data_gas: 200, create_data_limit: max_code_size, tx_gas: 21000, tx_create_gas: 53000, tx_data_zero_gas: 4, tx_data_non_zero_gas: 68, copy_gas: 3, extcodesize_gas: 700, extcodecopy_base_gas: 700, balance_gas: 400, suicide_gas: 5000, suicide_to_new_account_cost: 25000, sub_gas_cap_divisor: Some(64), no_empty: no_empty, kill_empty: kill_empty, } } fn new(efcd: bool, hdc: bool, tcg: usize) -> Schedule { Schedule { exceptional_failed_code_deposit: efcd, have_delegate_call: hdc, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], exp_gas: 10, exp_byte_gas: 10, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 50, sstore_set_gas: 20000, sstore_reset_gas: 5000, sstore_refund_gas: 15000, jumpdest_gas: 1, log_gas: 375, log_data_gas: 8, log_topic_gas: 375, create_gas: 32000, call_gas: 40, call_stipend: 2300, call_value_transfer_gas: 9000, call_new_account_gas: 25000, suicide_refund_gas: 24000, memory_gas: 3, quad_coeff_div: 512, create_data_gas: 200, create_data_limit: usize::max_value(), tx_gas: 21000, tx_create_gas: tcg, tx_data_zero_gas: 4, tx_data_non_zero_gas: 68, copy_gas: 3, extcodesize_gas: 20, extcodecopy_base_gas: 20, balance_gas: 20, suicide_gas: 0, suicide_to_new_account_cost: 0, sub_gas_cap_divisor: None, no_empty: false, kill_empty: false, } } } #[test] #[cfg(test)] fn schedule_evm_assumptions() { let s1 = Schedule::new_frontier(); let s2 = Schedule::new_homestead(); // To optimize division we assume 2**9 for quad_coeff_div assert_eq!(s1.quad_coeff_div, 512); assert_eq!(s2.quad_coeff_div, 512); }
random_line_split
schedule.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Cost schedule and other parameterisations for the EVM. /// Definition of the cost schedule and other parameterisations for the EVM. pub struct Schedule { /// Does it support exceptional failed code deposit pub exceptional_failed_code_deposit: bool, /// Does it have a delegate cal pub have_delegate_call: bool, /// VM stack limit pub stack_limit: usize, /// Max number of nested calls/creates pub max_depth: usize, /// Gas prices for instructions in all tiers pub tier_step_gas: [usize; 8], /// Gas price for `EXP` opcode pub exp_gas: usize, /// Additional gas for `EXP` opcode for each byte of exponent pub exp_byte_gas: usize, /// Gas price for `SHA3` opcode pub sha3_gas: usize, /// Additional gas for `SHA3` opcode for each word of hashed memory pub sha3_word_gas: usize, /// Gas price for loading from storage pub sload_gas: usize, /// Gas price for setting new value to storage (`storage==0`, `new!=0`) pub sstore_set_gas: usize, /// Gas price for altering value in storage pub sstore_reset_gas: usize, /// Gas refund for `SSTORE` clearing (when `storage!=0`, `new==0`) pub sstore_refund_gas: usize, /// Gas price for `JUMPDEST` opcode pub jumpdest_gas: usize, /// Gas price for `LOG*` pub log_gas: usize, /// Additional gas for data in `LOG*` pub log_data_gas: usize, /// Additional gas for each topic in `LOG*` pub log_topic_gas: usize, /// Gas price for `CREATE` opcode pub create_gas: usize, /// Gas price for `*CALL*` opcodes pub call_gas: usize, /// Stipend for transfer for `CALL|CALLCODE` opcode when `value>0` pub call_stipend: usize, /// Additional gas required for value transfer (`CALL|CALLCODE`) pub call_value_transfer_gas: usize, /// Additional gas for creating new account (`CALL|CALLCODE`) pub call_new_account_gas: usize, /// Refund for SUICIDE pub suicide_refund_gas: usize, /// Gas for used memory pub memory_gas: usize, /// Coefficient used to convert memory size to gas price for memory pub quad_coeff_div: usize, /// Cost for contract length when executing `CREATE` pub create_data_gas: usize, /// Maximum code size when creating a contract. pub create_data_limit: usize, /// Transaction cost pub tx_gas: usize, /// `CREATE` transaction cost pub tx_create_gas: usize, /// Additional cost for empty data transaction pub tx_data_zero_gas: usize, /// Aditional cost for non-empty data transaction pub tx_data_non_zero_gas: usize, /// Gas price for copying memory pub copy_gas: usize, /// Price of EXTCODESIZE pub extcodesize_gas: usize, /// Base price of EXTCODECOPY pub extcodecopy_base_gas: usize, /// Price of BALANCE pub balance_gas: usize, /// Price of SUICIDE pub suicide_gas: usize, /// Amount of additional gas to pay when SUICIDE credits a non-existant account pub suicide_to_new_account_cost: usize, /// If Some(x): let limit = GAS * (x - 1) / x; let CALL's gas = min(requested, limit). let CREATE's gas = limit. /// If None: let CALL's gas = (requested > GAS? [OOG] : GAS). let CREATE's gas = GAS pub sub_gas_cap_divisor: Option<usize>, /// Don't ever make empty accounts; contracts start with nonce=1. Also, don't charge 25k when sending/suicide zero-value. pub no_empty: bool, /// Kill empty accounts if touched. pub kill_empty: bool, } impl Schedule { /// Schedule for the Frontier-era of the Ethereum main net. pub fn
() -> Schedule { Self::new(false, false, 21000) } /// Schedule for the Homestead-era of the Ethereum main net. pub fn new_homestead() -> Schedule { Self::new(true, true, 53000) } /// Schedule for the post-EIP-150-era of the Ethereum main net. pub fn new_post_eip150(max_code_size: usize, fix_exp: bool, no_empty: bool, kill_empty: bool) -> Schedule { Schedule { exceptional_failed_code_deposit: true, have_delegate_call: true, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], exp_gas: 10, exp_byte_gas: if fix_exp { 50 } else { 10 }, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 200, sstore_set_gas: 20000, sstore_reset_gas: 5000, sstore_refund_gas: 15000, jumpdest_gas: 1, log_gas: 375, log_data_gas: 8, log_topic_gas: 375, create_gas: 32000, call_gas: 700, call_stipend: 2300, call_value_transfer_gas: 9000, call_new_account_gas: 25000, suicide_refund_gas: 24000, memory_gas: 3, quad_coeff_div: 512, create_data_gas: 200, create_data_limit: max_code_size, tx_gas: 21000, tx_create_gas: 53000, tx_data_zero_gas: 4, tx_data_non_zero_gas: 68, copy_gas: 3, extcodesize_gas: 700, extcodecopy_base_gas: 700, balance_gas: 400, suicide_gas: 5000, suicide_to_new_account_cost: 25000, sub_gas_cap_divisor: Some(64), no_empty: no_empty, kill_empty: kill_empty, } } fn new(efcd: bool, hdc: bool, tcg: usize) -> Schedule { Schedule { exceptional_failed_code_deposit: efcd, have_delegate_call: hdc, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], exp_gas: 10, exp_byte_gas: 10, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 50, sstore_set_gas: 20000, sstore_reset_gas: 5000, sstore_refund_gas: 15000, jumpdest_gas: 1, log_gas: 375, log_data_gas: 8, log_topic_gas: 375, create_gas: 32000, call_gas: 40, call_stipend: 2300, call_value_transfer_gas: 9000, call_new_account_gas: 25000, suicide_refund_gas: 24000, memory_gas: 3, quad_coeff_div: 512, create_data_gas: 200, create_data_limit: usize::max_value(), tx_gas: 21000, tx_create_gas: tcg, tx_data_zero_gas: 4, tx_data_non_zero_gas: 68, copy_gas: 3, extcodesize_gas: 20, extcodecopy_base_gas: 20, balance_gas: 20, suicide_gas: 0, suicide_to_new_account_cost: 0, sub_gas_cap_divisor: None, no_empty: false, kill_empty: false, } } } #[test] #[cfg(test)] fn schedule_evm_assumptions() { let s1 = Schedule::new_frontier(); let s2 = Schedule::new_homestead(); // To optimize division we assume 2**9 for quad_coeff_div assert_eq!(s1.quad_coeff_div, 512); assert_eq!(s2.quad_coeff_div, 512); }
new_frontier
identifier_name
schedule.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Cost schedule and other parameterisations for the EVM. /// Definition of the cost schedule and other parameterisations for the EVM. pub struct Schedule { /// Does it support exceptional failed code deposit pub exceptional_failed_code_deposit: bool, /// Does it have a delegate cal pub have_delegate_call: bool, /// VM stack limit pub stack_limit: usize, /// Max number of nested calls/creates pub max_depth: usize, /// Gas prices for instructions in all tiers pub tier_step_gas: [usize; 8], /// Gas price for `EXP` opcode pub exp_gas: usize, /// Additional gas for `EXP` opcode for each byte of exponent pub exp_byte_gas: usize, /// Gas price for `SHA3` opcode pub sha3_gas: usize, /// Additional gas for `SHA3` opcode for each word of hashed memory pub sha3_word_gas: usize, /// Gas price for loading from storage pub sload_gas: usize, /// Gas price for setting new value to storage (`storage==0`, `new!=0`) pub sstore_set_gas: usize, /// Gas price for altering value in storage pub sstore_reset_gas: usize, /// Gas refund for `SSTORE` clearing (when `storage!=0`, `new==0`) pub sstore_refund_gas: usize, /// Gas price for `JUMPDEST` opcode pub jumpdest_gas: usize, /// Gas price for `LOG*` pub log_gas: usize, /// Additional gas for data in `LOG*` pub log_data_gas: usize, /// Additional gas for each topic in `LOG*` pub log_topic_gas: usize, /// Gas price for `CREATE` opcode pub create_gas: usize, /// Gas price for `*CALL*` opcodes pub call_gas: usize, /// Stipend for transfer for `CALL|CALLCODE` opcode when `value>0` pub call_stipend: usize, /// Additional gas required for value transfer (`CALL|CALLCODE`) pub call_value_transfer_gas: usize, /// Additional gas for creating new account (`CALL|CALLCODE`) pub call_new_account_gas: usize, /// Refund for SUICIDE pub suicide_refund_gas: usize, /// Gas for used memory pub memory_gas: usize, /// Coefficient used to convert memory size to gas price for memory pub quad_coeff_div: usize, /// Cost for contract length when executing `CREATE` pub create_data_gas: usize, /// Maximum code size when creating a contract. pub create_data_limit: usize, /// Transaction cost pub tx_gas: usize, /// `CREATE` transaction cost pub tx_create_gas: usize, /// Additional cost for empty data transaction pub tx_data_zero_gas: usize, /// Aditional cost for non-empty data transaction pub tx_data_non_zero_gas: usize, /// Gas price for copying memory pub copy_gas: usize, /// Price of EXTCODESIZE pub extcodesize_gas: usize, /// Base price of EXTCODECOPY pub extcodecopy_base_gas: usize, /// Price of BALANCE pub balance_gas: usize, /// Price of SUICIDE pub suicide_gas: usize, /// Amount of additional gas to pay when SUICIDE credits a non-existant account pub suicide_to_new_account_cost: usize, /// If Some(x): let limit = GAS * (x - 1) / x; let CALL's gas = min(requested, limit). let CREATE's gas = limit. /// If None: let CALL's gas = (requested > GAS? [OOG] : GAS). let CREATE's gas = GAS pub sub_gas_cap_divisor: Option<usize>, /// Don't ever make empty accounts; contracts start with nonce=1. Also, don't charge 25k when sending/suicide zero-value. pub no_empty: bool, /// Kill empty accounts if touched. pub kill_empty: bool, } impl Schedule { /// Schedule for the Frontier-era of the Ethereum main net. pub fn new_frontier() -> Schedule { Self::new(false, false, 21000) } /// Schedule for the Homestead-era of the Ethereum main net. pub fn new_homestead() -> Schedule { Self::new(true, true, 53000) } /// Schedule for the post-EIP-150-era of the Ethereum main net. pub fn new_post_eip150(max_code_size: usize, fix_exp: bool, no_empty: bool, kill_empty: bool) -> Schedule
call_gas: 700, call_stipend: 2300, call_value_transfer_gas: 9000, call_new_account_gas: 25000, suicide_refund_gas: 24000, memory_gas: 3, quad_coeff_div: 512, create_data_gas: 200, create_data_limit: max_code_size, tx_gas: 21000, tx_create_gas: 53000, tx_data_zero_gas: 4, tx_data_non_zero_gas: 68, copy_gas: 3, extcodesize_gas: 700, extcodecopy_base_gas: 700, balance_gas: 400, suicide_gas: 5000, suicide_to_new_account_cost: 25000, sub_gas_cap_divisor: Some(64), no_empty: no_empty, kill_empty: kill_empty, } } fn new(efcd: bool, hdc: bool, tcg: usize) -> Schedule { Schedule { exceptional_failed_code_deposit: efcd, have_delegate_call: hdc, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], exp_gas: 10, exp_byte_gas: 10, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 50, sstore_set_gas: 20000, sstore_reset_gas: 5000, sstore_refund_gas: 15000, jumpdest_gas: 1, log_gas: 375, log_data_gas: 8, log_topic_gas: 375, create_gas: 32000, call_gas: 40, call_stipend: 2300, call_value_transfer_gas: 9000, call_new_account_gas: 25000, suicide_refund_gas: 24000, memory_gas: 3, quad_coeff_div: 512, create_data_gas: 200, create_data_limit: usize::max_value(), tx_gas: 21000, tx_create_gas: tcg, tx_data_zero_gas: 4, tx_data_non_zero_gas: 68, copy_gas: 3, extcodesize_gas: 20, extcodecopy_base_gas: 20, balance_gas: 20, suicide_gas: 0, suicide_to_new_account_cost: 0, sub_gas_cap_divisor: None, no_empty: false, kill_empty: false, } } } #[test] #[cfg(test)] fn schedule_evm_assumptions() { let s1 = Schedule::new_frontier(); let s2 = Schedule::new_homestead(); // To optimize division we assume 2**9 for quad_coeff_div assert_eq!(s1.quad_coeff_div, 512); assert_eq!(s2.quad_coeff_div, 512); }
{ Schedule { exceptional_failed_code_deposit: true, have_delegate_call: true, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], exp_gas: 10, exp_byte_gas: if fix_exp { 50 } else { 10 }, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 200, sstore_set_gas: 20000, sstore_reset_gas: 5000, sstore_refund_gas: 15000, jumpdest_gas: 1, log_gas: 375, log_data_gas: 8, log_topic_gas: 375, create_gas: 32000,
identifier_body
stats.rs
// rpc-perf - RPC Performance Testing // Copyright 2015 Twitter, Inc // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or 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. #[derive(Clone)] pub enum Status { Error, Hit, Miss, Ok, Closed, } #[derive(Clone)] pub struct
{ pub start: u64, pub stop: u64, pub status: Status, }
Stat
identifier_name
stats.rs
// rpc-perf - RPC Performance Testing // Copyright 2015 Twitter, Inc // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or 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.
Hit, Miss, Ok, Closed, } #[derive(Clone)] pub struct Stat { pub start: u64, pub stop: u64, pub status: Status, }
#[derive(Clone)] pub enum Status { Error,
random_line_split
bench.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_snake_case_functions)] use std::rand::{Rng, task_rng}; use stdtest::Bencher; use regex::{Regex, NoExpand}; fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) { b.iter(|| if!re.is_match(text) { fail!("no match") }); } #[bench] fn no_exponential(b: &mut Bencher) { let n = 100; let re = Regex::new(format!("{}{}", "a?".repeat(n), "a".repeat(n)).as_slice()).unwrap(); let text = "a".repeat(n); bench_assert_match(b, re, text.as_slice()); } #[bench] fn literal(b: &mut Bencher) { let re = regex!("y"); let text = format!("{}y", "x".repeat(50)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn not_literal(b: &mut Bencher) { let re = regex!(".y"); let text = format!("{}y", "x".repeat(50)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn match_class(b: &mut Bencher) { let re = regex!("[abcdw]"); let text = format!("{}w", "xxxx".repeat(20)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn match_class_in_range(b: &mut Bencher) { // 'b' is between 'a' and 'c', so the class range checking doesn't help. let re = regex!("[ac]"); let text = format!("{}c", "bbbb".repeat(20)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn replace_all(b: &mut Bencher) { let re = regex!("[cjrw]"); let text = "abcdefghijklmnopqrstuvwxyz"; // FIXME: This isn't using the $name expand stuff. // It's possible RE2/Go is using it, but currently, the expand in this // crate is actually compiling a regex, so it's incredibly slow. b.iter(|| re.replace_all(text, NoExpand(""))); } #[bench] fn anchored_literal_short_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text.as_slice())); } #[bench] fn anchored_literal_short_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text.as_slice())); } #[bench] fn one_pass_short_a(b: &mut Bencher) { let re = regex!("^.bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a_not(b: &mut Bencher) { let re = regex!(".bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b(b: &mut Bencher)
#[bench] fn one_pass_short_b_not(b: &mut Bencher) { let re = regex!(".bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix(b: &mut Bencher) { let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix_not(b: &mut Bencher) { let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } macro_rules! throughput( ($name:ident, $regex:expr, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let text = gen_text($size); b.bytes = $size; b.iter(|| if $regex.is_match(text.as_slice()) { fail!("match") }); } ); ) fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") } fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn gen_text(n: uint) -> String { let mut rng = task_rng(); let mut bytes = rng.gen_ascii_chars().map(|n| n as u8).take(n) .collect::<Vec<u8>>(); for (i, b) in bytes.mut_iter().enumerate() { if i % 20 == 0 { *b = '\n' as u8 } } String::from_utf8(bytes).unwrap() } throughput!(easy0_32, easy0(), 32) throughput!(easy0_1K, easy0(), 1<<10) throughput!(easy0_32K, easy0(), 32<<10) throughput!(easy1_32, easy1(), 32) throughput!(easy1_1K, easy1(), 1<<10) throughput!(easy1_32K, easy1(), 32<<10) throughput!(medium_32, medium(), 32) throughput!(medium_1K, medium(), 1<<10) throughput!(medium_32K,medium(), 32<<10) throughput!(hard_32, hard(), 32) throughput!(hard_1K, hard(), 1<<10) throughput!(hard_32K,hard(), 32<<10)
{ let re = regex!("^.bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); }
identifier_body
bench.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_snake_case_functions)] use std::rand::{Rng, task_rng}; use stdtest::Bencher; use regex::{Regex, NoExpand}; fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) { b.iter(|| if!re.is_match(text) { fail!("no match") }); } #[bench] fn no_exponential(b: &mut Bencher) { let n = 100; let re = Regex::new(format!("{}{}", "a?".repeat(n), "a".repeat(n)).as_slice()).unwrap(); let text = "a".repeat(n); bench_assert_match(b, re, text.as_slice()); } #[bench] fn literal(b: &mut Bencher) { let re = regex!("y"); let text = format!("{}y", "x".repeat(50)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn not_literal(b: &mut Bencher) { let re = regex!(".y"); let text = format!("{}y", "x".repeat(50)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn match_class(b: &mut Bencher) { let re = regex!("[abcdw]"); let text = format!("{}w", "xxxx".repeat(20)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn match_class_in_range(b: &mut Bencher) { // 'b' is between 'a' and 'c', so the class range checking doesn't help. let re = regex!("[ac]"); let text = format!("{}c", "bbbb".repeat(20)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn replace_all(b: &mut Bencher) { let re = regex!("[cjrw]"); let text = "abcdefghijklmnopqrstuvwxyz"; // FIXME: This isn't using the $name expand stuff. // It's possible RE2/Go is using it, but currently, the expand in this // crate is actually compiling a regex, so it's incredibly slow. b.iter(|| re.replace_all(text, NoExpand(""))); } #[bench] fn anchored_literal_short_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text.as_slice())); } #[bench] fn anchored_literal_short_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text.as_slice())); } #[bench] fn one_pass_short_a(b: &mut Bencher) { let re = regex!("^.bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a_not(b: &mut Bencher) { let re = regex!(".bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b(b: &mut Bencher) { let re = regex!("^.bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b_not(b: &mut Bencher) { let re = regex!(".bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix(b: &mut Bencher) { let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix_not(b: &mut Bencher) { let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } macro_rules! throughput( ($name:ident, $regex:expr, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let text = gen_text($size); b.bytes = $size; b.iter(|| if $regex.is_match(text.as_slice()) { fail!("match") }); } ); ) fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") } fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn
(n: uint) -> String { let mut rng = task_rng(); let mut bytes = rng.gen_ascii_chars().map(|n| n as u8).take(n) .collect::<Vec<u8>>(); for (i, b) in bytes.mut_iter().enumerate() { if i % 20 == 0 { *b = '\n' as u8 } } String::from_utf8(bytes).unwrap() } throughput!(easy0_32, easy0(), 32) throughput!(easy0_1K, easy0(), 1<<10) throughput!(easy0_32K, easy0(), 32<<10) throughput!(easy1_32, easy1(), 32) throughput!(easy1_1K, easy1(), 1<<10) throughput!(easy1_32K, easy1(), 32<<10) throughput!(medium_32, medium(), 32) throughput!(medium_1K, medium(), 1<<10) throughput!(medium_32K,medium(), 32<<10) throughput!(hard_32, hard(), 32) throughput!(hard_1K, hard(), 1<<10) throughput!(hard_32K,hard(), 32<<10)
gen_text
identifier_name
bench.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_snake_case_functions)] use std::rand::{Rng, task_rng}; use stdtest::Bencher; use regex::{Regex, NoExpand}; fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) { b.iter(|| if!re.is_match(text) { fail!("no match") }); } #[bench] fn no_exponential(b: &mut Bencher) { let n = 100; let re = Regex::new(format!("{}{}", "a?".repeat(n), "a".repeat(n)).as_slice()).unwrap(); let text = "a".repeat(n); bench_assert_match(b, re, text.as_slice()); } #[bench] fn literal(b: &mut Bencher) { let re = regex!("y"); let text = format!("{}y", "x".repeat(50)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn not_literal(b: &mut Bencher) { let re = regex!(".y"); let text = format!("{}y", "x".repeat(50)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn match_class(b: &mut Bencher) { let re = regex!("[abcdw]"); let text = format!("{}w", "xxxx".repeat(20)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn match_class_in_range(b: &mut Bencher) { // 'b' is between 'a' and 'c', so the class range checking doesn't help. let re = regex!("[ac]"); let text = format!("{}c", "bbbb".repeat(20)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn replace_all(b: &mut Bencher) { let re = regex!("[cjrw]"); let text = "abcdefghijklmnopqrstuvwxyz"; // FIXME: This isn't using the $name expand stuff. // It's possible RE2/Go is using it, but currently, the expand in this // crate is actually compiling a regex, so it's incredibly slow. b.iter(|| re.replace_all(text, NoExpand(""))); } #[bench] fn anchored_literal_short_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text.as_slice())); } #[bench] fn anchored_literal_short_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text.as_slice())); } #[bench] fn one_pass_short_a(b: &mut Bencher) { let re = regex!("^.bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a_not(b: &mut Bencher) { let re = regex!(".bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b(b: &mut Bencher) { let re = regex!("^.bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b_not(b: &mut Bencher) { let re = regex!(".bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix(b: &mut Bencher) { let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix_not(b: &mut Bencher) { let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } macro_rules! throughput( ($name:ident, $regex:expr, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let text = gen_text($size); b.bytes = $size; b.iter(|| if $regex.is_match(text.as_slice()) { fail!("match") }); } ); ) fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") } fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn gen_text(n: uint) -> String { let mut rng = task_rng(); let mut bytes = rng.gen_ascii_chars().map(|n| n as u8).take(n) .collect::<Vec<u8>>(); for (i, b) in bytes.mut_iter().enumerate() { if i % 20 == 0
} String::from_utf8(bytes).unwrap() } throughput!(easy0_32, easy0(), 32) throughput!(easy0_1K, easy0(), 1<<10) throughput!(easy0_32K, easy0(), 32<<10) throughput!(easy1_32, easy1(), 32) throughput!(easy1_1K, easy1(), 1<<10) throughput!(easy1_32K, easy1(), 32<<10) throughput!(medium_32, medium(), 32) throughput!(medium_1K, medium(), 1<<10) throughput!(medium_32K,medium(), 32<<10) throughput!(hard_32, hard(), 32) throughput!(hard_1K, hard(), 1<<10) throughput!(hard_32K,hard(), 32<<10)
{ *b = '\n' as u8 }
conditional_block
bench.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_snake_case_functions)] use std::rand::{Rng, task_rng}; use stdtest::Bencher; use regex::{Regex, NoExpand}; fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) { b.iter(|| if!re.is_match(text) { fail!("no match") }); } #[bench] fn no_exponential(b: &mut Bencher) { let n = 100; let re = Regex::new(format!("{}{}", "a?".repeat(n), "a".repeat(n)).as_slice()).unwrap(); let text = "a".repeat(n); bench_assert_match(b, re, text.as_slice()); } #[bench] fn literal(b: &mut Bencher) { let re = regex!("y"); let text = format!("{}y", "x".repeat(50)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn not_literal(b: &mut Bencher) { let re = regex!(".y"); let text = format!("{}y", "x".repeat(50)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn match_class(b: &mut Bencher) { let re = regex!("[abcdw]"); let text = format!("{}w", "xxxx".repeat(20)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn match_class_in_range(b: &mut Bencher) { // 'b' is between 'a' and 'c', so the class range checking doesn't help. let re = regex!("[ac]"); let text = format!("{}c", "bbbb".repeat(20)); bench_assert_match(b, re, text.as_slice()); } #[bench] fn replace_all(b: &mut Bencher) { let re = regex!("[cjrw]"); let text = "abcdefghijklmnopqrstuvwxyz"; // FIXME: This isn't using the $name expand stuff. // It's possible RE2/Go is using it, but currently, the expand in this // crate is actually compiling a regex, so it's incredibly slow. b.iter(|| re.replace_all(text, NoExpand(""))); } #[bench] fn anchored_literal_short_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text.as_slice())); } #[bench] fn anchored_literal_short_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn anchored_literal_long_match(b: &mut Bencher) {
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); b.iter(|| re.is_match(text.as_slice())); } #[bench] fn one_pass_short_a(b: &mut Bencher) { let re = regex!("^.bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_a_not(b: &mut Bencher) { let re = regex!(".bc(d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b(b: &mut Bencher) { let re = regex!("^.bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_short_b_not(b: &mut Bencher) { let re = regex!(".bc(?:d|e)*$"); let text = "abcddddddeeeededd"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix(b: &mut Bencher) { let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } #[bench] fn one_pass_long_prefix_not(b: &mut Bencher) { let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$"); let text = "abcdefghijklmnopqrstuvwxyz"; b.iter(|| re.is_match(text)); } macro_rules! throughput( ($name:ident, $regex:expr, $size:expr) => ( #[bench] fn $name(b: &mut Bencher) { let text = gen_text($size); b.bytes = $size; b.iter(|| if $regex.is_match(text.as_slice()) { fail!("match") }); } ); ) fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") } fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } fn gen_text(n: uint) -> String { let mut rng = task_rng(); let mut bytes = rng.gen_ascii_chars().map(|n| n as u8).take(n) .collect::<Vec<u8>>(); for (i, b) in bytes.mut_iter().enumerate() { if i % 20 == 0 { *b = '\n' as u8 } } String::from_utf8(bytes).unwrap() } throughput!(easy0_32, easy0(), 32) throughput!(easy0_1K, easy0(), 1<<10) throughput!(easy0_32K, easy0(), 32<<10) throughput!(easy1_32, easy1(), 32) throughput!(easy1_1K, easy1(), 1<<10) throughput!(easy1_32K, easy1(), 32<<10) throughput!(medium_32, medium(), 32) throughput!(medium_1K, medium(), 1<<10) throughput!(medium_32K,medium(), 32<<10) throughput!(hard_32, hard(), 32) throughput!(hard_1K, hard(), 1<<10) throughput!(hard_32K,hard(), 32<<10)
let re = regex!("^.bc(d|e)");
random_line_split
macro.rs
#[macro_use] extern crate double; // Traits which only return types that implement `Default`. trait Calculator: Clone { fn multiply(&self, x: i32, y: i32) -> i32; } trait BalanceSheet: Clone { fn profit(&self, revenue: u32, costs: u32) -> i32; fn loss(&self, revenue: u32, costs: u32) -> i32; } trait Greeter: Clone { fn greet<S: AsRef<str>>(&mut self, name: S); } mock_trait!(EmptyMock); mock_trait!( MockCalculator, multiply(i32, i32) -> i32); impl Calculator for MockCalculator { mock_method!(multiply(&self, x: i32, y: i32) -> i32); } mock_trait!( MockBalanceSheet, profit(u32, u32) -> i32, loss(u32, u32) -> i32); impl BalanceSheet for MockBalanceSheet { mock_method!(profit(&self, revenue: u32, costs: u32) -> i32); mock_method!(loss(&self, revenue: u32, costs: u32) -> i32); } mock_trait!( MockGreeter, greet(String) -> ()); impl Greeter for MockGreeter { mock_method!(greet<(S: AsRef<str>)>(&mut self, name: S), self, { self.greet.call(name.as_ref().to_string()); }); } // Traits which return types that do not implement `Default`. #[derive(Debug, Clone, PartialEq)] pub struct User { name: String } pub trait UserStore { fn get_user(&self, id: i32) -> Result<User, String>; fn delete_user(&self, id: i32) -> Result<(), String>; }
get_user(i32) -> Result<User, String>, delete_user(i32) -> Result<(), String>); impl UserStore for MockUserStore { mock_method!(get_user(&self, id: i32) -> Result<User, String>); mock_method!(delete_user(&self, id: i32) -> Result<(), String>); } fn main() { // Test individual return values let mock = MockBalanceSheet::default(); mock.profit.return_value(42); mock.profit.return_value_for((0, 0), 9001); let value = mock.profit(10, 20); assert_eq!(42, value); mock.profit.has_calls_exactly_in_order(vec!((10, 20))); let value = mock.profit(0, 0); assert_eq!(9001, value); mock.profit.has_calls_exactly_in_order(vec!((10, 20), (0, 0))); // Test sequence of return values mock.profit.return_values(vec!(1, 2, 3)); assert_eq!(1, mock.profit.call((1, 2))); assert_eq!(2, mock.profit.call((2, 4))); assert_eq!(3, mock.profit.call((3, 6))); assert_eq!(42, mock.profit.call((4, 8))); // Test using mocks that do not implement the `Default` trait. // One must manually specify the default values for all methods in the // mocked trait. let store = MockUserStore::new( Err("cannot get, no user with given ID".to_owned()), Err("cannot delete, no user with given ID".to_owned())); store.get_user.return_value_for( 42, Ok(User{ name: "Donald".to_owned() })); assert_eq!( Err("cannot get, no user with given ID".to_owned()), store.get_user(10)); assert_eq!( Ok(User{ name: "Donald".to_owned() }), store.get_user(42)); store.delete_user.return_value_for(42, Ok(())); assert_eq!( Err("cannot delete, no user with given ID".to_owned()), store.delete_user(10)); assert_eq!(Ok(()), store.delete_user(42)); }
mock_trait_no_default!( MockUserStore,
random_line_split
macro.rs
#[macro_use] extern crate double; // Traits which only return types that implement `Default`. trait Calculator: Clone { fn multiply(&self, x: i32, y: i32) -> i32; } trait BalanceSheet: Clone { fn profit(&self, revenue: u32, costs: u32) -> i32; fn loss(&self, revenue: u32, costs: u32) -> i32; } trait Greeter: Clone { fn greet<S: AsRef<str>>(&mut self, name: S); } mock_trait!(EmptyMock); mock_trait!( MockCalculator, multiply(i32, i32) -> i32); impl Calculator for MockCalculator { mock_method!(multiply(&self, x: i32, y: i32) -> i32); } mock_trait!( MockBalanceSheet, profit(u32, u32) -> i32, loss(u32, u32) -> i32); impl BalanceSheet for MockBalanceSheet { mock_method!(profit(&self, revenue: u32, costs: u32) -> i32); mock_method!(loss(&self, revenue: u32, costs: u32) -> i32); } mock_trait!( MockGreeter, greet(String) -> ()); impl Greeter for MockGreeter { mock_method!(greet<(S: AsRef<str>)>(&mut self, name: S), self, { self.greet.call(name.as_ref().to_string()); }); } // Traits which return types that do not implement `Default`. #[derive(Debug, Clone, PartialEq)] pub struct User { name: String } pub trait UserStore { fn get_user(&self, id: i32) -> Result<User, String>; fn delete_user(&self, id: i32) -> Result<(), String>; } mock_trait_no_default!( MockUserStore, get_user(i32) -> Result<User, String>, delete_user(i32) -> Result<(), String>); impl UserStore for MockUserStore { mock_method!(get_user(&self, id: i32) -> Result<User, String>); mock_method!(delete_user(&self, id: i32) -> Result<(), String>); } fn
() { // Test individual return values let mock = MockBalanceSheet::default(); mock.profit.return_value(42); mock.profit.return_value_for((0, 0), 9001); let value = mock.profit(10, 20); assert_eq!(42, value); mock.profit.has_calls_exactly_in_order(vec!((10, 20))); let value = mock.profit(0, 0); assert_eq!(9001, value); mock.profit.has_calls_exactly_in_order(vec!((10, 20), (0, 0))); // Test sequence of return values mock.profit.return_values(vec!(1, 2, 3)); assert_eq!(1, mock.profit.call((1, 2))); assert_eq!(2, mock.profit.call((2, 4))); assert_eq!(3, mock.profit.call((3, 6))); assert_eq!(42, mock.profit.call((4, 8))); // Test using mocks that do not implement the `Default` trait. // One must manually specify the default values for all methods in the // mocked trait. let store = MockUserStore::new( Err("cannot get, no user with given ID".to_owned()), Err("cannot delete, no user with given ID".to_owned())); store.get_user.return_value_for( 42, Ok(User{ name: "Donald".to_owned() })); assert_eq!( Err("cannot get, no user with given ID".to_owned()), store.get_user(10)); assert_eq!( Ok(User{ name: "Donald".to_owned() }), store.get_user(42)); store.delete_user.return_value_for(42, Ok(())); assert_eq!( Err("cannot delete, no user with given ID".to_owned()), store.delete_user(10)); assert_eq!(Ok(()), store.delete_user(42)); }
main
identifier_name
signal_handler.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use libc::{ c_int, c_void, siginfo_t, SIGBUS, SIGHUP, SIGILL, SIGPIPE, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ, }; use crate::{ExitCode, FC_EXIT_CODE_UNEXPECTED_ERROR}; use logger::{error, IncMetric, StoreMetric, METRICS}; use utils::signal::register_signal_handler; // The offset of `si_syscall` (offending syscall identifier) within the siginfo structure // expressed as an `(u)int*`. // Offset `6` for an `i32` field means that the needed information is located at `6 * sizeof(i32)`. // See /usr/include/linux/signal.h for the C struct definition. // See https://github.com/rust-lang/libc/issues/716 for why the offset is different in Rust. const SI_OFF_SYSCALL: isize = 6; const SYS_SECCOMP_CODE: i32 = 1; #[inline] fn exit_with_code(exit_code: ExitCode) { // Write the metrics before exiting. if let Err(e) = METRICS.write() { error!("Failed to write metrics while stopping: {}", e); } // Safe because we're terminating the process anyway. unsafe { libc::_exit(exit_code) }; } macro_rules! generate_handler { ($fn_name:ident,$signal_name:ident, $exit_code:ident, $signal_metric:expr, $body:ident) => { #[inline(always)] extern "C" fn $fn_name(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) { // Safe because we're just reading some fields from a supposedly valid argument. let si_signo = unsafe { (*info).si_signo }; let si_code = unsafe { (*info).si_code }; if num!= si_signo || num!= $signal_name { exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR); } $signal_metric.store(1); error!( "Shutting down VM after intercepting signal {}, code {}.", si_signo, si_code ); $body(si_code, info); #[cfg(not(test))] match si_signo { $signal_name => exit_with_code(crate::$exit_code), _ => exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR), }; } }; } fn log_sigsys_err(si_code: c_int, info: *mut siginfo_t) { if si_code!= SYS_SECCOMP_CODE as i32 { // We received a SIGSYS for a reason other than `bad syscall`. exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR); } // Other signals which might do async unsafe things incompatible with the rest of this // function are blocked due to the sa_mask used when registering the signal handler. let syscall = unsafe { *(info as *const i32).offset(SI_OFF_SYSCALL) as usize }; error!( "Shutting down VM after intercepting a bad syscall ({}).", syscall ); } fn empty_fn(_si_code: c_int, _info: *mut siginfo_t) {} generate_handler!( sigxfsz_handler, SIGXFSZ, FC_EXIT_CODE_SIGXFSZ, METRICS.signals.sigxfsz, empty_fn ); generate_handler!( sigxcpu_handler, SIGXCPU, FC_EXIT_CODE_SIGXCPU, METRICS.signals.sigxcpu, empty_fn ); generate_handler!( sigbus_handler, SIGBUS, FC_EXIT_CODE_SIGBUS, METRICS.signals.sigbus, empty_fn ); generate_handler!( sigsegv_handler, SIGSEGV, FC_EXIT_CODE_SIGSEGV, METRICS.signals.sigsegv, empty_fn ); generate_handler!( sigsys_handler, SIGSYS, FC_EXIT_CODE_BAD_SYSCALL, METRICS.seccomp.num_faults, log_sigsys_err ); generate_handler!( sighup_handler, SIGHUP, FC_EXIT_CODE_SIGHUP, METRICS.signals.sighup, empty_fn ); generate_handler!( sigill_handler, SIGILL, FC_EXIT_CODE_SIGILL, METRICS.signals.sigill, empty_fn ); #[inline(always)] extern "C" fn sigpipe_handler(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) { // Just record the metric and allow the process to continue, the EPIPE error needs // to be handled at caller level. // Safe because we're just reading some fields from a supposedly valid argument. let si_signo = unsafe { (*info).si_signo }; let si_code = unsafe { (*info).si_code }; if num!= si_signo || num!= SIGPIPE { error!("Received invalid signal {}, code {}.", si_signo, si_code); return; } METRICS.signals.sigpipe.inc(); error!("Received signal {}, code {}.", si_signo, si_code); } /// Registers all the required signal handlers. /// /// Custom handlers are installed for: `SIGBUS`, `SIGSEGV`, `SIGSYS` /// `SIGXFSZ` `SIGXCPU` `SIGPIPE` `SIGHUP` and `SIGILL`. pub fn register_signal_handlers() -> utils::errno::Result<()> { // Call to unsafe register_signal_handler which is considered unsafe because it will // register a signal handler which will be called in the current thread and will interrupt // whatever work is done on the current thread, so we have to keep in mind that the registered // signal handler must only do async-signal-safe operations. register_signal_handler(SIGSYS, sigsys_handler)?; register_signal_handler(SIGBUS, sigbus_handler)?; register_signal_handler(SIGSEGV, sigsegv_handler)?; register_signal_handler(SIGXFSZ, sigxfsz_handler)?; register_signal_handler(SIGXCPU, sigxcpu_handler)?; register_signal_handler(SIGPIPE, sigpipe_handler)?; register_signal_handler(SIGHUP, sighup_handler)?; register_signal_handler(SIGILL, sigill_handler)?; Ok(()) } #[cfg(test)] mod tests { use super::*; use libc::{cpu_set_t, syscall}; use std::{mem, process, thread}; use seccompiler::sock_filter; // This function is used when running unit tests, so all the unsafes are safe. fn cpu_count() -> usize { let mut cpuset: cpu_set_t = unsafe { mem::zeroed() }; unsafe { libc::CPU_ZERO(&mut cpuset); } let ret = unsafe { libc::sched_getaffinity( 0, mem::size_of::<cpu_set_t>(), &mut cpuset as *mut cpu_set_t, ) }; assert_eq!(ret, 0); let mut num = 0; for i in 0..libc::CPU_SETSIZE as usize { if unsafe { libc::CPU_ISSET(i, &cpuset) } { num += 1; } } num } #[test] fn test_signal_handler()
unsafe { syscall(libc::SYS_kill, process::id(), SIGSEGV); } // Call SIGXFSZ signal handler. assert_eq!(METRICS.signals.sigxfsz.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGXFSZ); } // Call SIGXCPU signal handler. assert_eq!(METRICS.signals.sigxcpu.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGXCPU); } // Call SIGPIPE signal handler. assert_eq!(METRICS.signals.sigpipe.count(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGPIPE); } // Call SIGHUP signal handler. assert_eq!(METRICS.signals.sighup.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGHUP); } // Call SIGILL signal handler. assert_eq!(METRICS.signals.sigill.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGILL); } }); assert!(child.join().is_ok()); // Sanity check. assert!(cpu_count() > 0); // Kcov somehow messes with our handler getting the SIGSYS signal when a bad syscall // is caught, so the following assertion no longer holds. Ideally, we'd have a surefire // way of either preventing this behaviour, or detecting for certain whether this test is // run by kcov or not. The best we could do so far is to look at the perceived number of // available CPUs. Kcov seems to make a single CPU available to the process running the // tests, so we use this as an heuristic to decide if we check the assertion. if cpu_count() > 1 { // The signal handler should let the program continue during unit tests. assert!(METRICS.seccomp.num_faults.fetch() >= 1); } assert!(METRICS.signals.sigbus.fetch() >= 1); assert!(METRICS.signals.sigsegv.fetch() >= 1); assert!(METRICS.signals.sigxfsz.fetch() >= 1); assert!(METRICS.signals.sigxcpu.fetch() >= 1); assert!(METRICS.signals.sigpipe.count() >= 1); assert!(METRICS.signals.sighup.fetch() >= 1); // Workaround to GitHub issue 2216. #[cfg(not(target_arch = "aarch64"))] assert!(METRICS.signals.sigill.fetch() >= 1); } fn make_test_seccomp_bpf_filter() -> Vec<sock_filter> { // Create seccomp filter that allows all syscalls, except for `SYS_mkdirat`. // For some reason, directly calling `SYS_kill` with SIGSYS, like we do with the // other signals, results in an error. Probably because of the way `cargo test` is // handling signals. #[cfg(target_arch = "aarch64")] #[allow(clippy::unreadable_literal)] let bpf_filter = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, sock_filter { code: 21, jt: 1, jf: 0, k: 3221225655, }, sock_filter { code: 6, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 21, jt: 0, jf: 1, k: 34, }, sock_filter { code: 5, jt: 0, jf: 0, k: 1, }, sock_filter { code: 5, jt: 0, jf: 0, k: 2, }, sock_filter { code: 6, jt: 0, jf: 0, k: 196608, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, ]; #[cfg(target_arch = "x86_64")] #[allow(clippy::unreadable_literal)] let bpf_filter = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, sock_filter { code: 21, jt: 1, jf: 0, k: 3221225534, }, sock_filter { code: 6, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 21, jt: 0, jf: 1, k: 258, }, sock_filter { code: 5, jt: 0, jf: 0, k: 1, }, sock_filter { code: 5, jt: 0, jf: 0, k: 2, }, sock_filter { code: 6, jt: 0, jf: 0, k: 196608, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, ]; bpf_filter } }
{ let child = thread::spawn(move || { assert!(register_signal_handlers().is_ok()); let filter = make_test_seccomp_bpf_filter(); assert!(seccompiler::apply_filter(&filter).is_ok()); assert_eq!(METRICS.seccomp.num_faults.fetch(), 0); // Call the forbidden `SYS_mkdirat`. unsafe { libc::syscall(libc::SYS_mkdirat, "/foo/bar\0") }; // Call SIGBUS signal handler. assert_eq!(METRICS.signals.sigbus.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGBUS); } // Call SIGSEGV signal handler. assert_eq!(METRICS.signals.sigsegv.fetch(), 0);
identifier_body
signal_handler.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use libc::{ c_int, c_void, siginfo_t, SIGBUS, SIGHUP, SIGILL, SIGPIPE, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ, }; use crate::{ExitCode, FC_EXIT_CODE_UNEXPECTED_ERROR}; use logger::{error, IncMetric, StoreMetric, METRICS}; use utils::signal::register_signal_handler; // The offset of `si_syscall` (offending syscall identifier) within the siginfo structure // expressed as an `(u)int*`. // Offset `6` for an `i32` field means that the needed information is located at `6 * sizeof(i32)`. // See /usr/include/linux/signal.h for the C struct definition. // See https://github.com/rust-lang/libc/issues/716 for why the offset is different in Rust. const SI_OFF_SYSCALL: isize = 6; const SYS_SECCOMP_CODE: i32 = 1; #[inline] fn exit_with_code(exit_code: ExitCode) { // Write the metrics before exiting. if let Err(e) = METRICS.write() { error!("Failed to write metrics while stopping: {}", e); } // Safe because we're terminating the process anyway. unsafe { libc::_exit(exit_code) }; } macro_rules! generate_handler { ($fn_name:ident,$signal_name:ident, $exit_code:ident, $signal_metric:expr, $body:ident) => { #[inline(always)] extern "C" fn $fn_name(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) { // Safe because we're just reading some fields from a supposedly valid argument. let si_signo = unsafe { (*info).si_signo }; let si_code = unsafe { (*info).si_code }; if num!= si_signo || num!= $signal_name { exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR); } $signal_metric.store(1); error!( "Shutting down VM after intercepting signal {}, code {}.", si_signo, si_code ); $body(si_code, info); #[cfg(not(test))] match si_signo { $signal_name => exit_with_code(crate::$exit_code), _ => exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR), }; } }; } fn log_sigsys_err(si_code: c_int, info: *mut siginfo_t) { if si_code!= SYS_SECCOMP_CODE as i32
// Other signals which might do async unsafe things incompatible with the rest of this // function are blocked due to the sa_mask used when registering the signal handler. let syscall = unsafe { *(info as *const i32).offset(SI_OFF_SYSCALL) as usize }; error!( "Shutting down VM after intercepting a bad syscall ({}).", syscall ); } fn empty_fn(_si_code: c_int, _info: *mut siginfo_t) {} generate_handler!( sigxfsz_handler, SIGXFSZ, FC_EXIT_CODE_SIGXFSZ, METRICS.signals.sigxfsz, empty_fn ); generate_handler!( sigxcpu_handler, SIGXCPU, FC_EXIT_CODE_SIGXCPU, METRICS.signals.sigxcpu, empty_fn ); generate_handler!( sigbus_handler, SIGBUS, FC_EXIT_CODE_SIGBUS, METRICS.signals.sigbus, empty_fn ); generate_handler!( sigsegv_handler, SIGSEGV, FC_EXIT_CODE_SIGSEGV, METRICS.signals.sigsegv, empty_fn ); generate_handler!( sigsys_handler, SIGSYS, FC_EXIT_CODE_BAD_SYSCALL, METRICS.seccomp.num_faults, log_sigsys_err ); generate_handler!( sighup_handler, SIGHUP, FC_EXIT_CODE_SIGHUP, METRICS.signals.sighup, empty_fn ); generate_handler!( sigill_handler, SIGILL, FC_EXIT_CODE_SIGILL, METRICS.signals.sigill, empty_fn ); #[inline(always)] extern "C" fn sigpipe_handler(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) { // Just record the metric and allow the process to continue, the EPIPE error needs // to be handled at caller level. // Safe because we're just reading some fields from a supposedly valid argument. let si_signo = unsafe { (*info).si_signo }; let si_code = unsafe { (*info).si_code }; if num!= si_signo || num!= SIGPIPE { error!("Received invalid signal {}, code {}.", si_signo, si_code); return; } METRICS.signals.sigpipe.inc(); error!("Received signal {}, code {}.", si_signo, si_code); } /// Registers all the required signal handlers. /// /// Custom handlers are installed for: `SIGBUS`, `SIGSEGV`, `SIGSYS` /// `SIGXFSZ` `SIGXCPU` `SIGPIPE` `SIGHUP` and `SIGILL`. pub fn register_signal_handlers() -> utils::errno::Result<()> { // Call to unsafe register_signal_handler which is considered unsafe because it will // register a signal handler which will be called in the current thread and will interrupt // whatever work is done on the current thread, so we have to keep in mind that the registered // signal handler must only do async-signal-safe operations. register_signal_handler(SIGSYS, sigsys_handler)?; register_signal_handler(SIGBUS, sigbus_handler)?; register_signal_handler(SIGSEGV, sigsegv_handler)?; register_signal_handler(SIGXFSZ, sigxfsz_handler)?; register_signal_handler(SIGXCPU, sigxcpu_handler)?; register_signal_handler(SIGPIPE, sigpipe_handler)?; register_signal_handler(SIGHUP, sighup_handler)?; register_signal_handler(SIGILL, sigill_handler)?; Ok(()) } #[cfg(test)] mod tests { use super::*; use libc::{cpu_set_t, syscall}; use std::{mem, process, thread}; use seccompiler::sock_filter; // This function is used when running unit tests, so all the unsafes are safe. fn cpu_count() -> usize { let mut cpuset: cpu_set_t = unsafe { mem::zeroed() }; unsafe { libc::CPU_ZERO(&mut cpuset); } let ret = unsafe { libc::sched_getaffinity( 0, mem::size_of::<cpu_set_t>(), &mut cpuset as *mut cpu_set_t, ) }; assert_eq!(ret, 0); let mut num = 0; for i in 0..libc::CPU_SETSIZE as usize { if unsafe { libc::CPU_ISSET(i, &cpuset) } { num += 1; } } num } #[test] fn test_signal_handler() { let child = thread::spawn(move || { assert!(register_signal_handlers().is_ok()); let filter = make_test_seccomp_bpf_filter(); assert!(seccompiler::apply_filter(&filter).is_ok()); assert_eq!(METRICS.seccomp.num_faults.fetch(), 0); // Call the forbidden `SYS_mkdirat`. unsafe { libc::syscall(libc::SYS_mkdirat, "/foo/bar\0") }; // Call SIGBUS signal handler. assert_eq!(METRICS.signals.sigbus.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGBUS); } // Call SIGSEGV signal handler. assert_eq!(METRICS.signals.sigsegv.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGSEGV); } // Call SIGXFSZ signal handler. assert_eq!(METRICS.signals.sigxfsz.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGXFSZ); } // Call SIGXCPU signal handler. assert_eq!(METRICS.signals.sigxcpu.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGXCPU); } // Call SIGPIPE signal handler. assert_eq!(METRICS.signals.sigpipe.count(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGPIPE); } // Call SIGHUP signal handler. assert_eq!(METRICS.signals.sighup.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGHUP); } // Call SIGILL signal handler. assert_eq!(METRICS.signals.sigill.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGILL); } }); assert!(child.join().is_ok()); // Sanity check. assert!(cpu_count() > 0); // Kcov somehow messes with our handler getting the SIGSYS signal when a bad syscall // is caught, so the following assertion no longer holds. Ideally, we'd have a surefire // way of either preventing this behaviour, or detecting for certain whether this test is // run by kcov or not. The best we could do so far is to look at the perceived number of // available CPUs. Kcov seems to make a single CPU available to the process running the // tests, so we use this as an heuristic to decide if we check the assertion. if cpu_count() > 1 { // The signal handler should let the program continue during unit tests. assert!(METRICS.seccomp.num_faults.fetch() >= 1); } assert!(METRICS.signals.sigbus.fetch() >= 1); assert!(METRICS.signals.sigsegv.fetch() >= 1); assert!(METRICS.signals.sigxfsz.fetch() >= 1); assert!(METRICS.signals.sigxcpu.fetch() >= 1); assert!(METRICS.signals.sigpipe.count() >= 1); assert!(METRICS.signals.sighup.fetch() >= 1); // Workaround to GitHub issue 2216. #[cfg(not(target_arch = "aarch64"))] assert!(METRICS.signals.sigill.fetch() >= 1); } fn make_test_seccomp_bpf_filter() -> Vec<sock_filter> { // Create seccomp filter that allows all syscalls, except for `SYS_mkdirat`. // For some reason, directly calling `SYS_kill` with SIGSYS, like we do with the // other signals, results in an error. Probably because of the way `cargo test` is // handling signals. #[cfg(target_arch = "aarch64")] #[allow(clippy::unreadable_literal)] let bpf_filter = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, sock_filter { code: 21, jt: 1, jf: 0, k: 3221225655, }, sock_filter { code: 6, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 21, jt: 0, jf: 1, k: 34, }, sock_filter { code: 5, jt: 0, jf: 0, k: 1, }, sock_filter { code: 5, jt: 0, jf: 0, k: 2, }, sock_filter { code: 6, jt: 0, jf: 0, k: 196608, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, ]; #[cfg(target_arch = "x86_64")] #[allow(clippy::unreadable_literal)] let bpf_filter = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, sock_filter { code: 21, jt: 1, jf: 0, k: 3221225534, }, sock_filter { code: 6, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 21, jt: 0, jf: 1, k: 258, }, sock_filter { code: 5, jt: 0, jf: 0, k: 1, }, sock_filter { code: 5, jt: 0, jf: 0, k: 2, }, sock_filter { code: 6, jt: 0, jf: 0, k: 196608, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, ]; bpf_filter } }
{ // We received a SIGSYS for a reason other than `bad syscall`. exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR); }
conditional_block
signal_handler.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use libc::{ c_int, c_void, siginfo_t, SIGBUS, SIGHUP, SIGILL, SIGPIPE, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ, }; use crate::{ExitCode, FC_EXIT_CODE_UNEXPECTED_ERROR}; use logger::{error, IncMetric, StoreMetric, METRICS}; use utils::signal::register_signal_handler; // The offset of `si_syscall` (offending syscall identifier) within the siginfo structure // expressed as an `(u)int*`. // Offset `6` for an `i32` field means that the needed information is located at `6 * sizeof(i32)`. // See /usr/include/linux/signal.h for the C struct definition. // See https://github.com/rust-lang/libc/issues/716 for why the offset is different in Rust. const SI_OFF_SYSCALL: isize = 6; const SYS_SECCOMP_CODE: i32 = 1; #[inline] fn exit_with_code(exit_code: ExitCode) { // Write the metrics before exiting. if let Err(e) = METRICS.write() { error!("Failed to write metrics while stopping: {}", e); } // Safe because we're terminating the process anyway. unsafe { libc::_exit(exit_code) }; } macro_rules! generate_handler { ($fn_name:ident,$signal_name:ident, $exit_code:ident, $signal_metric:expr, $body:ident) => { #[inline(always)] extern "C" fn $fn_name(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) { // Safe because we're just reading some fields from a supposedly valid argument. let si_signo = unsafe { (*info).si_signo }; let si_code = unsafe { (*info).si_code }; if num!= si_signo || num!= $signal_name { exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR); } $signal_metric.store(1); error!( "Shutting down VM after intercepting signal {}, code {}.", si_signo, si_code ); $body(si_code, info); #[cfg(not(test))] match si_signo { $signal_name => exit_with_code(crate::$exit_code), _ => exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR), }; } }; } fn log_sigsys_err(si_code: c_int, info: *mut siginfo_t) { if si_code!= SYS_SECCOMP_CODE as i32 { // We received a SIGSYS for a reason other than `bad syscall`. exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR); } // Other signals which might do async unsafe things incompatible with the rest of this // function are blocked due to the sa_mask used when registering the signal handler. let syscall = unsafe { *(info as *const i32).offset(SI_OFF_SYSCALL) as usize }; error!( "Shutting down VM after intercepting a bad syscall ({}).", syscall ); } fn empty_fn(_si_code: c_int, _info: *mut siginfo_t) {} generate_handler!( sigxfsz_handler, SIGXFSZ, FC_EXIT_CODE_SIGXFSZ, METRICS.signals.sigxfsz, empty_fn ); generate_handler!( sigxcpu_handler, SIGXCPU, FC_EXIT_CODE_SIGXCPU, METRICS.signals.sigxcpu, empty_fn ); generate_handler!( sigbus_handler, SIGBUS, FC_EXIT_CODE_SIGBUS, METRICS.signals.sigbus, empty_fn ); generate_handler!( sigsegv_handler, SIGSEGV, FC_EXIT_CODE_SIGSEGV, METRICS.signals.sigsegv, empty_fn ); generate_handler!( sigsys_handler, SIGSYS, FC_EXIT_CODE_BAD_SYSCALL, METRICS.seccomp.num_faults, log_sigsys_err ); generate_handler!( sighup_handler, SIGHUP, FC_EXIT_CODE_SIGHUP, METRICS.signals.sighup, empty_fn ); generate_handler!( sigill_handler, SIGILL, FC_EXIT_CODE_SIGILL, METRICS.signals.sigill, empty_fn ); #[inline(always)] extern "C" fn sigpipe_handler(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) { // Just record the metric and allow the process to continue, the EPIPE error needs // to be handled at caller level. // Safe because we're just reading some fields from a supposedly valid argument. let si_signo = unsafe { (*info).si_signo }; let si_code = unsafe { (*info).si_code }; if num!= si_signo || num!= SIGPIPE { error!("Received invalid signal {}, code {}.", si_signo, si_code); return;
error!("Received signal {}, code {}.", si_signo, si_code); } /// Registers all the required signal handlers. /// /// Custom handlers are installed for: `SIGBUS`, `SIGSEGV`, `SIGSYS` /// `SIGXFSZ` `SIGXCPU` `SIGPIPE` `SIGHUP` and `SIGILL`. pub fn register_signal_handlers() -> utils::errno::Result<()> { // Call to unsafe register_signal_handler which is considered unsafe because it will // register a signal handler which will be called in the current thread and will interrupt // whatever work is done on the current thread, so we have to keep in mind that the registered // signal handler must only do async-signal-safe operations. register_signal_handler(SIGSYS, sigsys_handler)?; register_signal_handler(SIGBUS, sigbus_handler)?; register_signal_handler(SIGSEGV, sigsegv_handler)?; register_signal_handler(SIGXFSZ, sigxfsz_handler)?; register_signal_handler(SIGXCPU, sigxcpu_handler)?; register_signal_handler(SIGPIPE, sigpipe_handler)?; register_signal_handler(SIGHUP, sighup_handler)?; register_signal_handler(SIGILL, sigill_handler)?; Ok(()) } #[cfg(test)] mod tests { use super::*; use libc::{cpu_set_t, syscall}; use std::{mem, process, thread}; use seccompiler::sock_filter; // This function is used when running unit tests, so all the unsafes are safe. fn cpu_count() -> usize { let mut cpuset: cpu_set_t = unsafe { mem::zeroed() }; unsafe { libc::CPU_ZERO(&mut cpuset); } let ret = unsafe { libc::sched_getaffinity( 0, mem::size_of::<cpu_set_t>(), &mut cpuset as *mut cpu_set_t, ) }; assert_eq!(ret, 0); let mut num = 0; for i in 0..libc::CPU_SETSIZE as usize { if unsafe { libc::CPU_ISSET(i, &cpuset) } { num += 1; } } num } #[test] fn test_signal_handler() { let child = thread::spawn(move || { assert!(register_signal_handlers().is_ok()); let filter = make_test_seccomp_bpf_filter(); assert!(seccompiler::apply_filter(&filter).is_ok()); assert_eq!(METRICS.seccomp.num_faults.fetch(), 0); // Call the forbidden `SYS_mkdirat`. unsafe { libc::syscall(libc::SYS_mkdirat, "/foo/bar\0") }; // Call SIGBUS signal handler. assert_eq!(METRICS.signals.sigbus.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGBUS); } // Call SIGSEGV signal handler. assert_eq!(METRICS.signals.sigsegv.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGSEGV); } // Call SIGXFSZ signal handler. assert_eq!(METRICS.signals.sigxfsz.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGXFSZ); } // Call SIGXCPU signal handler. assert_eq!(METRICS.signals.sigxcpu.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGXCPU); } // Call SIGPIPE signal handler. assert_eq!(METRICS.signals.sigpipe.count(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGPIPE); } // Call SIGHUP signal handler. assert_eq!(METRICS.signals.sighup.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGHUP); } // Call SIGILL signal handler. assert_eq!(METRICS.signals.sigill.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGILL); } }); assert!(child.join().is_ok()); // Sanity check. assert!(cpu_count() > 0); // Kcov somehow messes with our handler getting the SIGSYS signal when a bad syscall // is caught, so the following assertion no longer holds. Ideally, we'd have a surefire // way of either preventing this behaviour, or detecting for certain whether this test is // run by kcov or not. The best we could do so far is to look at the perceived number of // available CPUs. Kcov seems to make a single CPU available to the process running the // tests, so we use this as an heuristic to decide if we check the assertion. if cpu_count() > 1 { // The signal handler should let the program continue during unit tests. assert!(METRICS.seccomp.num_faults.fetch() >= 1); } assert!(METRICS.signals.sigbus.fetch() >= 1); assert!(METRICS.signals.sigsegv.fetch() >= 1); assert!(METRICS.signals.sigxfsz.fetch() >= 1); assert!(METRICS.signals.sigxcpu.fetch() >= 1); assert!(METRICS.signals.sigpipe.count() >= 1); assert!(METRICS.signals.sighup.fetch() >= 1); // Workaround to GitHub issue 2216. #[cfg(not(target_arch = "aarch64"))] assert!(METRICS.signals.sigill.fetch() >= 1); } fn make_test_seccomp_bpf_filter() -> Vec<sock_filter> { // Create seccomp filter that allows all syscalls, except for `SYS_mkdirat`. // For some reason, directly calling `SYS_kill` with SIGSYS, like we do with the // other signals, results in an error. Probably because of the way `cargo test` is // handling signals. #[cfg(target_arch = "aarch64")] #[allow(clippy::unreadable_literal)] let bpf_filter = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, sock_filter { code: 21, jt: 1, jf: 0, k: 3221225655, }, sock_filter { code: 6, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 21, jt: 0, jf: 1, k: 34, }, sock_filter { code: 5, jt: 0, jf: 0, k: 1, }, sock_filter { code: 5, jt: 0, jf: 0, k: 2, }, sock_filter { code: 6, jt: 0, jf: 0, k: 196608, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, ]; #[cfg(target_arch = "x86_64")] #[allow(clippy::unreadable_literal)] let bpf_filter = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, sock_filter { code: 21, jt: 1, jf: 0, k: 3221225534, }, sock_filter { code: 6, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 21, jt: 0, jf: 1, k: 258, }, sock_filter { code: 5, jt: 0, jf: 0, k: 1, }, sock_filter { code: 5, jt: 0, jf: 0, k: 2, }, sock_filter { code: 6, jt: 0, jf: 0, k: 196608, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, ]; bpf_filter } }
} METRICS.signals.sigpipe.inc();
random_line_split
signal_handler.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use libc::{ c_int, c_void, siginfo_t, SIGBUS, SIGHUP, SIGILL, SIGPIPE, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ, }; use crate::{ExitCode, FC_EXIT_CODE_UNEXPECTED_ERROR}; use logger::{error, IncMetric, StoreMetric, METRICS}; use utils::signal::register_signal_handler; // The offset of `si_syscall` (offending syscall identifier) within the siginfo structure // expressed as an `(u)int*`. // Offset `6` for an `i32` field means that the needed information is located at `6 * sizeof(i32)`. // See /usr/include/linux/signal.h for the C struct definition. // See https://github.com/rust-lang/libc/issues/716 for why the offset is different in Rust. const SI_OFF_SYSCALL: isize = 6; const SYS_SECCOMP_CODE: i32 = 1; #[inline] fn exit_with_code(exit_code: ExitCode) { // Write the metrics before exiting. if let Err(e) = METRICS.write() { error!("Failed to write metrics while stopping: {}", e); } // Safe because we're terminating the process anyway. unsafe { libc::_exit(exit_code) }; } macro_rules! generate_handler { ($fn_name:ident,$signal_name:ident, $exit_code:ident, $signal_metric:expr, $body:ident) => { #[inline(always)] extern "C" fn $fn_name(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) { // Safe because we're just reading some fields from a supposedly valid argument. let si_signo = unsafe { (*info).si_signo }; let si_code = unsafe { (*info).si_code }; if num!= si_signo || num!= $signal_name { exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR); } $signal_metric.store(1); error!( "Shutting down VM after intercepting signal {}, code {}.", si_signo, si_code ); $body(si_code, info); #[cfg(not(test))] match si_signo { $signal_name => exit_with_code(crate::$exit_code), _ => exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR), }; } }; } fn log_sigsys_err(si_code: c_int, info: *mut siginfo_t) { if si_code!= SYS_SECCOMP_CODE as i32 { // We received a SIGSYS for a reason other than `bad syscall`. exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR); } // Other signals which might do async unsafe things incompatible with the rest of this // function are blocked due to the sa_mask used when registering the signal handler. let syscall = unsafe { *(info as *const i32).offset(SI_OFF_SYSCALL) as usize }; error!( "Shutting down VM after intercepting a bad syscall ({}).", syscall ); } fn empty_fn(_si_code: c_int, _info: *mut siginfo_t) {} generate_handler!( sigxfsz_handler, SIGXFSZ, FC_EXIT_CODE_SIGXFSZ, METRICS.signals.sigxfsz, empty_fn ); generate_handler!( sigxcpu_handler, SIGXCPU, FC_EXIT_CODE_SIGXCPU, METRICS.signals.sigxcpu, empty_fn ); generate_handler!( sigbus_handler, SIGBUS, FC_EXIT_CODE_SIGBUS, METRICS.signals.sigbus, empty_fn ); generate_handler!( sigsegv_handler, SIGSEGV, FC_EXIT_CODE_SIGSEGV, METRICS.signals.sigsegv, empty_fn ); generate_handler!( sigsys_handler, SIGSYS, FC_EXIT_CODE_BAD_SYSCALL, METRICS.seccomp.num_faults, log_sigsys_err ); generate_handler!( sighup_handler, SIGHUP, FC_EXIT_CODE_SIGHUP, METRICS.signals.sighup, empty_fn ); generate_handler!( sigill_handler, SIGILL, FC_EXIT_CODE_SIGILL, METRICS.signals.sigill, empty_fn ); #[inline(always)] extern "C" fn
(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) { // Just record the metric and allow the process to continue, the EPIPE error needs // to be handled at caller level. // Safe because we're just reading some fields from a supposedly valid argument. let si_signo = unsafe { (*info).si_signo }; let si_code = unsafe { (*info).si_code }; if num!= si_signo || num!= SIGPIPE { error!("Received invalid signal {}, code {}.", si_signo, si_code); return; } METRICS.signals.sigpipe.inc(); error!("Received signal {}, code {}.", si_signo, si_code); } /// Registers all the required signal handlers. /// /// Custom handlers are installed for: `SIGBUS`, `SIGSEGV`, `SIGSYS` /// `SIGXFSZ` `SIGXCPU` `SIGPIPE` `SIGHUP` and `SIGILL`. pub fn register_signal_handlers() -> utils::errno::Result<()> { // Call to unsafe register_signal_handler which is considered unsafe because it will // register a signal handler which will be called in the current thread and will interrupt // whatever work is done on the current thread, so we have to keep in mind that the registered // signal handler must only do async-signal-safe operations. register_signal_handler(SIGSYS, sigsys_handler)?; register_signal_handler(SIGBUS, sigbus_handler)?; register_signal_handler(SIGSEGV, sigsegv_handler)?; register_signal_handler(SIGXFSZ, sigxfsz_handler)?; register_signal_handler(SIGXCPU, sigxcpu_handler)?; register_signal_handler(SIGPIPE, sigpipe_handler)?; register_signal_handler(SIGHUP, sighup_handler)?; register_signal_handler(SIGILL, sigill_handler)?; Ok(()) } #[cfg(test)] mod tests { use super::*; use libc::{cpu_set_t, syscall}; use std::{mem, process, thread}; use seccompiler::sock_filter; // This function is used when running unit tests, so all the unsafes are safe. fn cpu_count() -> usize { let mut cpuset: cpu_set_t = unsafe { mem::zeroed() }; unsafe { libc::CPU_ZERO(&mut cpuset); } let ret = unsafe { libc::sched_getaffinity( 0, mem::size_of::<cpu_set_t>(), &mut cpuset as *mut cpu_set_t, ) }; assert_eq!(ret, 0); let mut num = 0; for i in 0..libc::CPU_SETSIZE as usize { if unsafe { libc::CPU_ISSET(i, &cpuset) } { num += 1; } } num } #[test] fn test_signal_handler() { let child = thread::spawn(move || { assert!(register_signal_handlers().is_ok()); let filter = make_test_seccomp_bpf_filter(); assert!(seccompiler::apply_filter(&filter).is_ok()); assert_eq!(METRICS.seccomp.num_faults.fetch(), 0); // Call the forbidden `SYS_mkdirat`. unsafe { libc::syscall(libc::SYS_mkdirat, "/foo/bar\0") }; // Call SIGBUS signal handler. assert_eq!(METRICS.signals.sigbus.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGBUS); } // Call SIGSEGV signal handler. assert_eq!(METRICS.signals.sigsegv.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGSEGV); } // Call SIGXFSZ signal handler. assert_eq!(METRICS.signals.sigxfsz.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGXFSZ); } // Call SIGXCPU signal handler. assert_eq!(METRICS.signals.sigxcpu.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGXCPU); } // Call SIGPIPE signal handler. assert_eq!(METRICS.signals.sigpipe.count(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGPIPE); } // Call SIGHUP signal handler. assert_eq!(METRICS.signals.sighup.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGHUP); } // Call SIGILL signal handler. assert_eq!(METRICS.signals.sigill.fetch(), 0); unsafe { syscall(libc::SYS_kill, process::id(), SIGILL); } }); assert!(child.join().is_ok()); // Sanity check. assert!(cpu_count() > 0); // Kcov somehow messes with our handler getting the SIGSYS signal when a bad syscall // is caught, so the following assertion no longer holds. Ideally, we'd have a surefire // way of either preventing this behaviour, or detecting for certain whether this test is // run by kcov or not. The best we could do so far is to look at the perceived number of // available CPUs. Kcov seems to make a single CPU available to the process running the // tests, so we use this as an heuristic to decide if we check the assertion. if cpu_count() > 1 { // The signal handler should let the program continue during unit tests. assert!(METRICS.seccomp.num_faults.fetch() >= 1); } assert!(METRICS.signals.sigbus.fetch() >= 1); assert!(METRICS.signals.sigsegv.fetch() >= 1); assert!(METRICS.signals.sigxfsz.fetch() >= 1); assert!(METRICS.signals.sigxcpu.fetch() >= 1); assert!(METRICS.signals.sigpipe.count() >= 1); assert!(METRICS.signals.sighup.fetch() >= 1); // Workaround to GitHub issue 2216. #[cfg(not(target_arch = "aarch64"))] assert!(METRICS.signals.sigill.fetch() >= 1); } fn make_test_seccomp_bpf_filter() -> Vec<sock_filter> { // Create seccomp filter that allows all syscalls, except for `SYS_mkdirat`. // For some reason, directly calling `SYS_kill` with SIGSYS, like we do with the // other signals, results in an error. Probably because of the way `cargo test` is // handling signals. #[cfg(target_arch = "aarch64")] #[allow(clippy::unreadable_literal)] let bpf_filter = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, sock_filter { code: 21, jt: 1, jf: 0, k: 3221225655, }, sock_filter { code: 6, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 21, jt: 0, jf: 1, k: 34, }, sock_filter { code: 5, jt: 0, jf: 0, k: 1, }, sock_filter { code: 5, jt: 0, jf: 0, k: 2, }, sock_filter { code: 6, jt: 0, jf: 0, k: 196608, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, ]; #[cfg(target_arch = "x86_64")] #[allow(clippy::unreadable_literal)] let bpf_filter = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, sock_filter { code: 21, jt: 1, jf: 0, k: 3221225534, }, sock_filter { code: 6, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 21, jt: 0, jf: 1, k: 258, }, sock_filter { code: 5, jt: 0, jf: 0, k: 1, }, sock_filter { code: 5, jt: 0, jf: 0, k: 2, }, sock_filter { code: 6, jt: 0, jf: 0, k: 196608, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, sock_filter { code: 6, jt: 0, jf: 0, k: 2147418112, }, ]; bpf_filter } }
sigpipe_handler
identifier_name
mixer.rs
use std::ptr; use std::ffi::CStr; use std::ffi::CString; use std::cmp::min; use libc::c_int; use libc::c_uint; use libc::c_void; use format::error::DriverError; use alsa::device::AlsaDevice; use alsa::device::create_error; use alsa::ffi::*; pub type SndSize = snd_pcm_uframes_t; pub struct Params { hw_params: *mut snd_pcm_hw_params_t, } impl Params { pub fn new() -> Result<Params, DriverError> { let mut param_ptr: *mut snd_pcm_hw_params_t = ptr::null_mut(); let mut err = 0; unsafe { err = snd_pcm_hw_params_malloc(&mut param_ptr); } if err < 0 { return Err(create_error("snd_pcm_hw_params_malloc", err)); } else { return Ok(Params { hw_params: param_ptr }); } } pub fn free(&self) { unsafe { snd_pcm_hw_params_free(self.hw_params); } } pub fn buffer_size(&self) -> Result<SndSize, DriverError> { let mut size: snd_pcm_uframes_t = 0; let mut err = 0; unsafe { err = snd_pcm_hw_params_get_buffer_size(self.hw_params, &mut size); } if err < 0 { return Err(create_error("snd_pcm_hw_params_get_buffer_size", err)); } else { println!("Buffer size: {}", size); return Ok(size); } } pub fn any(&self, dev: &AlsaDevice) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; unsafe { err = snd_pcm_hw_params_any(pcm, self.hw_params); } if err < 0 { return Some(create_error("snd_pcm_hw_params_any", err)); } else { return None; } } pub fn format(&self, dev: &AlsaDevice, rate_in: c_uint, channels: c_uint, format: c_int) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; let mut rate: c_uint = rate_in; unsafe { err = snd_pcm_hw_params_set_rate_resample(pcm, self.hw_params, 1); err = snd_pcm_hw_params_set_access(pcm, self.hw_params, SND_PCM_ACCESS_RW_INTERLEAVED); err = snd_pcm_hw_params_set_format(pcm, self.hw_params, format); err = snd_pcm_hw_params_set_channels(pcm, self.hw_params, channels as c_uint); err = snd_pcm_hw_params_set_rate_near(pcm, self.hw_params, &mut rate, ptr::null_mut()); } if err < 0 { return Some(create_error("snd_pcm_hw_params_any", err)); } else { return None; } } pub fn apply(&self, dev: &AlsaDevice) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; unsafe { err = snd_pcm_hw_params(pcm, self.hw_params); } if err < 0 { return Some(create_error("snd_pcm_hw_params", err)); } else
} }
{ return None; }
conditional_block
mixer.rs
use std::ptr; use std::ffi::CStr; use std::ffi::CString; use std::cmp::min; use libc::c_int; use libc::c_uint; use libc::c_void; use format::error::DriverError; use alsa::device::AlsaDevice; use alsa::device::create_error; use alsa::ffi::*; pub type SndSize = snd_pcm_uframes_t; pub struct Params { hw_params: *mut snd_pcm_hw_params_t, } impl Params { pub fn new() -> Result<Params, DriverError> { let mut param_ptr: *mut snd_pcm_hw_params_t = ptr::null_mut(); let mut err = 0; unsafe { err = snd_pcm_hw_params_malloc(&mut param_ptr); } if err < 0 { return Err(create_error("snd_pcm_hw_params_malloc", err)); } else { return Ok(Params { hw_params: param_ptr }); } } pub fn free(&self) { unsafe { snd_pcm_hw_params_free(self.hw_params); } } pub fn buffer_size(&self) -> Result<SndSize, DriverError> { let mut size: snd_pcm_uframes_t = 0; let mut err = 0; unsafe { err = snd_pcm_hw_params_get_buffer_size(self.hw_params, &mut size); } if err < 0 { return Err(create_error("snd_pcm_hw_params_get_buffer_size", err)); } else { println!("Buffer size: {}", size); return Ok(size); } } pub fn any(&self, dev: &AlsaDevice) -> Option<DriverError>
pub fn format(&self, dev: &AlsaDevice, rate_in: c_uint, channels: c_uint, format: c_int) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; let mut rate: c_uint = rate_in; unsafe { err = snd_pcm_hw_params_set_rate_resample(pcm, self.hw_params, 1); err = snd_pcm_hw_params_set_access(pcm, self.hw_params, SND_PCM_ACCESS_RW_INTERLEAVED); err = snd_pcm_hw_params_set_format(pcm, self.hw_params, format); err = snd_pcm_hw_params_set_channels(pcm, self.hw_params, channels as c_uint); err = snd_pcm_hw_params_set_rate_near(pcm, self.hw_params, &mut rate, ptr::null_mut()); } if err < 0 { return Some(create_error("snd_pcm_hw_params_any", err)); } else { return None; } } pub fn apply(&self, dev: &AlsaDevice) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; unsafe { err = snd_pcm_hw_params(pcm, self.hw_params); } if err < 0 { return Some(create_error("snd_pcm_hw_params", err)); } else { return None; } } }
{ let pcm = dev.get_pcm(); let mut err = 0; unsafe { err = snd_pcm_hw_params_any(pcm, self.hw_params); } if err < 0 { return Some(create_error("snd_pcm_hw_params_any", err)); } else { return None; } }
identifier_body
mixer.rs
use std::ptr; use std::ffi::CStr; use std::ffi::CString; use std::cmp::min; use libc::c_int; use libc::c_uint; use libc::c_void; use format::error::DriverError; use alsa::device::AlsaDevice; use alsa::device::create_error; use alsa::ffi::*; pub type SndSize = snd_pcm_uframes_t; pub struct Params { hw_params: *mut snd_pcm_hw_params_t, } impl Params { pub fn new() -> Result<Params, DriverError> { let mut param_ptr: *mut snd_pcm_hw_params_t = ptr::null_mut(); let mut err = 0; unsafe { err = snd_pcm_hw_params_malloc(&mut param_ptr); } if err < 0 { return Err(create_error("snd_pcm_hw_params_malloc", err)); } else { return Ok(Params { hw_params: param_ptr }); } } pub fn free(&self) { unsafe { snd_pcm_hw_params_free(self.hw_params); } } pub fn
(&self) -> Result<SndSize, DriverError> { let mut size: snd_pcm_uframes_t = 0; let mut err = 0; unsafe { err = snd_pcm_hw_params_get_buffer_size(self.hw_params, &mut size); } if err < 0 { return Err(create_error("snd_pcm_hw_params_get_buffer_size", err)); } else { println!("Buffer size: {}", size); return Ok(size); } } pub fn any(&self, dev: &AlsaDevice) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; unsafe { err = snd_pcm_hw_params_any(pcm, self.hw_params); } if err < 0 { return Some(create_error("snd_pcm_hw_params_any", err)); } else { return None; } } pub fn format(&self, dev: &AlsaDevice, rate_in: c_uint, channels: c_uint, format: c_int) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; let mut rate: c_uint = rate_in; unsafe { err = snd_pcm_hw_params_set_rate_resample(pcm, self.hw_params, 1); err = snd_pcm_hw_params_set_access(pcm, self.hw_params, SND_PCM_ACCESS_RW_INTERLEAVED); err = snd_pcm_hw_params_set_format(pcm, self.hw_params, format); err = snd_pcm_hw_params_set_channels(pcm, self.hw_params, channels as c_uint); err = snd_pcm_hw_params_set_rate_near(pcm, self.hw_params, &mut rate, ptr::null_mut()); } if err < 0 { return Some(create_error("snd_pcm_hw_params_any", err)); } else { return None; } } pub fn apply(&self, dev: &AlsaDevice) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; unsafe { err = snd_pcm_hw_params(pcm, self.hw_params); } if err < 0 { return Some(create_error("snd_pcm_hw_params", err)); } else { return None; } } }
buffer_size
identifier_name
mixer.rs
use std::ptr; use std::ffi::CStr; use std::ffi::CString; use std::cmp::min; use libc::c_int; use libc::c_uint; use libc::c_void; use format::error::DriverError; use alsa::device::AlsaDevice; use alsa::device::create_error; use alsa::ffi::*; pub type SndSize = snd_pcm_uframes_t; pub struct Params { hw_params: *mut snd_pcm_hw_params_t, } impl Params { pub fn new() -> Result<Params, DriverError> { let mut param_ptr: *mut snd_pcm_hw_params_t = ptr::null_mut(); let mut err = 0; unsafe { err = snd_pcm_hw_params_malloc(&mut param_ptr); } if err < 0 { return Err(create_error("snd_pcm_hw_params_malloc", err)); } else { return Ok(Params { hw_params: param_ptr }); } } pub fn free(&self) { unsafe { snd_pcm_hw_params_free(self.hw_params); } } pub fn buffer_size(&self) -> Result<SndSize, DriverError> { let mut size: snd_pcm_uframes_t = 0; let mut err = 0; unsafe { err = snd_pcm_hw_params_get_buffer_size(self.hw_params, &mut size); } if err < 0 { return Err(create_error("snd_pcm_hw_params_get_buffer_size", err)); } else { println!("Buffer size: {}", size); return Ok(size);
pub fn any(&self, dev: &AlsaDevice) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; unsafe { err = snd_pcm_hw_params_any(pcm, self.hw_params); } if err < 0 { return Some(create_error("snd_pcm_hw_params_any", err)); } else { return None; } } pub fn format(&self, dev: &AlsaDevice, rate_in: c_uint, channels: c_uint, format: c_int) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; let mut rate: c_uint = rate_in; unsafe { err = snd_pcm_hw_params_set_rate_resample(pcm, self.hw_params, 1); err = snd_pcm_hw_params_set_access(pcm, self.hw_params, SND_PCM_ACCESS_RW_INTERLEAVED); err = snd_pcm_hw_params_set_format(pcm, self.hw_params, format); err = snd_pcm_hw_params_set_channels(pcm, self.hw_params, channels as c_uint); err = snd_pcm_hw_params_set_rate_near(pcm, self.hw_params, &mut rate, ptr::null_mut()); } if err < 0 { return Some(create_error("snd_pcm_hw_params_any", err)); } else { return None; } } pub fn apply(&self, dev: &AlsaDevice) -> Option<DriverError> { let pcm = dev.get_pcm(); let mut err = 0; unsafe { err = snd_pcm_hw_params(pcm, self.hw_params); } if err < 0 { return Some(create_error("snd_pcm_hw_params", err)); } else { return None; } } }
} }
random_line_split
logger.rs
extern crate log4rs; extern crate log; extern crate libc; use std::error::Error; use indy; pub struct IndyCliLogger; impl IndyCliLogger { pub fn
(path: &str) -> Result<(), String> { log4rs::init_file(path, Default::default()) .map_err(|err| format!("Cannot init Indy CLI logger: {}", err.description()))?; indy::logger::set_logger(log::logger()) .map_err(|_| "Cannot init Libindy logger".to_string()) } } #[macro_export] macro_rules! try_log { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { error!("try_log! | {}", err); return Err(From::from(err)) } }) } macro_rules! _log_err { ($lvl:expr, $expr:expr) => ( |err| { log!($lvl, "{} - {:?}", $expr, err); err } ); ($lvl:expr) => ( |err| { log!($lvl, "{:?}", err); err } ) } #[macro_export] macro_rules! error_err { () => ( _log_err!(::log::Level::Error) ); ($($arg:tt)*) => ( _log_err!(::log::Level::Error, $($arg)*) ) } #[macro_export] macro_rules! trace_err { () => ( _log_err!(::log::Level::Trace) ); ($($arg:tt)*) => ( _log_err!(::log::Level::Trace, $($arg)*) ) } #[cfg(debug_assertions)] #[macro_export] macro_rules! secret { ($val:expr) => {{ $val }}; } #[cfg(not(debug_assertions))] #[macro_export] macro_rules! secret { ($val:expr) => {{ "_" }}; }
init
identifier_name
logger.rs
extern crate log4rs; extern crate log; extern crate libc; use std::error::Error; use indy; pub struct IndyCliLogger; impl IndyCliLogger { pub fn init(path: &str) -> Result<(), String> { log4rs::init_file(path, Default::default()) .map_err(|err| format!("Cannot init Indy CLI logger: {}", err.description()))?;
} #[macro_export] macro_rules! try_log { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { error!("try_log! | {}", err); return Err(From::from(err)) } }) } macro_rules! _log_err { ($lvl:expr, $expr:expr) => ( |err| { log!($lvl, "{} - {:?}", $expr, err); err } ); ($lvl:expr) => ( |err| { log!($lvl, "{:?}", err); err } ) } #[macro_export] macro_rules! error_err { () => ( _log_err!(::log::Level::Error) ); ($($arg:tt)*) => ( _log_err!(::log::Level::Error, $($arg)*) ) } #[macro_export] macro_rules! trace_err { () => ( _log_err!(::log::Level::Trace) ); ($($arg:tt)*) => ( _log_err!(::log::Level::Trace, $($arg)*) ) } #[cfg(debug_assertions)] #[macro_export] macro_rules! secret { ($val:expr) => {{ $val }}; } #[cfg(not(debug_assertions))] #[macro_export] macro_rules! secret { ($val:expr) => {{ "_" }}; }
indy::logger::set_logger(log::logger()) .map_err(|_| "Cannot init Libindy logger".to_string()) }
random_line_split
logger.rs
extern crate log4rs; extern crate log; extern crate libc; use std::error::Error; use indy; pub struct IndyCliLogger; impl IndyCliLogger { pub fn init(path: &str) -> Result<(), String>
} #[macro_export] macro_rules! try_log { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { error!("try_log! | {}", err); return Err(From::from(err)) } }) } macro_rules! _log_err { ($lvl:expr, $expr:expr) => ( |err| { log!($lvl, "{} - {:?}", $expr, err); err } ); ($lvl:expr) => ( |err| { log!($lvl, "{:?}", err); err } ) } #[macro_export] macro_rules! error_err { () => ( _log_err!(::log::Level::Error) ); ($($arg:tt)*) => ( _log_err!(::log::Level::Error, $($arg)*) ) } #[macro_export] macro_rules! trace_err { () => ( _log_err!(::log::Level::Trace) ); ($($arg:tt)*) => ( _log_err!(::log::Level::Trace, $($arg)*) ) } #[cfg(debug_assertions)] #[macro_export] macro_rules! secret { ($val:expr) => {{ $val }}; } #[cfg(not(debug_assertions))] #[macro_export] macro_rules! secret { ($val:expr) => {{ "_" }}; }
{ log4rs::init_file(path, Default::default()) .map_err(|err| format!("Cannot init Indy CLI logger: {}", err.description()))?; indy::logger::set_logger(log::logger()) .map_err(|_| "Cannot init Libindy logger".to_string()) }
identifier_body
contrast.rs
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *
* 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. */ #include "ip.rsh" #pragma rs_fp_relaxed static float brightM = 0.f; static float brightC = 0.f; void setBright(float v) { brightM = pow(2.f, v / 100.f); brightC = 127.f - brightM * 127.f; } void contrast(const uchar4 *in, uchar4 *out) { float3 v = convert_float3(in->rgb) * brightM + brightC; out->rgb = convert_uchar3(clamp(v, 0.f, 255.f)); }
* 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,
random_line_split
linux.rs
extern crate libxdo; extern crate itertools; use std::borrow::Cow; use self::itertools::Itertools; use self::libxdo::XDo; use super::{Physical, Key}; const DELAY: u32 = 12_000; // microseconds // Keysyms can be found via the xev tool or here: // https://cgit.freedesktop.org/xorg/proto/x11proto/tree/ fn get_physical_keysym(key: Physical) -> &'static str { use Physical::*; match key { Return => "Return", Shift => "Shift", Control => "Control", Alt => "Alt", A => "a", B => "b", C => "c", D => "d", E => "e", F => "f", G => "g", H => "h", I => "i", J => "j", K => "k", L => "l", M => "m", N => "n", O => "o", P => "p", Q => "q", R => "r", S => "s", T => "t", U => "u", V => "v", W => "w", X => "x", Y => "y", Z => "z", } } fn get_unicode_keysym(c: char) -> String { format!("U{:04X}", c as u32) } fn get_keysym(key: Key) -> Cow<'static, str> { match key { Key::Unicode(ch) => get_unicode_keysym(ch).into(), Key::Physical(key) => get_physical_keysym(key).into(), } } pub fn
(key: Key) { if let Ok(xdo) = XDo::new(None) { let sym = get_keysym(key); let _ = xdo.send_keysequence_down(&sym, DELAY); } } pub fn release_key(key: Key) { if let Ok(xdo) = XDo::new(None) { let sym = get_keysym(key); let _ = xdo.send_keysequence_up(&sym, DELAY); } } pub fn send_combo(keys: &[Key]) { if let Ok(xdo) = XDo::new(None) { let sym = keys.iter().cloned().map(get_keysym).join("+"); let _ = xdo.send_keysequence(&sym, DELAY); } } pub fn send_key(key: Key) { match key { Key::Unicode(c) => send_char(c), Key::Physical(key) => if let Ok(xdo) = XDo::new(None) { let sym = get_physical_keysym(key); let _ = xdo.send_keysequence(sym, DELAY); } } } /// Send a unicode character. Unsupported chars are silently ignored. pub fn send_char(c: char) { send_str(&c.to_string()); } /// Send a string as keyboard events. Unsupported chars are silently ignored. pub fn send_str(msg: &str) { if let Ok(xdo) = XDo::new(None) { let _ = xdo.enter_text(msg, DELAY); } }
press_key
identifier_name
linux.rs
extern crate libxdo; extern crate itertools; use std::borrow::Cow; use self::itertools::Itertools; use self::libxdo::XDo; use super::{Physical, Key}; const DELAY: u32 = 12_000; // microseconds // Keysyms can be found via the xev tool or here: // https://cgit.freedesktop.org/xorg/proto/x11proto/tree/ fn get_physical_keysym(key: Physical) -> &'static str { use Physical::*; match key { Return => "Return", Shift => "Shift", Control => "Control", Alt => "Alt", A => "a", B => "b", C => "c", D => "d", E => "e", F => "f", G => "g", H => "h", I => "i", J => "j", K => "k", L => "l", M => "m", N => "n", O => "o", P => "p", Q => "q", R => "r", S => "s", T => "t", U => "u", V => "v", W => "w", X => "x", Y => "y", Z => "z", } } fn get_unicode_keysym(c: char) -> String { format!("U{:04X}", c as u32) } fn get_keysym(key: Key) -> Cow<'static, str> { match key { Key::Unicode(ch) => get_unicode_keysym(ch).into(), Key::Physical(key) => get_physical_keysym(key).into(), } } pub fn press_key(key: Key) { if let Ok(xdo) = XDo::new(None) { let sym = get_keysym(key); let _ = xdo.send_keysequence_down(&sym, DELAY); } } pub fn release_key(key: Key) { if let Ok(xdo) = XDo::new(None) { let sym = get_keysym(key); let _ = xdo.send_keysequence_up(&sym, DELAY); } } pub fn send_combo(keys: &[Key]) { if let Ok(xdo) = XDo::new(None) { let sym = keys.iter().cloned().map(get_keysym).join("+"); let _ = xdo.send_keysequence(&sym, DELAY); } } pub fn send_key(key: Key) { match key { Key::Unicode(c) => send_char(c), Key::Physical(key) => if let Ok(xdo) = XDo::new(None) { let sym = get_physical_keysym(key); let _ = xdo.send_keysequence(sym, DELAY); }
send_str(&c.to_string()); } /// Send a string as keyboard events. Unsupported chars are silently ignored. pub fn send_str(msg: &str) { if let Ok(xdo) = XDo::new(None) { let _ = xdo.enter_text(msg, DELAY); } }
} } /// Send a unicode character. Unsupported chars are silently ignored. pub fn send_char(c: char) {
random_line_split
linux.rs
extern crate libxdo; extern crate itertools; use std::borrow::Cow; use self::itertools::Itertools; use self::libxdo::XDo; use super::{Physical, Key}; const DELAY: u32 = 12_000; // microseconds // Keysyms can be found via the xev tool or here: // https://cgit.freedesktop.org/xorg/proto/x11proto/tree/ fn get_physical_keysym(key: Physical) -> &'static str { use Physical::*; match key { Return => "Return", Shift => "Shift", Control => "Control", Alt => "Alt", A => "a", B => "b", C => "c", D => "d", E => "e", F => "f", G => "g", H => "h", I => "i", J => "j", K => "k", L => "l", M => "m", N => "n", O => "o", P => "p", Q => "q", R => "r", S => "s", T => "t", U => "u", V => "v", W => "w", X => "x", Y => "y", Z => "z", } } fn get_unicode_keysym(c: char) -> String { format!("U{:04X}", c as u32) } fn get_keysym(key: Key) -> Cow<'static, str> { match key { Key::Unicode(ch) => get_unicode_keysym(ch).into(), Key::Physical(key) => get_physical_keysym(key).into(), } } pub fn press_key(key: Key) { if let Ok(xdo) = XDo::new(None) { let sym = get_keysym(key); let _ = xdo.send_keysequence_down(&sym, DELAY); } } pub fn release_key(key: Key) { if let Ok(xdo) = XDo::new(None) { let sym = get_keysym(key); let _ = xdo.send_keysequence_up(&sym, DELAY); } } pub fn send_combo(keys: &[Key]) { if let Ok(xdo) = XDo::new(None) { let sym = keys.iter().cloned().map(get_keysym).join("+"); let _ = xdo.send_keysequence(&sym, DELAY); } } pub fn send_key(key: Key) { match key { Key::Unicode(c) => send_char(c), Key::Physical(key) => if let Ok(xdo) = XDo::new(None) { let sym = get_physical_keysym(key); let _ = xdo.send_keysequence(sym, DELAY); } } } /// Send a unicode character. Unsupported chars are silently ignored. pub fn send_char(c: char) { send_str(&c.to_string()); } /// Send a string as keyboard events. Unsupported chars are silently ignored. pub fn send_str(msg: &str)
{ if let Ok(xdo) = XDo::new(None) { let _ = xdo.enter_text(msg, DELAY); } }
identifier_body
rensa_coef_tracker.rs
use field_bit::FieldBit; use rensa_tracker::RensaTracker; use score; pub struct RensaCoefTracker { pub num_erased: [usize; 20], pub long_bonus_coef: [usize; 20], pub color_bonus_coef: [usize; 20], } impl RensaCoefTracker { pub fn new() -> RensaCoefTracker { RensaCoefTracker { num_erased: [0; 20], long_bonus_coef: [0; 20], color_bonus_coef: [0; 20], } } pub fn coef(&self, nth_chain: usize) -> usize { score::calculate_rensa_bonus_coef(score::chain_bonus(nth_chain), self.long_bonus_coef[nth_chain], self.color_bonus_coef[nth_chain]) } } impl RensaTracker for RensaCoefTracker { fn track_coef(&mut self, nth_chain: usize, num_erased: usize, long_bonus_coef: usize, color_bonus_coef: usize) { self.num_erased[nth_chain] = num_erased; self.long_bonus_coef[nth_chain] = long_bonus_coef; self.color_bonus_coef[nth_chain] = color_bonus_coef; } fn track_vanish(&mut self, _nth_chain: usize, _vanished: &FieldBit, _ojama_vanished: &FieldBit)
fn track_drop(&mut self, _old_low_bits: u64, _old_high_bits: u64, _new_low_bits: u64, _new_high_bits: u64) {} } #[cfg(test)] mod tests { use super::RensaCoefTracker; use rensa_tracker::RensaTracker; #[test] fn test_score() { let mut tracker = RensaCoefTracker::new(); tracker.track_coef(1, 4, 0, 0); tracker.track_coef(2, 4, 0, 0); tracker.track_coef(3, 4, 0, 0); assert_eq!(4, tracker.num_erased[3]); assert_eq!(0, tracker.num_erased[4]); } } #[cfg(all(test, target_feature = "avx2", target_feature="bmi2"))] mod tests_for_avx2 { use super::RensaCoefTracker; use field::BitField; #[test] fn test_simulate() { let mut bf = BitField::from_str(concat!( "R...RR", "RGBRYR", "RRGBBY", "GGBYYR")); let mut tracker = RensaCoefTracker::new(); let rensa_result = bf.simulate_with_tracker(&mut tracker); assert_eq!(5, rensa_result.chain); assert_eq!(4, tracker.num_erased[1]); assert_eq!(4, tracker.num_erased[2]); assert_eq!(4, tracker.num_erased[3]); assert_eq!(4, tracker.num_erased[4]); assert_eq!(5, tracker.num_erased[5]); assert_eq!(1, tracker.coef(1)); assert_eq!(8, tracker.coef(2)); assert_eq!(16, tracker.coef(3)); assert_eq!(32, tracker.coef(4)); assert_eq!(64 + 2, tracker.coef(5)); } }
{}
identifier_body
rensa_coef_tracker.rs
use field_bit::FieldBit; use rensa_tracker::RensaTracker; use score; pub struct RensaCoefTracker { pub num_erased: [usize; 20], pub long_bonus_coef: [usize; 20], pub color_bonus_coef: [usize; 20], } impl RensaCoefTracker { pub fn new() -> RensaCoefTracker { RensaCoefTracker { num_erased: [0; 20], long_bonus_coef: [0; 20], color_bonus_coef: [0; 20], } } pub fn coef(&self, nth_chain: usize) -> usize { score::calculate_rensa_bonus_coef(score::chain_bonus(nth_chain), self.long_bonus_coef[nth_chain], self.color_bonus_coef[nth_chain]) } } impl RensaTracker for RensaCoefTracker { fn track_coef(&mut self, nth_chain: usize, num_erased: usize, long_bonus_coef: usize, color_bonus_coef: usize) { self.num_erased[nth_chain] = num_erased; self.long_bonus_coef[nth_chain] = long_bonus_coef; self.color_bonus_coef[nth_chain] = color_bonus_coef; } fn track_vanish(&mut self, _nth_chain: usize, _vanished: &FieldBit, _ojama_vanished: &FieldBit) {} fn track_drop(&mut self, _old_low_bits: u64, _old_high_bits: u64, _new_low_bits: u64, _new_high_bits: u64) {} } #[cfg(test)] mod tests { use super::RensaCoefTracker; use rensa_tracker::RensaTracker; #[test] fn test_score() { let mut tracker = RensaCoefTracker::new(); tracker.track_coef(1, 4, 0, 0); tracker.track_coef(2, 4, 0, 0); tracker.track_coef(3, 4, 0, 0); assert_eq!(4, tracker.num_erased[3]); assert_eq!(0, tracker.num_erased[4]); } } #[cfg(all(test, target_feature = "avx2", target_feature="bmi2"))] mod tests_for_avx2 { use super::RensaCoefTracker; use field::BitField; #[test] fn test_simulate() { let mut bf = BitField::from_str(concat!( "R...RR", "RGBRYR", "RRGBBY", "GGBYYR"));
assert_eq!(4, tracker.num_erased[1]); assert_eq!(4, tracker.num_erased[2]); assert_eq!(4, tracker.num_erased[3]); assert_eq!(4, tracker.num_erased[4]); assert_eq!(5, tracker.num_erased[5]); assert_eq!(1, tracker.coef(1)); assert_eq!(8, tracker.coef(2)); assert_eq!(16, tracker.coef(3)); assert_eq!(32, tracker.coef(4)); assert_eq!(64 + 2, tracker.coef(5)); } }
let mut tracker = RensaCoefTracker::new(); let rensa_result = bf.simulate_with_tracker(&mut tracker); assert_eq!(5, rensa_result.chain);
random_line_split
rensa_coef_tracker.rs
use field_bit::FieldBit; use rensa_tracker::RensaTracker; use score; pub struct RensaCoefTracker { pub num_erased: [usize; 20], pub long_bonus_coef: [usize; 20], pub color_bonus_coef: [usize; 20], } impl RensaCoefTracker { pub fn new() -> RensaCoefTracker { RensaCoefTracker { num_erased: [0; 20], long_bonus_coef: [0; 20], color_bonus_coef: [0; 20], } } pub fn coef(&self, nth_chain: usize) -> usize { score::calculate_rensa_bonus_coef(score::chain_bonus(nth_chain), self.long_bonus_coef[nth_chain], self.color_bonus_coef[nth_chain]) } } impl RensaTracker for RensaCoefTracker { fn
(&mut self, nth_chain: usize, num_erased: usize, long_bonus_coef: usize, color_bonus_coef: usize) { self.num_erased[nth_chain] = num_erased; self.long_bonus_coef[nth_chain] = long_bonus_coef; self.color_bonus_coef[nth_chain] = color_bonus_coef; } fn track_vanish(&mut self, _nth_chain: usize, _vanished: &FieldBit, _ojama_vanished: &FieldBit) {} fn track_drop(&mut self, _old_low_bits: u64, _old_high_bits: u64, _new_low_bits: u64, _new_high_bits: u64) {} } #[cfg(test)] mod tests { use super::RensaCoefTracker; use rensa_tracker::RensaTracker; #[test] fn test_score() { let mut tracker = RensaCoefTracker::new(); tracker.track_coef(1, 4, 0, 0); tracker.track_coef(2, 4, 0, 0); tracker.track_coef(3, 4, 0, 0); assert_eq!(4, tracker.num_erased[3]); assert_eq!(0, tracker.num_erased[4]); } } #[cfg(all(test, target_feature = "avx2", target_feature="bmi2"))] mod tests_for_avx2 { use super::RensaCoefTracker; use field::BitField; #[test] fn test_simulate() { let mut bf = BitField::from_str(concat!( "R...RR", "RGBRYR", "RRGBBY", "GGBYYR")); let mut tracker = RensaCoefTracker::new(); let rensa_result = bf.simulate_with_tracker(&mut tracker); assert_eq!(5, rensa_result.chain); assert_eq!(4, tracker.num_erased[1]); assert_eq!(4, tracker.num_erased[2]); assert_eq!(4, tracker.num_erased[3]); assert_eq!(4, tracker.num_erased[4]); assert_eq!(5, tracker.num_erased[5]); assert_eq!(1, tracker.coef(1)); assert_eq!(8, tracker.coef(2)); assert_eq!(16, tracker.coef(3)); assert_eq!(32, tracker.coef(4)); assert_eq!(64 + 2, tracker.coef(5)); } }
track_coef
identifier_name
mod.rs
#[derive(PartialEq, Debug)] pub enum BinaryType { ELF, COFF, PE, DOS, UNKNOWN, } pub fn detect(bytes: &[u8]) -> BinaryType { if scan_elf(bytes)
else { BinaryType::UNKNOWN } } // TODO: Can the other 12 bytes be utilized for more confirmation? fn scan_elf(bytes: &[u8]) -> bool { let ident: &[u8] = &bytes[0..15]; // [0x7F, 0x45, 0x4C, 0x46] = [0x7F, 'E', 'L', 'F'] ident[0..4] == [0x7F, 0x45, 0x4C, 0x46] } // fn scan_coff // fn scan_pe
{ BinaryType::ELF }
conditional_block
mod.rs
#[derive(PartialEq, Debug)] pub enum BinaryType { ELF, COFF, PE, DOS, UNKNOWN, } pub fn
(bytes: &[u8]) -> BinaryType { if scan_elf(bytes) { BinaryType::ELF } else { BinaryType::UNKNOWN } } // TODO: Can the other 12 bytes be utilized for more confirmation? fn scan_elf(bytes: &[u8]) -> bool { let ident: &[u8] = &bytes[0..15]; // [0x7F, 0x45, 0x4C, 0x46] = [0x7F, 'E', 'L', 'F'] ident[0..4] == [0x7F, 0x45, 0x4C, 0x46] } // fn scan_coff // fn scan_pe
detect
identifier_name
mod.rs
#[derive(PartialEq, Debug)] pub enum BinaryType { ELF, COFF, PE, DOS, UNKNOWN, } pub fn detect(bytes: &[u8]) -> BinaryType { if scan_elf(bytes) { BinaryType::ELF } else {
} } // TODO: Can the other 12 bytes be utilized for more confirmation? fn scan_elf(bytes: &[u8]) -> bool { let ident: &[u8] = &bytes[0..15]; // [0x7F, 0x45, 0x4C, 0x46] = [0x7F, 'E', 'L', 'F'] ident[0..4] == [0x7F, 0x45, 0x4C, 0x46] } // fn scan_coff // fn scan_pe
BinaryType::UNKNOWN
random_line_split
exp2f64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::exp2f64; use core::num::Float; use core::f64; // pub fn exp2f64(x: f64) -> f64; #[test] fn expf64_test1() { let x: f64 = f64::nan(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result.is_nan(), true); } #[test] fn
() { let x: f64 = f64::infinity(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, f64::infinity()); } #[test] fn expf64_test3() { let x: f64 = f64::neg_infinity(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, 0.0); } #[test] fn expf64_test4() { let x: f64 = 10.0; let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, 1024.0); } }
expf64_test2
identifier_name
exp2f64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::exp2f64; use core::num::Float; use core::f64; // pub fn exp2f64(x: f64) -> f64; #[test] fn expf64_test1() { let x: f64 = f64::nan(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result.is_nan(), true); } #[test] fn expf64_test2() { let x: f64 = f64::infinity(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, f64::infinity()); } #[test] fn expf64_test3()
#[test] fn expf64_test4() { let x: f64 = 10.0; let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, 1024.0); } }
{ let x: f64 = f64::neg_infinity(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, 0.0); }
identifier_body