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
texture_animator.rs
use resources::AnimatedTexture; use rand::{Rng, thread_rng}; use sfml::graphics::IntRect; pub struct TextureAnimator { n_frames: u32, step: i32, randomize: (bool, bool), tex_width: u32, current: u32, delay: f32, timer: f32, rect: IntRect, } impl TextureAnimator { pub fn new(anim_tex: &AnimatedTexture) -> TextureAnimator { let size = anim_tex.tex.size(); let mut t = TextureAnimator { n_frames: anim_tex.n_frames, step: (size.y / anim_tex.n_frames) as i32, randomize: anim_tex.randomize, tex_width: size.x, current: 0, delay: anim_tex.delay, timer: 0., rect: IntRect::new(0, 0, 1, 1), }; t.gen_rect(); t } pub fn update(&mut self, delta: f32) { self.timer += delta; if self.timer > self.delay { self.timer = 0.; self.gen_rect(); self.current += 1; if self.current > self.n_frames - 1 { self.current = 0; } } } pub fn texture_rect(&self) -> IntRect
fn gen_rect(&mut self) { let (left, width) = if self.randomize.0 && thread_rng().gen_weighted_bool(2) { (self.tex_width as i32, -(self.tex_width as i32)) } else { (0, self.tex_width as i32) }; let (top, height) = if self.randomize.1 && thread_rng().gen_weighted_bool(2) { ((self.current as i32 + 1) * self.step, -self.step) } else { (self.current as i32 * self.step, self.step) }; self.rect = IntRect::new(left, top, width, height); } /* pub fn n_frames(&self) -> u32 { self.n_frames } pub fn current(&self) -> u32 { self.current } */ }
{ self.rect }
identifier_body
texture_animator.rs
use resources::AnimatedTexture; use rand::{Rng, thread_rng}; use sfml::graphics::IntRect; pub struct TextureAnimator { n_frames: u32, step: i32, randomize: (bool, bool), tex_width: u32, current: u32, delay: f32, timer: f32, rect: IntRect, } impl TextureAnimator { pub fn new(anim_tex: &AnimatedTexture) -> TextureAnimator { let size = anim_tex.tex.size(); let mut t = TextureAnimator { n_frames: anim_tex.n_frames, step: (size.y / anim_tex.n_frames) as i32, randomize: anim_tex.randomize, tex_width: size.x, current: 0, delay: anim_tex.delay, timer: 0., rect: IntRect::new(0, 0, 1, 1), }; t.gen_rect(); t } pub fn update(&mut self, delta: f32) { self.timer += delta; if self.timer > self.delay { self.timer = 0.; self.gen_rect(); self.current += 1; if self.current > self.n_frames - 1 { self.current = 0; } } } pub fn
(&self) -> IntRect { self.rect } fn gen_rect(&mut self) { let (left, width) = if self.randomize.0 && thread_rng().gen_weighted_bool(2) { (self.tex_width as i32, -(self.tex_width as i32)) } else { (0, self.tex_width as i32) }; let (top, height) = if self.randomize.1 && thread_rng().gen_weighted_bool(2) { ((self.current as i32 + 1) * self.step, -self.step) } else { (self.current as i32 * self.step, self.step) }; self.rect = IntRect::new(left, top, width, height); } /* pub fn n_frames(&self) -> u32 { self.n_frames } pub fn current(&self) -> u32 { self.current } */ }
texture_rect
identifier_name
layout_debug.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/. */ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to make layout debugging easier. // for thread_local #![allow(unsafe_code)] use flow; use flow_ref::FlowRef; use rustc_serialize::json; use std::borrow::ToOwned; use std::cell::RefCell; use std::fs::File; use std::io::Write; #[cfg(debug_assertions)] use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; thread_local!(static STATE_KEY: RefCell<Option<State>> = RefCell::new(None)); #[cfg(debug_assertions)] static DEBUG_ID_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; pub struct Scope; #[macro_export] macro_rules! layout_debug_scope( ($($arg:tt)*) => ( if cfg!(debug_assertions) { layout_debug::Scope::new(format!($($arg)*)) } else { layout_debug::Scope } ) ); #[derive(RustcEncodable)] struct ScopeData { name: String, pre: String, post: String, children: Vec<Box<ScopeData>>, } impl ScopeData { fn new(name: String, pre: String) -> ScopeData { ScopeData { name: name, pre: pre, post: String::new(), children: vec!(), } } } struct State { flow_root: FlowRef, scope_stack: Vec<Box<ScopeData>>, } /// A layout debugging scope. The entire state of the flow tree /// will be output at the beginning and end of this scope. impl Scope { pub fn new(name: String) -> Scope { STATE_KEY.with(|ref r| { match *r.borrow_mut() { Some(ref mut state) => { let flow_trace = json::encode(&flow::base(&*state.flow_root)).unwrap(); let data = box ScopeData::new(name.clone(), flow_trace); state.scope_stack.push(data); } None => {} } }); Scope } } #[cfg(debug_assertions)] impl Drop for Scope { fn
(&mut self) { STATE_KEY.with(|ref r| { match *r.borrow_mut() { Some(ref mut state) => { let mut current_scope = state.scope_stack.pop().unwrap(); current_scope.post = json::encode(&flow::base(&*state.flow_root)).unwrap(); let previous_scope = state.scope_stack.last_mut().unwrap(); previous_scope.children.push(current_scope); } None => {} } }); } } /// Generate a unique ID. This is used for items such as Fragment /// which are often reallocated but represent essentially the /// same data. #[cfg(debug_assertions)] pub fn generate_unique_debug_id() -> u16 { DEBUG_ID_COUNTER.fetch_add(1, Ordering::SeqCst) as u16 } /// Begin a layout debug trace. If this has not been called, /// creating debug scopes has no effect. pub fn begin_trace(flow_root: FlowRef) { assert!(STATE_KEY.with(|ref r| r.borrow().is_none())); STATE_KEY.with(|ref r| { let flow_trace = json::encode(&flow::base(&*flow_root)).unwrap(); let state = State { scope_stack: vec![box ScopeData::new("root".to_owned(), flow_trace)], flow_root: flow_root.clone(), }; *r.borrow_mut() = Some(state); }); } /// End the debug layout trace. This will write the layout /// trace to disk in the current directory. The output /// file can then be viewed with an external tool. pub fn end_trace(generation: u32) { let mut thread_state = STATE_KEY.with(|ref r| r.borrow_mut().take().unwrap()); assert!(thread_state.scope_stack.len() == 1); let mut root_scope = thread_state.scope_stack.pop().unwrap(); root_scope.post = json::encode(&flow::base(&*thread_state.flow_root)).unwrap(); let result = json::encode(&root_scope).unwrap(); let mut file = File::create(format!("layout_trace-{}.json", generation)).unwrap(); file.write_all(result.as_bytes()).unwrap(); }
drop
identifier_name
layout_debug.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/. */ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to make layout debugging easier. // for thread_local #![allow(unsafe_code)] use flow; use flow_ref::FlowRef; use rustc_serialize::json; use std::borrow::ToOwned; use std::cell::RefCell; use std::fs::File; use std::io::Write; #[cfg(debug_assertions)] use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; thread_local!(static STATE_KEY: RefCell<Option<State>> = RefCell::new(None)); #[cfg(debug_assertions)] static DEBUG_ID_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; pub struct Scope; #[macro_export] macro_rules! layout_debug_scope( ($($arg:tt)*) => ( if cfg!(debug_assertions) { layout_debug::Scope::new(format!($($arg)*)) } else { layout_debug::Scope } ) ); #[derive(RustcEncodable)] struct ScopeData { name: String, pre: String, post: String, children: Vec<Box<ScopeData>>, } impl ScopeData { fn new(name: String, pre: String) -> ScopeData { ScopeData { name: name, pre: pre, post: String::new(), children: vec!(), } } } struct State { flow_root: FlowRef, scope_stack: Vec<Box<ScopeData>>, } /// A layout debugging scope. The entire state of the flow tree /// will be output at the beginning and end of this scope. impl Scope { pub fn new(name: String) -> Scope { STATE_KEY.with(|ref r| { match *r.borrow_mut() { Some(ref mut state) => { let flow_trace = json::encode(&flow::base(&*state.flow_root)).unwrap(); let data = box ScopeData::new(name.clone(), flow_trace); state.scope_stack.push(data); } None => {} } }); Scope } } #[cfg(debug_assertions)] impl Drop for Scope { fn drop(&mut self) { STATE_KEY.with(|ref r| { match *r.borrow_mut() { Some(ref mut state) =>
None => {} } }); } } /// Generate a unique ID. This is used for items such as Fragment /// which are often reallocated but represent essentially the /// same data. #[cfg(debug_assertions)] pub fn generate_unique_debug_id() -> u16 { DEBUG_ID_COUNTER.fetch_add(1, Ordering::SeqCst) as u16 } /// Begin a layout debug trace. If this has not been called, /// creating debug scopes has no effect. pub fn begin_trace(flow_root: FlowRef) { assert!(STATE_KEY.with(|ref r| r.borrow().is_none())); STATE_KEY.with(|ref r| { let flow_trace = json::encode(&flow::base(&*flow_root)).unwrap(); let state = State { scope_stack: vec![box ScopeData::new("root".to_owned(), flow_trace)], flow_root: flow_root.clone(), }; *r.borrow_mut() = Some(state); }); } /// End the debug layout trace. This will write the layout /// trace to disk in the current directory. The output /// file can then be viewed with an external tool. pub fn end_trace(generation: u32) { let mut thread_state = STATE_KEY.with(|ref r| r.borrow_mut().take().unwrap()); assert!(thread_state.scope_stack.len() == 1); let mut root_scope = thread_state.scope_stack.pop().unwrap(); root_scope.post = json::encode(&flow::base(&*thread_state.flow_root)).unwrap(); let result = json::encode(&root_scope).unwrap(); let mut file = File::create(format!("layout_trace-{}.json", generation)).unwrap(); file.write_all(result.as_bytes()).unwrap(); }
{ let mut current_scope = state.scope_stack.pop().unwrap(); current_scope.post = json::encode(&flow::base(&*state.flow_root)).unwrap(); let previous_scope = state.scope_stack.last_mut().unwrap(); previous_scope.children.push(current_scope); }
conditional_block
layout_debug.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/. */ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to make layout debugging easier. // for thread_local #![allow(unsafe_code)] use flow; use flow_ref::FlowRef; use rustc_serialize::json; use std::borrow::ToOwned; use std::cell::RefCell; use std::fs::File; use std::io::Write; #[cfg(debug_assertions)] use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; thread_local!(static STATE_KEY: RefCell<Option<State>> = RefCell::new(None)); #[cfg(debug_assertions)] static DEBUG_ID_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; pub struct Scope; #[macro_export] macro_rules! layout_debug_scope( ($($arg:tt)*) => ( if cfg!(debug_assertions) { layout_debug::Scope::new(format!($($arg)*)) } else { layout_debug::Scope } ) ); #[derive(RustcEncodable)] struct ScopeData { name: String, pre: String, post: String, children: Vec<Box<ScopeData>>, } impl ScopeData { fn new(name: String, pre: String) -> ScopeData { ScopeData { name: name, pre: pre, post: String::new(), children: vec!(), } } } struct State { flow_root: FlowRef, scope_stack: Vec<Box<ScopeData>>, } /// A layout debugging scope. The entire state of the flow tree /// will be output at the beginning and end of this scope. impl Scope { pub fn new(name: String) -> Scope { STATE_KEY.with(|ref r| { match *r.borrow_mut() { Some(ref mut state) => { let flow_trace = json::encode(&flow::base(&*state.flow_root)).unwrap(); let data = box ScopeData::new(name.clone(), flow_trace); state.scope_stack.push(data); } None => {} } }); Scope } }
impl Drop for Scope { fn drop(&mut self) { STATE_KEY.with(|ref r| { match *r.borrow_mut() { Some(ref mut state) => { let mut current_scope = state.scope_stack.pop().unwrap(); current_scope.post = json::encode(&flow::base(&*state.flow_root)).unwrap(); let previous_scope = state.scope_stack.last_mut().unwrap(); previous_scope.children.push(current_scope); } None => {} } }); } } /// Generate a unique ID. This is used for items such as Fragment /// which are often reallocated but represent essentially the /// same data. #[cfg(debug_assertions)] pub fn generate_unique_debug_id() -> u16 { DEBUG_ID_COUNTER.fetch_add(1, Ordering::SeqCst) as u16 } /// Begin a layout debug trace. If this has not been called, /// creating debug scopes has no effect. pub fn begin_trace(flow_root: FlowRef) { assert!(STATE_KEY.with(|ref r| r.borrow().is_none())); STATE_KEY.with(|ref r| { let flow_trace = json::encode(&flow::base(&*flow_root)).unwrap(); let state = State { scope_stack: vec![box ScopeData::new("root".to_owned(), flow_trace)], flow_root: flow_root.clone(), }; *r.borrow_mut() = Some(state); }); } /// End the debug layout trace. This will write the layout /// trace to disk in the current directory. The output /// file can then be viewed with an external tool. pub fn end_trace(generation: u32) { let mut thread_state = STATE_KEY.with(|ref r| r.borrow_mut().take().unwrap()); assert!(thread_state.scope_stack.len() == 1); let mut root_scope = thread_state.scope_stack.pop().unwrap(); root_scope.post = json::encode(&flow::base(&*thread_state.flow_root)).unwrap(); let result = json::encode(&root_scope).unwrap(); let mut file = File::create(format!("layout_trace-{}.json", generation)).unwrap(); file.write_all(result.as_bytes()).unwrap(); }
#[cfg(debug_assertions)]
random_line_split
pattern.rs
use std::sync::mpsc; use std::thread; use std::time::Duration; use dmx_output::DmxOutput; use error::Error; use types::{Runnable, SequenceData}; use utils; pub struct Pattern { data: SequenceData } impl Pattern { pub fn new(seq_path: String) -> Result<Pattern, Error> { // TODO check if path exists let data = try!(utils::load_sequence_data(&seq_path)); Ok(Pattern { data: data }) } } impl <D: DmxOutput> Runnable<D> for Pattern { /// Run the playlist item fn run(&mut self, dmx: &mut D) -> Result<(), Error>
// Output every frame for frame in rx { let d = &self.data.data[frame as usize]; match dmx.send(d) { Ok(_) => (), Err(e) => println!("\tError: {}", e), } } println!("Done."); Ok(()) } }
{ println!("Running pattern"); // Create channels for clock thread tx/rx let (tx, rx) = mpsc::channel(); // Spawn timer that ticks once per frame until all frames have been ticked let num_frames = self.data.num_frames; let frame_dur = self.data.frame_dur_ms as u64; let mut curr_frame = 0; thread::spawn(move || { while curr_frame != num_frames { // TODO maybe map the unwrap error to Error type tx.send(curr_frame).unwrap(); curr_frame += 1; thread::sleep(Duration::from_millis(frame_dur)); } });
identifier_body
pattern.rs
use std::sync::mpsc; use std::thread; use std::time::Duration; use dmx_output::DmxOutput; use error::Error; use types::{Runnable, SequenceData}; use utils; pub struct Pattern { data: SequenceData } impl Pattern { pub fn new(seq_path: String) -> Result<Pattern, Error> { // TODO check if path exists let data = try!(utils::load_sequence_data(&seq_path)); Ok(Pattern { data: data }) } } impl <D: DmxOutput> Runnable<D> for Pattern { /// Run the playlist item fn run(&mut self, dmx: &mut D) -> Result<(), Error> { println!("Running pattern"); // Create channels for clock thread tx/rx let (tx, rx) = mpsc::channel(); // Spawn timer that ticks once per frame until all frames have been ticked let num_frames = self.data.num_frames; let frame_dur = self.data.frame_dur_ms as u64; let mut curr_frame = 0; thread::spawn(move || { while curr_frame!= num_frames { // TODO maybe map the unwrap error to Error type tx.send(curr_frame).unwrap(); curr_frame += 1; thread::sleep(Duration::from_millis(frame_dur)); } }); // Output every frame for frame in rx { let d = &self.data.data[frame as usize]; match dmx.send(d) { Ok(_) => (), Err(e) => println!("\tError: {}", e),
println!("Done."); Ok(()) } }
} }
random_line_split
pattern.rs
use std::sync::mpsc; use std::thread; use std::time::Duration; use dmx_output::DmxOutput; use error::Error; use types::{Runnable, SequenceData}; use utils; pub struct Pattern { data: SequenceData } impl Pattern { pub fn new(seq_path: String) -> Result<Pattern, Error> { // TODO check if path exists let data = try!(utils::load_sequence_data(&seq_path)); Ok(Pattern { data: data }) } } impl <D: DmxOutput> Runnable<D> for Pattern { /// Run the playlist item fn
(&mut self, dmx: &mut D) -> Result<(), Error> { println!("Running pattern"); // Create channels for clock thread tx/rx let (tx, rx) = mpsc::channel(); // Spawn timer that ticks once per frame until all frames have been ticked let num_frames = self.data.num_frames; let frame_dur = self.data.frame_dur_ms as u64; let mut curr_frame = 0; thread::spawn(move || { while curr_frame!= num_frames { // TODO maybe map the unwrap error to Error type tx.send(curr_frame).unwrap(); curr_frame += 1; thread::sleep(Duration::from_millis(frame_dur)); } }); // Output every frame for frame in rx { let d = &self.data.data[frame as usize]; match dmx.send(d) { Ok(_) => (), Err(e) => println!("\tError: {}", e), } } println!("Done."); Ok(()) } }
run
identifier_name
paint.rs
//! Paint trait and implementations. use crate::canvas::Canvas; use lyon_path::PathEvent; /// A trait for types which can be represented on a `Canvas`. pub trait Paint { /// Paints self in the composition. fn paint(&self, canvas: &mut Canvas); } /// Paints a path with a fill pattern. pub struct Filled<D>(pub D); impl<P: Paint> Paint for Filled<P> { fn paint(&self, comp: &mut Canvas) { self.0.paint(comp); comp.fill(); } } /// Paints a path with a stroke. pub struct Stroked<D> { pub element: D, pub width: f32, } impl<P: Paint> Paint for Stroked<P> { fn
(&self, comp: &mut Canvas) { self.element.paint(comp); comp.set_stroke_width(self.width); comp.stroke(); } } impl<P> Paint for P where P: Iterator<Item = PathEvent> + Clone, { fn paint(&self, canvas: &mut Canvas) { self.clone().for_each(|p| match p { PathEvent::Line { to,.. } => canvas.line_to(to), PathEvent::Quadratic { ctrl, to,.. } => canvas.quadratic_to(ctrl, to), PathEvent::Cubic { ctrl1, ctrl2, to,.. } => canvas.cubic_to(ctrl1, ctrl2, to), PathEvent::Begin { at } => canvas.move_to(at), PathEvent::End { close,.. } if close => canvas.close_path(), _ => {} }); } }
paint
identifier_name
paint.rs
//! Paint trait and implementations. use crate::canvas::Canvas; use lyon_path::PathEvent; /// A trait for types which can be represented on a `Canvas`. pub trait Paint { /// Paints self in the composition. fn paint(&self, canvas: &mut Canvas); } /// Paints a path with a fill pattern. pub struct Filled<D>(pub D); impl<P: Paint> Paint for Filled<P> { fn paint(&self, comp: &mut Canvas) { self.0.paint(comp); comp.fill(); } } /// Paints a path with a stroke. pub struct Stroked<D> { pub element: D, pub width: f32, } impl<P: Paint> Paint for Stroked<P> { fn paint(&self, comp: &mut Canvas) { self.element.paint(comp); comp.set_stroke_width(self.width); comp.stroke(); } } impl<P> Paint for P where P: Iterator<Item = PathEvent> + Clone, { fn paint(&self, canvas: &mut Canvas) { self.clone().for_each(|p| match p { PathEvent::Line { to,.. } => canvas.line_to(to),
PathEvent::Quadratic { ctrl, to,.. } => canvas.quadratic_to(ctrl, to), PathEvent::Cubic { ctrl1, ctrl2, to,.. } => canvas.cubic_to(ctrl1, ctrl2, to), PathEvent::Begin { at } => canvas.move_to(at), PathEvent::End { close,.. } if close => canvas.close_path(), _ => {} }); } }
random_line_split
waveform_with_overlay.rs
use gtk::{cairo, pango, prelude::*}; use log::debug; use std::{ cell::RefCell, collections::Bound::Included, rc::Rc, sync::{Arc, Mutex}, }; use metadata::Duration; use renderers::{ImagePositions, SampleIndexRange, Timestamp, WaveformRenderer, BACKGROUND_COLOR}; use crate::info::{self, ChaptersBoundaries}; // Use this text to compute the largest text box for the waveform limits // This is required to position the labels in such a way they don't // move constantly depending on the digits width const LIMIT_TEXT_MN: &str = "00:00.000"; const LIMIT_TEXT_H: &str = "00:00:00.000"; const CURSOR_TEXT_MN: &str = "00:00.000.000"; const CURSOR_TEXT_H: &str = "00:00:00.000.000"; // Other UI components refresh period const OTHER_UI_REFRESH_PERIOD: Duration = Duration::from_millis(50); const ONE_HOUR: Duration = Duration::from_secs(60 * 60); #[derive(Default)] struct TextMetrics { font_family: Option<String>, font_size: f64, twice_font_size: f64, half_font_size: f64, limit_mn_width: f64, limit_h_width: f64, limit_y: f64, cursor_mn_width: f64, cursor_h_width: f64, cursor_y: f64, ref_lbl: Option<gtk::Label>, } impl TextMetrics { fn new(ref_lbl: gtk::Label) -> Self { TextMetrics { ref_lbl: Some(ref_lbl), ..Default::default() } } fn set_text_metrics(&mut self, cr: &cairo::Context) { // FIXME use Once for this match self.font_family { Some(ref family) => { cr.select_font_face(family, cairo::FontSlant::Normal, cairo::FontWeight::Normal); cr.set_font_size(self.font_size); } None => { // Get font specs from the reference label let ref_layout = self.ref_lbl.as_ref().unwrap().layout().unwrap(); let ref_ctx = ref_layout.context().unwrap(); let font_desc = ref_ctx.font_description().unwrap(); let family = font_desc.family().unwrap(); cr.select_font_face(&family, cairo::FontSlant::Normal, cairo::FontWeight::Normal); let font_size = f64::from(ref_layout.baseline() / pango::SCALE); cr.set_font_size(font_size); self.font_family = Some(family.to_string()); self.font_size = font_size; self.twice_font_size = 2f64 * font_size; self.half_font_size = 0.5f64 * font_size; self.limit_mn_width = cr.text_extents(LIMIT_TEXT_MN).unwrap().width; self.limit_h_width = cr.text_extents(LIMIT_TEXT_H).unwrap().width; self.limit_y = 2f64 * font_size; self.cursor_mn_width = cr.text_extents(CURSOR_TEXT_MN).unwrap().width; self.cursor_h_width = cr.text_extents(CURSOR_TEXT_H).unwrap().width; self.cursor_y = font_size; } } } } pub struct WaveformWithOverlay { waveform_renderer_mtx: Arc<Mutex<Box<WaveformRenderer>>>, text_metrics: TextMetrics, boundaries: Rc<RefCell<ChaptersBoundaries>>, positions: Rc<RefCell<ImagePositions>>, last_other_ui_refresh: Timestamp, } impl WaveformWithOverlay { pub fn new( waveform_renderer_mtx: &Arc<Mutex<Box<WaveformRenderer>>>, positions: &Rc<RefCell<ImagePositions>>, boundaries: &Rc<RefCell<ChaptersBoundaries>>, ref_lbl: &gtk::Label, ) -> Self { WaveformWithOverlay { waveform_renderer_mtx: Arc::clone(waveform_renderer_mtx), text_metrics: TextMetrics::new(ref_lbl.clone()), boundaries: Rc::clone(boundaries), positions: Rc::clone(positions), last_other_ui_refresh: Timestamp::default(), } } pub fn draw(&mut self, da: &gtk::DrawingArea, cr: &cairo::Context) { cr.set_source_rgb(BACKGROUND_COLOR.0, BACKGROUND_COLOR.1, BACKGROUND_COLOR.2); cr.paint().unwrap(); let (positions, state) = { let waveform_renderer = &mut *self.waveform_renderer_mtx.lock().unwrap(); // FIXME send an event? //self.playback_needs_refresh = waveform_renderer.playback_needs_refresh(); if let Err(err) = waveform_renderer.refresh() { if err.is_not_ready() { return; } else { panic!("{}", err); } } let (image, positions, state) = match waveform_renderer.image() { Some(image_and_positions) => image_and_positions, None => { debug!("draw got no image"); return; } }; image.with_surface_external_context(cr, |cr, surface| { cr.set_source_surface(surface, -positions.offset.x, 0f64) .unwrap(); cr.paint().unwrap(); }); (positions, state) }; cr.scale(1f64, 1f64); cr.set_source_rgb(1f64, 1f64, 0f64); self.text_metrics.set_text_metrics(cr); // first position let first_text = positions.offset.ts.for_humans().to_string(); let first_text_end = if positions.offset.ts < ONE_HOUR { 2f64 + self.text_metrics.limit_mn_width } else { 2f64 + self.text_metrics.limit_h_width }; cr.move_to(2f64, self.text_metrics.twice_font_size); cr.show_text(&first_text).unwrap(); // last position let last_text = positions.last.ts.for_humans().to_string(); let last_text_start = if positions.last.ts < ONE_HOUR { 2f64 + self.text_metrics.limit_mn_width } else { 2f64 + self.text_metrics.limit_h_width }; if positions.last.x - last_text_start > first_text_end + 5f64 { // last text won't overlap with first text cr.move_to( positions.last.x - last_text_start, self.text_metrics.twice_font_size, ); cr.show_text(&last_text).unwrap(); } // Draw in-range chapters boundaries let boundaries = self.boundaries.borrow(); let chapter_range = boundaries.range((Included(&positions.offset.ts), Included(&positions.last.ts))); let allocation = da.allocation(); let (area_width, area_height) = (allocation.width() as f64, allocation.width() as f64); cr.set_source_rgb(0.5f64, 0.6f64, 1f64); cr.set_line_width(1f64); let boundary_y0 = self.text_metrics.twice_font_size + 5f64; let text_base = allocation.height() as f64 - self.text_metrics.half_font_size; for (boundary, chapters) in chapter_range { if *boundary >= positions.offset.ts { let x = SampleIndexRange::from_duration( *boundary - positions.offset.ts, positions.sample_duration, ) .as_f64() / positions.sample_step; cr.move_to(x, boundary_y0); cr.line_to(x, area_height); cr.stroke().unwrap(); if let Some(ref prev_chapter) = chapters.prev { cr.move_to( x - 5f64 - cr.text_extents(&prev_chapter.title).unwrap().width, text_base, ); cr.show_text(&prev_chapter.title).unwrap(); } if let Some(ref next_chapter) = chapters.next { cr.move_to(x + 5f64, text_base); cr.show_text(&next_chapter.title).unwrap(); } } } if let Some(cursor) = &positions.cursor { // draw current pos cr.set_source_rgb(1f64, 1f64, 0f64); let cursor_text = cursor.ts.for_humans().with_micro().to_string(); let cursor_text_end = if cursor.ts < ONE_HOUR { 5f64 + self.text_metrics.cursor_mn_width } else { 5f64 + self.text_metrics.cursor_h_width }; let cursor_text_x = if cursor.x + cursor_text_end < area_width
else { cursor.x - cursor_text_end }; cr.move_to(cursor_text_x, self.text_metrics.font_size); cr.show_text(&cursor_text).unwrap(); cr.set_line_width(1f64); cr.move_to(cursor.x, 0f64); cr.line_to(cursor.x, area_height - self.text_metrics.twice_font_size); cr.stroke().unwrap(); let cursor_ts = cursor.ts; // update other UI position // Note: we go through the audio controller here in order // to reduce position queries on the ref gst element if!state.is_playing() || cursor.ts < self.last_other_ui_refresh || cursor.ts > self.last_other_ui_refresh + OTHER_UI_REFRESH_PERIOD { info::refresh(cursor_ts); self.last_other_ui_refresh = cursor_ts; } } *self.positions.borrow_mut() = positions; } }
{ cursor.x + 5f64 }
conditional_block
waveform_with_overlay.rs
use gtk::{cairo, pango, prelude::*}; use log::debug; use std::{ cell::RefCell, collections::Bound::Included, rc::Rc, sync::{Arc, Mutex}, }; use metadata::Duration; use renderers::{ImagePositions, SampleIndexRange, Timestamp, WaveformRenderer, BACKGROUND_COLOR}; use crate::info::{self, ChaptersBoundaries}; // Use this text to compute the largest text box for the waveform limits // This is required to position the labels in such a way they don't // move constantly depending on the digits width const LIMIT_TEXT_MN: &str = "00:00.000"; const LIMIT_TEXT_H: &str = "00:00:00.000"; const CURSOR_TEXT_MN: &str = "00:00.000.000"; const CURSOR_TEXT_H: &str = "00:00:00.000.000"; // Other UI components refresh period const OTHER_UI_REFRESH_PERIOD: Duration = Duration::from_millis(50); const ONE_HOUR: Duration = Duration::from_secs(60 * 60); #[derive(Default)] struct TextMetrics { font_family: Option<String>, font_size: f64, twice_font_size: f64, half_font_size: f64, limit_mn_width: f64, limit_h_width: f64, limit_y: f64, cursor_mn_width: f64, cursor_h_width: f64, cursor_y: f64, ref_lbl: Option<gtk::Label>, } impl TextMetrics { fn new(ref_lbl: gtk::Label) -> Self { TextMetrics { ref_lbl: Some(ref_lbl), ..Default::default() } } fn set_text_metrics(&mut self, cr: &cairo::Context) { // FIXME use Once for this match self.font_family { Some(ref family) => { cr.select_font_face(family, cairo::FontSlant::Normal, cairo::FontWeight::Normal); cr.set_font_size(self.font_size); } None => { // Get font specs from the reference label let ref_layout = self.ref_lbl.as_ref().unwrap().layout().unwrap(); let ref_ctx = ref_layout.context().unwrap(); let font_desc = ref_ctx.font_description().unwrap(); let family = font_desc.family().unwrap(); cr.select_font_face(&family, cairo::FontSlant::Normal, cairo::FontWeight::Normal); let font_size = f64::from(ref_layout.baseline() / pango::SCALE); cr.set_font_size(font_size); self.font_family = Some(family.to_string()); self.font_size = font_size; self.twice_font_size = 2f64 * font_size; self.half_font_size = 0.5f64 * font_size; self.limit_mn_width = cr.text_extents(LIMIT_TEXT_MN).unwrap().width; self.limit_h_width = cr.text_extents(LIMIT_TEXT_H).unwrap().width; self.limit_y = 2f64 * font_size;
} } } } pub struct WaveformWithOverlay { waveform_renderer_mtx: Arc<Mutex<Box<WaveformRenderer>>>, text_metrics: TextMetrics, boundaries: Rc<RefCell<ChaptersBoundaries>>, positions: Rc<RefCell<ImagePositions>>, last_other_ui_refresh: Timestamp, } impl WaveformWithOverlay { pub fn new( waveform_renderer_mtx: &Arc<Mutex<Box<WaveformRenderer>>>, positions: &Rc<RefCell<ImagePositions>>, boundaries: &Rc<RefCell<ChaptersBoundaries>>, ref_lbl: &gtk::Label, ) -> Self { WaveformWithOverlay { waveform_renderer_mtx: Arc::clone(waveform_renderer_mtx), text_metrics: TextMetrics::new(ref_lbl.clone()), boundaries: Rc::clone(boundaries), positions: Rc::clone(positions), last_other_ui_refresh: Timestamp::default(), } } pub fn draw(&mut self, da: &gtk::DrawingArea, cr: &cairo::Context) { cr.set_source_rgb(BACKGROUND_COLOR.0, BACKGROUND_COLOR.1, BACKGROUND_COLOR.2); cr.paint().unwrap(); let (positions, state) = { let waveform_renderer = &mut *self.waveform_renderer_mtx.lock().unwrap(); // FIXME send an event? //self.playback_needs_refresh = waveform_renderer.playback_needs_refresh(); if let Err(err) = waveform_renderer.refresh() { if err.is_not_ready() { return; } else { panic!("{}", err); } } let (image, positions, state) = match waveform_renderer.image() { Some(image_and_positions) => image_and_positions, None => { debug!("draw got no image"); return; } }; image.with_surface_external_context(cr, |cr, surface| { cr.set_source_surface(surface, -positions.offset.x, 0f64) .unwrap(); cr.paint().unwrap(); }); (positions, state) }; cr.scale(1f64, 1f64); cr.set_source_rgb(1f64, 1f64, 0f64); self.text_metrics.set_text_metrics(cr); // first position let first_text = positions.offset.ts.for_humans().to_string(); let first_text_end = if positions.offset.ts < ONE_HOUR { 2f64 + self.text_metrics.limit_mn_width } else { 2f64 + self.text_metrics.limit_h_width }; cr.move_to(2f64, self.text_metrics.twice_font_size); cr.show_text(&first_text).unwrap(); // last position let last_text = positions.last.ts.for_humans().to_string(); let last_text_start = if positions.last.ts < ONE_HOUR { 2f64 + self.text_metrics.limit_mn_width } else { 2f64 + self.text_metrics.limit_h_width }; if positions.last.x - last_text_start > first_text_end + 5f64 { // last text won't overlap with first text cr.move_to( positions.last.x - last_text_start, self.text_metrics.twice_font_size, ); cr.show_text(&last_text).unwrap(); } // Draw in-range chapters boundaries let boundaries = self.boundaries.borrow(); let chapter_range = boundaries.range((Included(&positions.offset.ts), Included(&positions.last.ts))); let allocation = da.allocation(); let (area_width, area_height) = (allocation.width() as f64, allocation.width() as f64); cr.set_source_rgb(0.5f64, 0.6f64, 1f64); cr.set_line_width(1f64); let boundary_y0 = self.text_metrics.twice_font_size + 5f64; let text_base = allocation.height() as f64 - self.text_metrics.half_font_size; for (boundary, chapters) in chapter_range { if *boundary >= positions.offset.ts { let x = SampleIndexRange::from_duration( *boundary - positions.offset.ts, positions.sample_duration, ) .as_f64() / positions.sample_step; cr.move_to(x, boundary_y0); cr.line_to(x, area_height); cr.stroke().unwrap(); if let Some(ref prev_chapter) = chapters.prev { cr.move_to( x - 5f64 - cr.text_extents(&prev_chapter.title).unwrap().width, text_base, ); cr.show_text(&prev_chapter.title).unwrap(); } if let Some(ref next_chapter) = chapters.next { cr.move_to(x + 5f64, text_base); cr.show_text(&next_chapter.title).unwrap(); } } } if let Some(cursor) = &positions.cursor { // draw current pos cr.set_source_rgb(1f64, 1f64, 0f64); let cursor_text = cursor.ts.for_humans().with_micro().to_string(); let cursor_text_end = if cursor.ts < ONE_HOUR { 5f64 + self.text_metrics.cursor_mn_width } else { 5f64 + self.text_metrics.cursor_h_width }; let cursor_text_x = if cursor.x + cursor_text_end < area_width { cursor.x + 5f64 } else { cursor.x - cursor_text_end }; cr.move_to(cursor_text_x, self.text_metrics.font_size); cr.show_text(&cursor_text).unwrap(); cr.set_line_width(1f64); cr.move_to(cursor.x, 0f64); cr.line_to(cursor.x, area_height - self.text_metrics.twice_font_size); cr.stroke().unwrap(); let cursor_ts = cursor.ts; // update other UI position // Note: we go through the audio controller here in order // to reduce position queries on the ref gst element if!state.is_playing() || cursor.ts < self.last_other_ui_refresh || cursor.ts > self.last_other_ui_refresh + OTHER_UI_REFRESH_PERIOD { info::refresh(cursor_ts); self.last_other_ui_refresh = cursor_ts; } } *self.positions.borrow_mut() = positions; } }
self.cursor_mn_width = cr.text_extents(CURSOR_TEXT_MN).unwrap().width; self.cursor_h_width = cr.text_extents(CURSOR_TEXT_H).unwrap().width; self.cursor_y = font_size;
random_line_split
waveform_with_overlay.rs
use gtk::{cairo, pango, prelude::*}; use log::debug; use std::{ cell::RefCell, collections::Bound::Included, rc::Rc, sync::{Arc, Mutex}, }; use metadata::Duration; use renderers::{ImagePositions, SampleIndexRange, Timestamp, WaveformRenderer, BACKGROUND_COLOR}; use crate::info::{self, ChaptersBoundaries}; // Use this text to compute the largest text box for the waveform limits // This is required to position the labels in such a way they don't // move constantly depending on the digits width const LIMIT_TEXT_MN: &str = "00:00.000"; const LIMIT_TEXT_H: &str = "00:00:00.000"; const CURSOR_TEXT_MN: &str = "00:00.000.000"; const CURSOR_TEXT_H: &str = "00:00:00.000.000"; // Other UI components refresh period const OTHER_UI_REFRESH_PERIOD: Duration = Duration::from_millis(50); const ONE_HOUR: Duration = Duration::from_secs(60 * 60); #[derive(Default)] struct TextMetrics { font_family: Option<String>, font_size: f64, twice_font_size: f64, half_font_size: f64, limit_mn_width: f64, limit_h_width: f64, limit_y: f64, cursor_mn_width: f64, cursor_h_width: f64, cursor_y: f64, ref_lbl: Option<gtk::Label>, } impl TextMetrics { fn new(ref_lbl: gtk::Label) -> Self { TextMetrics { ref_lbl: Some(ref_lbl), ..Default::default() } } fn set_text_metrics(&mut self, cr: &cairo::Context)
self.twice_font_size = 2f64 * font_size; self.half_font_size = 0.5f64 * font_size; self.limit_mn_width = cr.text_extents(LIMIT_TEXT_MN).unwrap().width; self.limit_h_width = cr.text_extents(LIMIT_TEXT_H).unwrap().width; self.limit_y = 2f64 * font_size; self.cursor_mn_width = cr.text_extents(CURSOR_TEXT_MN).unwrap().width; self.cursor_h_width = cr.text_extents(CURSOR_TEXT_H).unwrap().width; self.cursor_y = font_size; } } } } pub struct WaveformWithOverlay { waveform_renderer_mtx: Arc<Mutex<Box<WaveformRenderer>>>, text_metrics: TextMetrics, boundaries: Rc<RefCell<ChaptersBoundaries>>, positions: Rc<RefCell<ImagePositions>>, last_other_ui_refresh: Timestamp, } impl WaveformWithOverlay { pub fn new( waveform_renderer_mtx: &Arc<Mutex<Box<WaveformRenderer>>>, positions: &Rc<RefCell<ImagePositions>>, boundaries: &Rc<RefCell<ChaptersBoundaries>>, ref_lbl: &gtk::Label, ) -> Self { WaveformWithOverlay { waveform_renderer_mtx: Arc::clone(waveform_renderer_mtx), text_metrics: TextMetrics::new(ref_lbl.clone()), boundaries: Rc::clone(boundaries), positions: Rc::clone(positions), last_other_ui_refresh: Timestamp::default(), } } pub fn draw(&mut self, da: &gtk::DrawingArea, cr: &cairo::Context) { cr.set_source_rgb(BACKGROUND_COLOR.0, BACKGROUND_COLOR.1, BACKGROUND_COLOR.2); cr.paint().unwrap(); let (positions, state) = { let waveform_renderer = &mut *self.waveform_renderer_mtx.lock().unwrap(); // FIXME send an event? //self.playback_needs_refresh = waveform_renderer.playback_needs_refresh(); if let Err(err) = waveform_renderer.refresh() { if err.is_not_ready() { return; } else { panic!("{}", err); } } let (image, positions, state) = match waveform_renderer.image() { Some(image_and_positions) => image_and_positions, None => { debug!("draw got no image"); return; } }; image.with_surface_external_context(cr, |cr, surface| { cr.set_source_surface(surface, -positions.offset.x, 0f64) .unwrap(); cr.paint().unwrap(); }); (positions, state) }; cr.scale(1f64, 1f64); cr.set_source_rgb(1f64, 1f64, 0f64); self.text_metrics.set_text_metrics(cr); // first position let first_text = positions.offset.ts.for_humans().to_string(); let first_text_end = if positions.offset.ts < ONE_HOUR { 2f64 + self.text_metrics.limit_mn_width } else { 2f64 + self.text_metrics.limit_h_width }; cr.move_to(2f64, self.text_metrics.twice_font_size); cr.show_text(&first_text).unwrap(); // last position let last_text = positions.last.ts.for_humans().to_string(); let last_text_start = if positions.last.ts < ONE_HOUR { 2f64 + self.text_metrics.limit_mn_width } else { 2f64 + self.text_metrics.limit_h_width }; if positions.last.x - last_text_start > first_text_end + 5f64 { // last text won't overlap with first text cr.move_to( positions.last.x - last_text_start, self.text_metrics.twice_font_size, ); cr.show_text(&last_text).unwrap(); } // Draw in-range chapters boundaries let boundaries = self.boundaries.borrow(); let chapter_range = boundaries.range((Included(&positions.offset.ts), Included(&positions.last.ts))); let allocation = da.allocation(); let (area_width, area_height) = (allocation.width() as f64, allocation.width() as f64); cr.set_source_rgb(0.5f64, 0.6f64, 1f64); cr.set_line_width(1f64); let boundary_y0 = self.text_metrics.twice_font_size + 5f64; let text_base = allocation.height() as f64 - self.text_metrics.half_font_size; for (boundary, chapters) in chapter_range { if *boundary >= positions.offset.ts { let x = SampleIndexRange::from_duration( *boundary - positions.offset.ts, positions.sample_duration, ) .as_f64() / positions.sample_step; cr.move_to(x, boundary_y0); cr.line_to(x, area_height); cr.stroke().unwrap(); if let Some(ref prev_chapter) = chapters.prev { cr.move_to( x - 5f64 - cr.text_extents(&prev_chapter.title).unwrap().width, text_base, ); cr.show_text(&prev_chapter.title).unwrap(); } if let Some(ref next_chapter) = chapters.next { cr.move_to(x + 5f64, text_base); cr.show_text(&next_chapter.title).unwrap(); } } } if let Some(cursor) = &positions.cursor { // draw current pos cr.set_source_rgb(1f64, 1f64, 0f64); let cursor_text = cursor.ts.for_humans().with_micro().to_string(); let cursor_text_end = if cursor.ts < ONE_HOUR { 5f64 + self.text_metrics.cursor_mn_width } else { 5f64 + self.text_metrics.cursor_h_width }; let cursor_text_x = if cursor.x + cursor_text_end < area_width { cursor.x + 5f64 } else { cursor.x - cursor_text_end }; cr.move_to(cursor_text_x, self.text_metrics.font_size); cr.show_text(&cursor_text).unwrap(); cr.set_line_width(1f64); cr.move_to(cursor.x, 0f64); cr.line_to(cursor.x, area_height - self.text_metrics.twice_font_size); cr.stroke().unwrap(); let cursor_ts = cursor.ts; // update other UI position // Note: we go through the audio controller here in order // to reduce position queries on the ref gst element if!state.is_playing() || cursor.ts < self.last_other_ui_refresh || cursor.ts > self.last_other_ui_refresh + OTHER_UI_REFRESH_PERIOD { info::refresh(cursor_ts); self.last_other_ui_refresh = cursor_ts; } } *self.positions.borrow_mut() = positions; } }
{ // FIXME use Once for this match self.font_family { Some(ref family) => { cr.select_font_face(family, cairo::FontSlant::Normal, cairo::FontWeight::Normal); cr.set_font_size(self.font_size); } None => { // Get font specs from the reference label let ref_layout = self.ref_lbl.as_ref().unwrap().layout().unwrap(); let ref_ctx = ref_layout.context().unwrap(); let font_desc = ref_ctx.font_description().unwrap(); let family = font_desc.family().unwrap(); cr.select_font_face(&family, cairo::FontSlant::Normal, cairo::FontWeight::Normal); let font_size = f64::from(ref_layout.baseline() / pango::SCALE); cr.set_font_size(font_size); self.font_family = Some(family.to_string()); self.font_size = font_size;
identifier_body
waveform_with_overlay.rs
use gtk::{cairo, pango, prelude::*}; use log::debug; use std::{ cell::RefCell, collections::Bound::Included, rc::Rc, sync::{Arc, Mutex}, }; use metadata::Duration; use renderers::{ImagePositions, SampleIndexRange, Timestamp, WaveformRenderer, BACKGROUND_COLOR}; use crate::info::{self, ChaptersBoundaries}; // Use this text to compute the largest text box for the waveform limits // This is required to position the labels in such a way they don't // move constantly depending on the digits width const LIMIT_TEXT_MN: &str = "00:00.000"; const LIMIT_TEXT_H: &str = "00:00:00.000"; const CURSOR_TEXT_MN: &str = "00:00.000.000"; const CURSOR_TEXT_H: &str = "00:00:00.000.000"; // Other UI components refresh period const OTHER_UI_REFRESH_PERIOD: Duration = Duration::from_millis(50); const ONE_HOUR: Duration = Duration::from_secs(60 * 60); #[derive(Default)] struct TextMetrics { font_family: Option<String>, font_size: f64, twice_font_size: f64, half_font_size: f64, limit_mn_width: f64, limit_h_width: f64, limit_y: f64, cursor_mn_width: f64, cursor_h_width: f64, cursor_y: f64, ref_lbl: Option<gtk::Label>, } impl TextMetrics { fn new(ref_lbl: gtk::Label) -> Self { TextMetrics { ref_lbl: Some(ref_lbl), ..Default::default() } } fn set_text_metrics(&mut self, cr: &cairo::Context) { // FIXME use Once for this match self.font_family { Some(ref family) => { cr.select_font_face(family, cairo::FontSlant::Normal, cairo::FontWeight::Normal); cr.set_font_size(self.font_size); } None => { // Get font specs from the reference label let ref_layout = self.ref_lbl.as_ref().unwrap().layout().unwrap(); let ref_ctx = ref_layout.context().unwrap(); let font_desc = ref_ctx.font_description().unwrap(); let family = font_desc.family().unwrap(); cr.select_font_face(&family, cairo::FontSlant::Normal, cairo::FontWeight::Normal); let font_size = f64::from(ref_layout.baseline() / pango::SCALE); cr.set_font_size(font_size); self.font_family = Some(family.to_string()); self.font_size = font_size; self.twice_font_size = 2f64 * font_size; self.half_font_size = 0.5f64 * font_size; self.limit_mn_width = cr.text_extents(LIMIT_TEXT_MN).unwrap().width; self.limit_h_width = cr.text_extents(LIMIT_TEXT_H).unwrap().width; self.limit_y = 2f64 * font_size; self.cursor_mn_width = cr.text_extents(CURSOR_TEXT_MN).unwrap().width; self.cursor_h_width = cr.text_extents(CURSOR_TEXT_H).unwrap().width; self.cursor_y = font_size; } } } } pub struct WaveformWithOverlay { waveform_renderer_mtx: Arc<Mutex<Box<WaveformRenderer>>>, text_metrics: TextMetrics, boundaries: Rc<RefCell<ChaptersBoundaries>>, positions: Rc<RefCell<ImagePositions>>, last_other_ui_refresh: Timestamp, } impl WaveformWithOverlay { pub fn new( waveform_renderer_mtx: &Arc<Mutex<Box<WaveformRenderer>>>, positions: &Rc<RefCell<ImagePositions>>, boundaries: &Rc<RefCell<ChaptersBoundaries>>, ref_lbl: &gtk::Label, ) -> Self { WaveformWithOverlay { waveform_renderer_mtx: Arc::clone(waveform_renderer_mtx), text_metrics: TextMetrics::new(ref_lbl.clone()), boundaries: Rc::clone(boundaries), positions: Rc::clone(positions), last_other_ui_refresh: Timestamp::default(), } } pub fn
(&mut self, da: &gtk::DrawingArea, cr: &cairo::Context) { cr.set_source_rgb(BACKGROUND_COLOR.0, BACKGROUND_COLOR.1, BACKGROUND_COLOR.2); cr.paint().unwrap(); let (positions, state) = { let waveform_renderer = &mut *self.waveform_renderer_mtx.lock().unwrap(); // FIXME send an event? //self.playback_needs_refresh = waveform_renderer.playback_needs_refresh(); if let Err(err) = waveform_renderer.refresh() { if err.is_not_ready() { return; } else { panic!("{}", err); } } let (image, positions, state) = match waveform_renderer.image() { Some(image_and_positions) => image_and_positions, None => { debug!("draw got no image"); return; } }; image.with_surface_external_context(cr, |cr, surface| { cr.set_source_surface(surface, -positions.offset.x, 0f64) .unwrap(); cr.paint().unwrap(); }); (positions, state) }; cr.scale(1f64, 1f64); cr.set_source_rgb(1f64, 1f64, 0f64); self.text_metrics.set_text_metrics(cr); // first position let first_text = positions.offset.ts.for_humans().to_string(); let first_text_end = if positions.offset.ts < ONE_HOUR { 2f64 + self.text_metrics.limit_mn_width } else { 2f64 + self.text_metrics.limit_h_width }; cr.move_to(2f64, self.text_metrics.twice_font_size); cr.show_text(&first_text).unwrap(); // last position let last_text = positions.last.ts.for_humans().to_string(); let last_text_start = if positions.last.ts < ONE_HOUR { 2f64 + self.text_metrics.limit_mn_width } else { 2f64 + self.text_metrics.limit_h_width }; if positions.last.x - last_text_start > first_text_end + 5f64 { // last text won't overlap with first text cr.move_to( positions.last.x - last_text_start, self.text_metrics.twice_font_size, ); cr.show_text(&last_text).unwrap(); } // Draw in-range chapters boundaries let boundaries = self.boundaries.borrow(); let chapter_range = boundaries.range((Included(&positions.offset.ts), Included(&positions.last.ts))); let allocation = da.allocation(); let (area_width, area_height) = (allocation.width() as f64, allocation.width() as f64); cr.set_source_rgb(0.5f64, 0.6f64, 1f64); cr.set_line_width(1f64); let boundary_y0 = self.text_metrics.twice_font_size + 5f64; let text_base = allocation.height() as f64 - self.text_metrics.half_font_size; for (boundary, chapters) in chapter_range { if *boundary >= positions.offset.ts { let x = SampleIndexRange::from_duration( *boundary - positions.offset.ts, positions.sample_duration, ) .as_f64() / positions.sample_step; cr.move_to(x, boundary_y0); cr.line_to(x, area_height); cr.stroke().unwrap(); if let Some(ref prev_chapter) = chapters.prev { cr.move_to( x - 5f64 - cr.text_extents(&prev_chapter.title).unwrap().width, text_base, ); cr.show_text(&prev_chapter.title).unwrap(); } if let Some(ref next_chapter) = chapters.next { cr.move_to(x + 5f64, text_base); cr.show_text(&next_chapter.title).unwrap(); } } } if let Some(cursor) = &positions.cursor { // draw current pos cr.set_source_rgb(1f64, 1f64, 0f64); let cursor_text = cursor.ts.for_humans().with_micro().to_string(); let cursor_text_end = if cursor.ts < ONE_HOUR { 5f64 + self.text_metrics.cursor_mn_width } else { 5f64 + self.text_metrics.cursor_h_width }; let cursor_text_x = if cursor.x + cursor_text_end < area_width { cursor.x + 5f64 } else { cursor.x - cursor_text_end }; cr.move_to(cursor_text_x, self.text_metrics.font_size); cr.show_text(&cursor_text).unwrap(); cr.set_line_width(1f64); cr.move_to(cursor.x, 0f64); cr.line_to(cursor.x, area_height - self.text_metrics.twice_font_size); cr.stroke().unwrap(); let cursor_ts = cursor.ts; // update other UI position // Note: we go through the audio controller here in order // to reduce position queries on the ref gst element if!state.is_playing() || cursor.ts < self.last_other_ui_refresh || cursor.ts > self.last_other_ui_refresh + OTHER_UI_REFRESH_PERIOD { info::refresh(cursor_ts); self.last_other_ui_refresh = cursor_ts; } } *self.positions.borrow_mut() = positions; } }
draw
identifier_name
dialog.rs
use std::collections::HashMap; use std::boxed::Box; use core::position::{Size, HasSize}; use core::cellbuffer::CellAccessor; use ui::core::{ Alignable, HorizontalAlign, VerticalAlign, Widget, Frame, Button, ButtonResult, Layout, Painter }; use ui::label::Label; /// Pack labels, buttons and other widgets into dialogs /// /// # Examples /// /// ``` /// use rustty::ui::core::{VerticalAlign, HorizontalAlign, ButtonResult, Widget}; /// use rustty::ui::{Dialog, StdButton}; /// /// let mut maindlg = Dialog::new(60, 10); /// /// let mut b1 = StdButton::new("Quit", 'q', ButtonResult::Ok); /// b1.pack(&maindlg, HorizontalAlign::Left, VerticalAlign::Middle, (1,1)); /// /// maindlg.draw_box(); /// // draw to terminal /// // maindlg.draw(&mut term); /// ``` /// pub struct Dialog { frame: Frame, buttons: Vec<Box<Button>>, layouts: Vec<Box<Layout>>, accel2result: HashMap<char, ButtonResult>, } impl Dialog { /// Construct a new Dialog widget `cols` wide by `rows` high. /// /// # Examples /// /// ``` /// use rustty::ui::Dialog; /// /// let mut maindlg = Dialog::new(60, 10); /// ``` pub fn new(cols: usize, rows: usize) -> Dialog { Dialog { frame: Frame::new(cols, rows), buttons: Vec::new(), layouts: Vec::new(), accel2result: HashMap::new(), } } /// Add an existing widget that implements the [Button](core/button/trait.Button.html) /// trait. /// /// # Examples /// /// ``` /// use rustty::ui::core::{Widget, ButtonResult, HorizontalAlign, VerticalAlign}; /// use rustty::ui::{Dialog, StdButton}; /// let mut maindlg = Dialog::new(60, 10); /// /// let mut b1 = StdButton::new("Quit", 'q', ButtonResult::Ok); /// b1.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (1,1)); /// maindlg.add_button(b1); /// ``` pub fn add_button<T: Button +'static>(&mut self, button: T) { self.accel2result.insert(button.accel(), button.result()); self.buttons.push(Box::new(button)); self.buttons.last_mut().unwrap().draw(&mut self.frame); } /// Add an existing widget that implements the [Layout](core/layout/trait.Layout.html) /// trait. **NEEDS A REWORK**, the way of passing in a vector of buttons is ugly and a /// very bad API. /// /// # Examples /// /// ``` /// use rustty::ui::core::{HorizontalAlign, VerticalAlign, ButtonResult, Button, Widget}; /// use rustty::ui::{Dialog, StdButton, VerticalLayout}; /// /// let mut maindlg = Dialog::new(60, 10); /// let b1 = StdButton::new("Foo", 'f', ButtonResult::Ok); /// let b2 = StdButton::new("Bar", 'b', ButtonResult::Cancel); /// /// let vec = vec![b1, b2].into_iter().map(Box::new).map(|x| x as Box<Button>).collect(); /// let mut vlayout = VerticalLayout::from_vec(vec, 0); /// vlayout.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (0,0)); /// /// maindlg.add_layout(vlayout); /// ``` /// pub fn add_layout<T: Layout +'static>(&mut self, layout: T) { self.layouts.push(Box::new(layout)); self.layouts.last_mut().unwrap().align_elems(); self.layouts.last_mut().unwrap().frame().draw_into(&mut self.frame); self.layouts.last_mut().unwrap().forward_keys(&mut self.accel2result); } /// Add an existing label that contains some text. /// /// # Examples /// /// ``` /// use rustty::ui::core::{HorizontalAlign, VerticalAlign, Widget}; /// use rustty::ui::{Dialog, Label}; /// /// let mut maindlg = Dialog::new(60, 10); /// let mut lbl = Label::from_str("Foo"); /// lbl.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (0,0)); /// /// maindlg.add_label(lbl); /// ``` /// pub fn add_label(&mut self, mut label: Label) { label.draw(&mut self.frame); } /// Change the state of an existing CheckButton, if any exists, /// within the dialog. If an invalid button result is given, the /// function will panic. *Note* StdButtons are still valid handles /// for this function, however they will not actually do anything. /// This function is for buttons that perform some action upon being /// pressed. /// /// # Examples /// /// ```ignore /// // match character for dialog /// match dialog.result_for_key(ch) { /// Some(ButtonResult::Ok) => { /// dialog.button_pressed(ButtonResult::Custom(i)); /// // do stuff... /// }, /// _ => { } /// } /// ``` /// pub fn button_pressed(&mut self, res: ButtonResult) { match self.buttons.iter_mut().find(|x| x.result() == res) { Some(i) => { i.pressed(); i.draw(&mut self.frame)} _ => { panic!("Not a valid button result for\ Dialog::button_checked()"); } } } /// For buttons that have a state manager, this function will return /// the current state of the button. *CheckButton* for example uses /// a state to manage whether the button is checked, different actions /// can be taken depending on the state once read. /// /// # Examples /// /// ```ignore /// // match character for dialog /// match dialog.result_for_key(ch) { /// Some(ButtonResult::Ok) => { /// dialog.button_pressed(ButtonResult::Custom(i)); /// if dialog.is_button_pressed(ButtonResult::Custom(i)) { /// // do... /// } else { /// // do else... /// } /// }, /// _ => { } /// } /// ``` /// pub fn is_button_pressed(&self, res: ButtonResult) -> bool { match self.buttons.iter().find(|x| x.result() == res) { Some(i) => i.state(), _ => panic!("Not a valid button result for\ Dialog::is_button_checked()") } } /// Checks whether the char passed is a valid key for any buttons currently /// drawn within the dialog, if so the corresponding `ButtonResult` is returned pub fn result_for_key(&self, key: char) -> Option<ButtonResult> { match self.accel2result.get(&key.to_lowercase().next().unwrap_or(key)) { Some(r) => Some(*r), None => None, } } } impl Widget for Dialog { fn draw(&mut self, parent: &mut CellAccessor) { self.frame.draw_into(parent); } fn pack(&mut self, parent: &HasSize, halign: HorizontalAlign, valign: VerticalAlign, margin: (usize, usize)) { self.frame.align(parent, halign, valign, margin); } fn draw_box(&mut self) { self.frame.draw_box(); } fn resize(&mut self, new_size: Size) { self.frame.resize(new_size); } fn frame(&self) -> &Frame {
&self.frame } fn frame_mut(&mut self) -> &mut Frame { &mut self.frame } } impl HasSize for Dialog { fn size(&self) -> Size { self.frame.size() } }
random_line_split
dialog.rs
use std::collections::HashMap; use std::boxed::Box; use core::position::{Size, HasSize}; use core::cellbuffer::CellAccessor; use ui::core::{ Alignable, HorizontalAlign, VerticalAlign, Widget, Frame, Button, ButtonResult, Layout, Painter }; use ui::label::Label; /// Pack labels, buttons and other widgets into dialogs /// /// # Examples /// /// ``` /// use rustty::ui::core::{VerticalAlign, HorizontalAlign, ButtonResult, Widget}; /// use rustty::ui::{Dialog, StdButton}; /// /// let mut maindlg = Dialog::new(60, 10); /// /// let mut b1 = StdButton::new("Quit", 'q', ButtonResult::Ok); /// b1.pack(&maindlg, HorizontalAlign::Left, VerticalAlign::Middle, (1,1)); /// /// maindlg.draw_box(); /// // draw to terminal /// // maindlg.draw(&mut term); /// ``` /// pub struct Dialog { frame: Frame, buttons: Vec<Box<Button>>, layouts: Vec<Box<Layout>>, accel2result: HashMap<char, ButtonResult>, } impl Dialog { /// Construct a new Dialog widget `cols` wide by `rows` high. /// /// # Examples /// /// ``` /// use rustty::ui::Dialog; /// /// let mut maindlg = Dialog::new(60, 10); /// ``` pub fn new(cols: usize, rows: usize) -> Dialog { Dialog { frame: Frame::new(cols, rows), buttons: Vec::new(), layouts: Vec::new(), accel2result: HashMap::new(), } } /// Add an existing widget that implements the [Button](core/button/trait.Button.html) /// trait. /// /// # Examples /// /// ``` /// use rustty::ui::core::{Widget, ButtonResult, HorizontalAlign, VerticalAlign}; /// use rustty::ui::{Dialog, StdButton}; /// let mut maindlg = Dialog::new(60, 10); /// /// let mut b1 = StdButton::new("Quit", 'q', ButtonResult::Ok); /// b1.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (1,1)); /// maindlg.add_button(b1); /// ``` pub fn add_button<T: Button +'static>(&mut self, button: T) { self.accel2result.insert(button.accel(), button.result()); self.buttons.push(Box::new(button)); self.buttons.last_mut().unwrap().draw(&mut self.frame); } /// Add an existing widget that implements the [Layout](core/layout/trait.Layout.html) /// trait. **NEEDS A REWORK**, the way of passing in a vector of buttons is ugly and a /// very bad API. /// /// # Examples /// /// ``` /// use rustty::ui::core::{HorizontalAlign, VerticalAlign, ButtonResult, Button, Widget}; /// use rustty::ui::{Dialog, StdButton, VerticalLayout}; /// /// let mut maindlg = Dialog::new(60, 10); /// let b1 = StdButton::new("Foo", 'f', ButtonResult::Ok); /// let b2 = StdButton::new("Bar", 'b', ButtonResult::Cancel); /// /// let vec = vec![b1, b2].into_iter().map(Box::new).map(|x| x as Box<Button>).collect(); /// let mut vlayout = VerticalLayout::from_vec(vec, 0); /// vlayout.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (0,0)); /// /// maindlg.add_layout(vlayout); /// ``` /// pub fn add_layout<T: Layout +'static>(&mut self, layout: T) { self.layouts.push(Box::new(layout)); self.layouts.last_mut().unwrap().align_elems(); self.layouts.last_mut().unwrap().frame().draw_into(&mut self.frame); self.layouts.last_mut().unwrap().forward_keys(&mut self.accel2result); } /// Add an existing label that contains some text. /// /// # Examples /// /// ``` /// use rustty::ui::core::{HorizontalAlign, VerticalAlign, Widget}; /// use rustty::ui::{Dialog, Label}; /// /// let mut maindlg = Dialog::new(60, 10); /// let mut lbl = Label::from_str("Foo"); /// lbl.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (0,0)); /// /// maindlg.add_label(lbl); /// ``` /// pub fn add_label(&mut self, mut label: Label) { label.draw(&mut self.frame); } /// Change the state of an existing CheckButton, if any exists, /// within the dialog. If an invalid button result is given, the /// function will panic. *Note* StdButtons are still valid handles /// for this function, however they will not actually do anything. /// This function is for buttons that perform some action upon being /// pressed. /// /// # Examples /// /// ```ignore /// // match character for dialog /// match dialog.result_for_key(ch) { /// Some(ButtonResult::Ok) => { /// dialog.button_pressed(ButtonResult::Custom(i)); /// // do stuff... /// }, /// _ => { } /// } /// ``` /// pub fn button_pressed(&mut self, res: ButtonResult) { match self.buttons.iter_mut().find(|x| x.result() == res) { Some(i) => { i.pressed(); i.draw(&mut self.frame)} _ => { panic!("Not a valid button result for\ Dialog::button_checked()"); } } } /// For buttons that have a state manager, this function will return /// the current state of the button. *CheckButton* for example uses /// a state to manage whether the button is checked, different actions /// can be taken depending on the state once read. /// /// # Examples /// /// ```ignore /// // match character for dialog /// match dialog.result_for_key(ch) { /// Some(ButtonResult::Ok) => { /// dialog.button_pressed(ButtonResult::Custom(i)); /// if dialog.is_button_pressed(ButtonResult::Custom(i)) { /// // do... /// } else { /// // do else... /// } /// }, /// _ => { } /// } /// ``` /// pub fn is_button_pressed(&self, res: ButtonResult) -> bool { match self.buttons.iter().find(|x| x.result() == res) { Some(i) => i.state(), _ => panic!("Not a valid button result for\ Dialog::is_button_checked()") } } /// Checks whether the char passed is a valid key for any buttons currently /// drawn within the dialog, if so the corresponding `ButtonResult` is returned pub fn result_for_key(&self, key: char) -> Option<ButtonResult> { match self.accel2result.get(&key.to_lowercase().next().unwrap_or(key)) { Some(r) => Some(*r), None => None, } } } impl Widget for Dialog { fn draw(&mut self, parent: &mut CellAccessor) { self.frame.draw_into(parent); } fn
(&mut self, parent: &HasSize, halign: HorizontalAlign, valign: VerticalAlign, margin: (usize, usize)) { self.frame.align(parent, halign, valign, margin); } fn draw_box(&mut self) { self.frame.draw_box(); } fn resize(&mut self, new_size: Size) { self.frame.resize(new_size); } fn frame(&self) -> &Frame { &self.frame } fn frame_mut(&mut self) -> &mut Frame { &mut self.frame } } impl HasSize for Dialog { fn size(&self) -> Size { self.frame.size() } }
pack
identifier_name
dialog.rs
use std::collections::HashMap; use std::boxed::Box; use core::position::{Size, HasSize}; use core::cellbuffer::CellAccessor; use ui::core::{ Alignable, HorizontalAlign, VerticalAlign, Widget, Frame, Button, ButtonResult, Layout, Painter }; use ui::label::Label; /// Pack labels, buttons and other widgets into dialogs /// /// # Examples /// /// ``` /// use rustty::ui::core::{VerticalAlign, HorizontalAlign, ButtonResult, Widget}; /// use rustty::ui::{Dialog, StdButton}; /// /// let mut maindlg = Dialog::new(60, 10); /// /// let mut b1 = StdButton::new("Quit", 'q', ButtonResult::Ok); /// b1.pack(&maindlg, HorizontalAlign::Left, VerticalAlign::Middle, (1,1)); /// /// maindlg.draw_box(); /// // draw to terminal /// // maindlg.draw(&mut term); /// ``` /// pub struct Dialog { frame: Frame, buttons: Vec<Box<Button>>, layouts: Vec<Box<Layout>>, accel2result: HashMap<char, ButtonResult>, } impl Dialog { /// Construct a new Dialog widget `cols` wide by `rows` high. /// /// # Examples /// /// ``` /// use rustty::ui::Dialog; /// /// let mut maindlg = Dialog::new(60, 10); /// ``` pub fn new(cols: usize, rows: usize) -> Dialog { Dialog { frame: Frame::new(cols, rows), buttons: Vec::new(), layouts: Vec::new(), accel2result: HashMap::new(), } } /// Add an existing widget that implements the [Button](core/button/trait.Button.html) /// trait. /// /// # Examples /// /// ``` /// use rustty::ui::core::{Widget, ButtonResult, HorizontalAlign, VerticalAlign}; /// use rustty::ui::{Dialog, StdButton}; /// let mut maindlg = Dialog::new(60, 10); /// /// let mut b1 = StdButton::new("Quit", 'q', ButtonResult::Ok); /// b1.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (1,1)); /// maindlg.add_button(b1); /// ``` pub fn add_button<T: Button +'static>(&mut self, button: T) { self.accel2result.insert(button.accel(), button.result()); self.buttons.push(Box::new(button)); self.buttons.last_mut().unwrap().draw(&mut self.frame); } /// Add an existing widget that implements the [Layout](core/layout/trait.Layout.html) /// trait. **NEEDS A REWORK**, the way of passing in a vector of buttons is ugly and a /// very bad API. /// /// # Examples /// /// ``` /// use rustty::ui::core::{HorizontalAlign, VerticalAlign, ButtonResult, Button, Widget}; /// use rustty::ui::{Dialog, StdButton, VerticalLayout}; /// /// let mut maindlg = Dialog::new(60, 10); /// let b1 = StdButton::new("Foo", 'f', ButtonResult::Ok); /// let b2 = StdButton::new("Bar", 'b', ButtonResult::Cancel); /// /// let vec = vec![b1, b2].into_iter().map(Box::new).map(|x| x as Box<Button>).collect(); /// let mut vlayout = VerticalLayout::from_vec(vec, 0); /// vlayout.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (0,0)); /// /// maindlg.add_layout(vlayout); /// ``` /// pub fn add_layout<T: Layout +'static>(&mut self, layout: T) { self.layouts.push(Box::new(layout)); self.layouts.last_mut().unwrap().align_elems(); self.layouts.last_mut().unwrap().frame().draw_into(&mut self.frame); self.layouts.last_mut().unwrap().forward_keys(&mut self.accel2result); } /// Add an existing label that contains some text. /// /// # Examples /// /// ``` /// use rustty::ui::core::{HorizontalAlign, VerticalAlign, Widget}; /// use rustty::ui::{Dialog, Label}; /// /// let mut maindlg = Dialog::new(60, 10); /// let mut lbl = Label::from_str("Foo"); /// lbl.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (0,0)); /// /// maindlg.add_label(lbl); /// ``` /// pub fn add_label(&mut self, mut label: Label) { label.draw(&mut self.frame); } /// Change the state of an existing CheckButton, if any exists, /// within the dialog. If an invalid button result is given, the /// function will panic. *Note* StdButtons are still valid handles /// for this function, however they will not actually do anything. /// This function is for buttons that perform some action upon being /// pressed. /// /// # Examples /// /// ```ignore /// // match character for dialog /// match dialog.result_for_key(ch) { /// Some(ButtonResult::Ok) => { /// dialog.button_pressed(ButtonResult::Custom(i)); /// // do stuff... /// }, /// _ => { } /// } /// ``` /// pub fn button_pressed(&mut self, res: ButtonResult) { match self.buttons.iter_mut().find(|x| x.result() == res) { Some(i) => { i.pressed(); i.draw(&mut self.frame)} _ => { panic!("Not a valid button result for\ Dialog::button_checked()"); } } } /// For buttons that have a state manager, this function will return /// the current state of the button. *CheckButton* for example uses /// a state to manage whether the button is checked, different actions /// can be taken depending on the state once read. /// /// # Examples /// /// ```ignore /// // match character for dialog /// match dialog.result_for_key(ch) { /// Some(ButtonResult::Ok) => { /// dialog.button_pressed(ButtonResult::Custom(i)); /// if dialog.is_button_pressed(ButtonResult::Custom(i)) { /// // do... /// } else { /// // do else... /// } /// }, /// _ => { } /// } /// ``` /// pub fn is_button_pressed(&self, res: ButtonResult) -> bool { match self.buttons.iter().find(|x| x.result() == res) { Some(i) => i.state(), _ => panic!("Not a valid button result for\ Dialog::is_button_checked()") } } /// Checks whether the char passed is a valid key for any buttons currently /// drawn within the dialog, if so the corresponding `ButtonResult` is returned pub fn result_for_key(&self, key: char) -> Option<ButtonResult> { match self.accel2result.get(&key.to_lowercase().next().unwrap_or(key)) { Some(r) => Some(*r), None => None, } } } impl Widget for Dialog { fn draw(&mut self, parent: &mut CellAccessor) { self.frame.draw_into(parent); } fn pack(&mut self, parent: &HasSize, halign: HorizontalAlign, valign: VerticalAlign, margin: (usize, usize)) { self.frame.align(parent, halign, valign, margin); } fn draw_box(&mut self) { self.frame.draw_box(); } fn resize(&mut self, new_size: Size) { self.frame.resize(new_size); } fn frame(&self) -> &Frame
fn frame_mut(&mut self) -> &mut Frame { &mut self.frame } } impl HasSize for Dialog { fn size(&self) -> Size { self.frame.size() } }
{ &self.frame }
identifier_body
to_ref.rs
pub trait ToRef<'a> { type Ref: 'a; fn to_ref(&'a self) -> Self::Ref; } pub trait ToMut<'a>: ToRef<'a> { type Mut: 'a; fn to_mut(&'a mut self) -> Self::Mut; } impl<'a, T: 'a> ToRef<'a> for &'a T { type Ref = &'a T; fn to_ref(&'a self) -> Self::Ref { &*self } } impl<'a, T: 'a> ToRef<'a> for &'a mut T { type Ref = &'a T; fn to_ref(&'a self) -> Self::Ref { &*self } } impl<'a, T: 'a> ToMut<'a> for &'a mut T { type Mut = &'a mut T; fn to_mut(&'a mut self) -> Self::Mut
} impl<'a> ToRef<'a> for () { type Ref = (); fn to_ref(&'a self) -> Self::Ref { () } } impl<'a> ToMut<'a> for () { type Mut = (); fn to_mut(&'a mut self) -> Self::Mut { () } }
{ &mut *self }
identifier_body
to_ref.rs
pub trait ToRef<'a> { type Ref: 'a; fn to_ref(&'a self) -> Self::Ref; } pub trait ToMut<'a>: ToRef<'a> { type Mut: 'a; fn to_mut(&'a mut self) -> Self::Mut; } impl<'a, T: 'a> ToRef<'a> for &'a T { type Ref = &'a T; fn to_ref(&'a self) -> Self::Ref { &*self } } impl<'a, T: 'a> ToRef<'a> for &'a mut T { type Ref = &'a T; fn to_ref(&'a self) -> Self::Ref { &*self } } impl<'a, T: 'a> ToMut<'a> for &'a mut T { type Mut = &'a mut T; fn to_mut(&'a mut self) -> Self::Mut { &mut *self } } impl<'a> ToRef<'a> for () { type Ref = (); fn to_ref(&'a self) -> Self::Ref { () } } impl<'a> ToMut<'a> for () { type Mut = (); fn
(&'a mut self) -> Self::Mut { () } }
to_mut
identifier_name
to_ref.rs
pub trait ToRef<'a> { type Ref: 'a; fn to_ref(&'a self) -> Self::Ref; } pub trait ToMut<'a>: ToRef<'a> { type Mut: 'a; fn to_mut(&'a mut self) -> Self::Mut; } impl<'a, T: 'a> ToRef<'a> for &'a T { type Ref = &'a T; fn to_ref(&'a self) -> Self::Ref { &*self } } impl<'a, T: 'a> ToRef<'a> for &'a mut T { type Ref = &'a T; fn to_ref(&'a self) -> Self::Ref { &*self } } impl<'a, T: 'a> ToMut<'a> for &'a mut T { type Mut = &'a mut T; fn to_mut(&'a mut self) -> Self::Mut {
type Ref = (); fn to_ref(&'a self) -> Self::Ref { () } } impl<'a> ToMut<'a> for () { type Mut = (); fn to_mut(&'a mut self) -> Self::Mut { () } }
&mut *self } } impl<'a> ToRef<'a> for () {
random_line_split
structs.rs
use collections::BTreeMap; //JSON support use serialize::json::{ self, ToJson, Json}; // syntax elements use syntax::ast::StructDef; use syntax::ast::StructFieldKind::*; pub struct StructDefinition { name: String, // (name ,type ) fields: Vec<(String, String)>, } impl StructDefinition { pub fn
(name: String, struct_def: &StructDef) -> StructDefinition { let mut tuple_struct_index = 0i64; let fields: Vec<(String,String)> = struct_def.fields .iter() .map(|field| match field.node.kind { // TODO: handle visibility NamedField(ref ident, ref _visibility) => (super::get_name_from_ident(ident), super::read_type(&field.node.ty.node)), UnnamedField(ref _visibility) => { let t = (tuple_struct_index.to_string(), super::read_type(&field.node.ty.node)); tuple_struct_index += 1; t } } ) .collect(); StructDefinition { name: name, fields: fields } } } // for serialization // eg: struct Test { a: i64, b: String } // => {"name":"Test","fields":[["a","i64"],["b","String"]]} impl ToJson for StructDefinition { fn to_json(&self) -> json::Json { let mut j = BTreeMap::new(); j.insert("name".to_string(), self.name.to_json()); j.insert("fields".to_string(), self.fields.to_json()); j.to_json() } }
new
identifier_name
structs.rs
use collections::BTreeMap; //JSON support
use serialize::json::{ self, ToJson, Json}; // syntax elements use syntax::ast::StructDef; use syntax::ast::StructFieldKind::*; pub struct StructDefinition { name: String, // (name ,type ) fields: Vec<(String, String)>, } impl StructDefinition { pub fn new(name: String, struct_def: &StructDef) -> StructDefinition { let mut tuple_struct_index = 0i64; let fields: Vec<(String,String)> = struct_def.fields .iter() .map(|field| match field.node.kind { // TODO: handle visibility NamedField(ref ident, ref _visibility) => (super::get_name_from_ident(ident), super::read_type(&field.node.ty.node)), UnnamedField(ref _visibility) => { let t = (tuple_struct_index.to_string(), super::read_type(&field.node.ty.node)); tuple_struct_index += 1; t } } ) .collect(); StructDefinition { name: name, fields: fields } } } // for serialization // eg: struct Test { a: i64, b: String } // => {"name":"Test","fields":[["a","i64"],["b","String"]]} impl ToJson for StructDefinition { fn to_json(&self) -> json::Json { let mut j = BTreeMap::new(); j.insert("name".to_string(), self.name.to_json()); j.insert("fields".to_string(), self.fields.to_json()); j.to_json() } }
random_line_split
structs.rs
use collections::BTreeMap; //JSON support use serialize::json::{ self, ToJson, Json}; // syntax elements use syntax::ast::StructDef; use syntax::ast::StructFieldKind::*; pub struct StructDefinition { name: String, // (name ,type ) fields: Vec<(String, String)>, } impl StructDefinition { pub fn new(name: String, struct_def: &StructDef) -> StructDefinition
} // for serialization // eg: struct Test { a: i64, b: String } // => {"name":"Test","fields":[["a","i64"],["b","String"]]} impl ToJson for StructDefinition { fn to_json(&self) -> json::Json { let mut j = BTreeMap::new(); j.insert("name".to_string(), self.name.to_json()); j.insert("fields".to_string(), self.fields.to_json()); j.to_json() } }
{ let mut tuple_struct_index = 0i64; let fields: Vec<(String,String)> = struct_def.fields .iter() .map(|field| match field.node.kind { // TODO: handle visibility NamedField(ref ident, ref _visibility) => (super::get_name_from_ident(ident), super::read_type(&field.node.ty.node)), UnnamedField(ref _visibility) => { let t = (tuple_struct_index.to_string(), super::read_type(&field.node.ty.node)); tuple_struct_index += 1; t } } ) .collect(); StructDefinition { name: name, fields: fields } }
identifier_body
meth.rs
-> Callee<'blk, 'tcx> { let _icx = push_ctxt("meth::trans_monomorphized_callee"); match vtable { traits::VtableImpl(vtable_impl) => { let ccx = bcx.ccx(); let impl_did = vtable_impl.impl_def_id; let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) { ty::MethodTraitItem(method) => method.name, ty::TypeTraitItem(_) => { bcx.tcx().sess.bug("can't monomorphize an associated \ type") } }; let mth_id = method_with_name(bcx.ccx(), impl_did, mname); // create a concatenated set of substitutions which includes // those from the impl and those from the method: let callee_substs = combine_impl_and_methods_tps( bcx, MethodCall(method_call), vtable_impl.substs); // translate the function let llfn = trans_fn_ref_with_substs(bcx, mth_id, MethodCall(method_call), callee_substs); Callee { bcx: bcx, data: Fn(llfn) } } traits::VtableUnboxedClosure(closure_def_id, substs) => { // The substitutions should have no type parameters remaining // after passing through fulfill_obligation let llfn = trans_fn_ref_with_substs(bcx, closure_def_id, MethodCall(method_call), substs); Callee { bcx: bcx, data: Fn(llfn), } } _ => { bcx.tcx().sess.bug( "vtable_param left in monomorphized function's vtable substs"); } } } fn combine_impl_and_methods_tps(bcx: Block, node: ExprOrMethodCall, rcvr_substs: subst::Substs) -> subst::Substs { /*! * Creates a concatenated set of substitutions which includes * those from the impl and those from the method. This are * some subtle complications here. Statically, we have a list * of type parameters like `[T0, T1, T2, M1, M2, M3]` where * `Tn` are type parameters that appear on the receiver. For * example, if the receiver is a method parameter `A` with a * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`. * * The weird part is that the type `A` might now be bound to * any other type, such as `foo<X>`. In that case, the vector * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is * to slice off the method type parameters and append them to * the type parameters from the type that the receiver is * mapped to. */ let ccx = bcx.ccx(); let node_substs = node_id_substs(bcx, node); debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx())); debug!("node_substs={}", node_substs.repr(ccx.tcx())); // Break apart the type parameters from the node and type // parameters from the receiver. let node_method = node_substs.types.split().fns; let subst::SeparateVecsPerParamSpace { types: rcvr_type, selfs: rcvr_self, assocs: rcvr_assoc, fns: rcvr_method } = rcvr_substs.types.clone().split(); assert!(rcvr_method.is_empty()); subst::Substs { regions: subst::ErasedRegions, types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, rcvr_assoc, node_method) } } fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, method_ty: ty::t, n_method: uint, self_expr: &ast::Expr, arg_cleanup_scope: cleanup::ScopeId) -> Callee<'blk, 'tcx> { /*! * Create a method callee where the method is coming from a trait * object (e.g., Box<Trait> type). In this case, we must pull the fn * pointer out of the vtable that is packaged up with the object. * Objects are represented as a pair, so we first evaluate the self * expression and then extract the self data and vtable out of the * pair. */ let _icx = push_ctxt("meth::trans_trait_callee"); let mut bcx = bcx; // Translate self_datum and take ownership of the value by // converting to an rvalue. let self_datum = unpack_datum!( bcx, expr::trans(bcx, self_expr)); let llval = if ty::type_needs_drop(bcx.tcx(), self_datum.ty) { let self_datum = unpack_datum!( bcx, self_datum.to_rvalue_datum(bcx, "trait_callee")); // Convert to by-ref since `trans_trait_callee_from_llval` wants it // that way. let self_datum = unpack_datum!( bcx, self_datum.to_ref_datum(bcx)); // Arrange cleanup in case something should go wrong before the // actual call occurs. self_datum.add_clean(bcx.fcx, arg_cleanup_scope) } else { // We don't have to do anything about cleanups for &Trait and &mut Trait. assert!(self_datum.kind.is_by_ref()); self_datum.val }; trans_trait_callee_from_llval(bcx, method_ty, n_method, llval) } pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, callee_ty: ty::t, n_method: uint, llpair: ValueRef) -> Callee<'blk, 'tcx> { /*! * Same as `trans_trait_callee()` above, except that it is given * a by-ref pointer to the object pair. */ let _icx = push_ctxt("meth::trans_trait_callee"); let ccx = bcx.ccx(); // Load the data pointer from the object. debug!("(translating trait callee) loading second index from pair"); let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]); let llbox = Load(bcx, llboxptr); let llself = PointerCast(bcx, llbox, Type::i8p(ccx)); // Load the function from the vtable and cast it to the expected type. debug!("(translating trait callee) loading method"); // Replace the self type (&Self or Box<Self>) with an opaque pointer. let llcallee_ty = match ty::get(callee_ty).sty { ty::ty_bare_fn(ref f) if f.abi == Rust || f.abi == RustCall => { type_of_rust_fn(ccx, Some(Type::i8p(ccx)), f.sig.inputs.slice_from(1), f.sig.output, f.abi) } _ => { ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn"); } }; let llvtable = Load(bcx, PointerCast(bcx, GEPi(bcx, llpair, [0u, abi::trt_field_vtable]), Type::vtable(ccx).ptr_to().ptr_to())); let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + VTABLE_OFFSET])); let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to()); return Callee { bcx: bcx, data: TraitItem(MethodData { llfn: mptr, llself: llself, }) }; } /// Creates a returns a dynamic vtable for the given type and vtable origin. /// This is used only for objects. /// /// The `trait_ref` encodes the erased self type. Hence if we are /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then /// `trait_ref` would map `T:Trait`, but `box_ty` would be /// `Foo<T>`. This `box_ty` is primarily used to encode the destructor. /// This will hopefully change now that DST is underway. pub fn get_vtable(bcx: Block, box_ty: ty::t, trait_ref: Rc<ty::TraitRef>) -> ValueRef { debug!("get_vtable(box_ty={}, trait_ref={})", box_ty.repr(bcx.tcx()), trait_ref.repr(bcx.tcx())); let tcx = bcx.tcx(); let ccx = bcx.ccx(); let _icx = push_ctxt("meth::get_vtable"); // Check the cache. let cache_key = (box_ty, trait_ref.clone()); match ccx.vtables().borrow().get(&cache_key) { Some(&val) => { return val } None => { } } // Not in the cache. Build it. let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| { let vtable = fulfill_obligation(bcx.ccx(), DUMMY_SP, trait_ref.clone()); match vtable { traits::VtableBuiltin(_) => { Vec::new().into_iter() } traits::VtableImpl( traits::VtableImplData { impl_def_id: id, substs, nested: _ }) => { emit_vtable_methods(bcx, id, substs).into_iter() } traits::VtableUnboxedClosure(closure_def_id, substs) => { // Look up closure type let self_ty = ty::node_id_to_type(bcx.tcx(), closure_def_id.node); // Apply substitutions from closure param environment. // The substitutions should have no type parameters // remaining after passing through fulfill_obligation let self_ty = self_ty.subst(bcx.tcx(), &substs); let mut llfn = trans_fn_ref_with_substs( bcx, closure_def_id, ExprId(0), substs.clone()); { let unboxed_closures = bcx.tcx() .unboxed_closures .borrow(); let closure_info = unboxed_closures.get(&closure_def_id) .expect("get_vtable(): didn't find \ unboxed closure"); if closure_info.kind == ty::FnOnceUnboxedClosureKind { // Untuple the arguments and create an unboxing shim. let (new_inputs, new_output) = match ty::get(self_ty).sty { ty::ty_unboxed_closure(_, _, ref substs) => { let mut new_inputs = vec![self_ty.clone()]; match ty::get(closure_info.closure_type .sig .inputs[0]).sty { ty::ty_tup(ref elements) => { for element in elements.iter() { new_inputs.push(element.subst(bcx.tcx(), substs)); } } ty::ty_nil => {} _ => { bcx.tcx().sess.bug("get_vtable(): closure \ type wasn't a tuple") } } (new_inputs, closure_info.closure_type.sig.output.subst(bcx.tcx(), substs)) }, _ => bcx.tcx().sess.bug("get_vtable(): def wasn't an unboxed closure") }; let closure_type = ty::BareFnTy { fn_style: closure_info.closure_type.fn_style, abi: Rust, sig: ty::FnSig { binder_id: closure_info.closure_type .sig .binder_id, inputs: new_inputs, output: new_output, variadic: false, }, }; debug!("get_vtable(): closure type is {}", closure_type.repr(bcx.tcx())); llfn = trans_unboxing_shim(bcx, llfn, &closure_type, closure_def_id, substs); } } (vec!(llfn)).into_iter() } traits::VtableParam(..) => { bcx.sess().bug( format!("resolved vtable for {} to bad vtable {} in trans", trait_ref.repr(bcx.tcx()), vtable.repr(bcx.tcx())).as_slice()); } } }); let size_ty = sizing_type_of(ccx, trait_ref.self_ty()); let size = machine::llsize_of_alloc(ccx, size_ty); let ll_size = C_uint(ccx, size); let align = align_of(ccx, trait_ref.self_ty()); let ll_align = C_uint(ccx, align); // Generate a destructor for the vtable. let drop_glue = glue::get_drop_glue(ccx, box_ty); let vtable = make_vtable(ccx, drop_glue, ll_size, ll_align, methods); ccx.vtables().borrow_mut().insert(cache_key, vtable); vtable } /// Helper function to declare and initialize the vtable. pub fn make_vtable<I: Iterator<ValueRef>>(ccx: &CrateContext, drop_glue: ValueRef, size: ValueRef, align: ValueRef, ptrs: I) -> ValueRef { let _icx = push_ctxt("meth::make_vtable"); let head = vec![drop_glue, size, align]; let components: Vec<_> = head.into_iter().chain(ptrs).collect(); unsafe { let tbl = C_struct(ccx, components.as_slice(), false); let sym = token::gensym("vtable"); let vt_gvar = format!("vtable{}", sym.uint()).with_c_str(|buf| { llvm::LLVMAddGlobal(ccx.llmod(), val_ty(tbl).to_ref(), buf) }); llvm::LLVMSetInitializer(vt_gvar, tbl); llvm::LLVMSetGlobalConstant(vt_gvar, llvm::True); llvm::SetLinkage(vt_gvar, llvm::InternalLinkage); vt_gvar } } fn
emit_vtable_methods
identifier_name
meth.rs
method_num, origin) } typeck::MethodTraitObject(ref mt) => { let self_expr = match self_expr { Some(self_expr) => self_expr, None => { bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id), "self expr wasn't provided for trait object \ callee (trying to call overloaded op?)") } }; trans_trait_callee(bcx, monomorphize_type(bcx, method_ty), mt.real_index, self_expr, arg_cleanup_scope) } } } pub fn trans_static_method_callee(bcx: Block, method_id: ast::DefId, trait_id: ast::DefId, expr_id: ast::NodeId) -> ValueRef { let _icx = push_ctxt("meth::trans_static_method_callee"); let ccx = bcx.ccx(); debug!("trans_static_method_callee(method_id={}, trait_id={}, \ expr_id={})", method_id, ty::item_path_str(bcx.tcx(), trait_id), expr_id); let mname = if method_id.krate == ast::LOCAL_CRATE { match bcx.tcx().map.get(method_id.node) { ast_map::NodeTraitItem(method) => { let ident = match *method { ast::RequiredMethod(ref m) => m.ident, ast::ProvidedMethod(ref m) => m.pe_ident(), ast::TypeTraitItem(_) => { bcx.tcx().sess.bug("trans_static_method_callee() on \ an associated type?!") } }; ident.name } _ => panic!("callee is not a trait method") } } else { csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name() }; debug!("trans_static_method_callee: method_id={}, expr_id={}, \ name={}", method_id, expr_id, token::get_name(mname)); // Find the substitutions for the fn itself. This includes // type parameters that belong to the trait but also some that // belong to the method: let rcvr_substs = node_id_substs(bcx, ExprId(expr_id)); let subst::SeparateVecsPerParamSpace { types: rcvr_type, selfs: rcvr_self, assocs: rcvr_assoc, fns: rcvr_method } = rcvr_substs.types.split(); // Lookup the precise impl being called. To do that, we need to // create a trait reference identifying the self type and other // input type parameters. To create that trait reference, we have // to pick apart the type parameters to identify just those that // pertain to the trait. This is easiest to explain by example: // // trait Convert { // fn from<U:Foo>(n: U) -> Option<Self>; // } // ... // let f = <Vec<int> as Convert>::from::<String>(...) // // Here, in this call, which I've written with explicit UFCS // notation, the set of type parameters will be: // // rcvr_type: [] <-- nothing declared on the trait itself // rcvr_self: [Vec<int>] <-- the self type // rcvr_method: [String] <-- method type parameter // // So we create a trait reference using the first two, // basically corresponding to `<Vec<int> as Convert>`. // The remaining type parameters (`rcvr_method`) will be used below. let trait_substs = Substs::erased(VecPerParamSpace::new(rcvr_type, rcvr_self, rcvr_assoc, Vec::new())); debug!("trait_substs={}", trait_substs.repr(bcx.tcx())); let trait_ref = Rc::new(ty::TraitRef { def_id: trait_id, substs: trait_substs }); let vtbl = fulfill_obligation(bcx.ccx(), DUMMY_SP, trait_ref); // Now that we know which impl is being used, we can dispatch to // the actual function: match vtbl { traits::VtableImpl(traits::VtableImplData { impl_def_id: impl_did, substs: impl_substs, nested: _ }) => { assert!(impl_substs.types.all(|t|!ty::type_needs_infer(*t))); // Create the substitutions that are in scope. This combines // the type parameters from the impl with those declared earlier. // To see what I mean, consider a possible impl: // // impl<T> Convert for Vec<T> { // fn from<U:Foo>(n: U) {... } // } // // Recall that we matched `<Vec<int> as Convert>`. Trait // resolution will have given us a substitution // containing `impl_substs=[[T=int],[],[]]` (the type // parameters defined on the impl). We combine // that with the `rcvr_method` from before, which tells us // the type parameters from the *method*, to yield // `callee_substs=[[T=int],[],[U=String]]`. let subst::SeparateVecsPerParamSpace { types: impl_type, selfs: impl_self, assocs: impl_assoc, fns: _ } = impl_substs.types.split(); let callee_substs = Substs::erased(VecPerParamSpace::new(impl_type, impl_self, impl_assoc, rcvr_method)); let mth_id = method_with_name(ccx, impl_did, mname); let llfn = trans_fn_ref_with_substs(bcx, mth_id, ExprId(expr_id), callee_substs); let callee_ty = node_id_type(bcx, expr_id); let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to(); PointerCast(bcx, llfn, llty) } _ => { bcx.tcx().sess.bug( format!("static call to invalid vtable: {}", vtbl.repr(bcx.tcx())).as_slice()); } } } fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name) -> ast::DefId
fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, method_call: MethodCall, trait_id: ast::DefId, n_method: uint, vtable: traits::Vtable<()>) -> Callee<'blk, 'tcx> { let _icx = push_ctxt("meth::trans_monomorphized_callee"); match vtable { traits::VtableImpl(vtable_impl) => { let ccx = bcx.ccx(); let impl_did = vtable_impl.impl_def_id; let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) { ty::MethodTraitItem(method) => method.name, ty::TypeTraitItem(_) => { bcx.tcx().sess.bug("can't monomorphize an associated \ type") } }; let mth_id = method_with_name(bcx.ccx(), impl_did, mname); // create a concatenated set of substitutions which includes // those from the impl and those from the method: let callee_substs = combine_impl_and_methods_tps( bcx, MethodCall(method_call), vtable_impl.substs); // translate the function let llfn = trans_fn_ref_with_substs(bcx, mth_id, MethodCall(method_call), callee_substs); Callee { bcx: bcx, data: Fn(llfn) } } traits::VtableUnboxedClosure(closure_def_id, substs) => { // The substitutions should have no type parameters remaining // after passing through fulfill_obligation let llfn = trans_fn_ref_with_substs(bcx, closure_def_id, MethodCall(method_call), substs); Callee { bcx: bcx, data: Fn(llfn), } } _ => { bcx.tcx().sess.bug( "vtable_param left in monomorphized function's vtable substs"); } } } fn combine_impl_and_methods_tps(bcx: Block, node: ExprOrMethodCall, rcvr_substs: subst::Substs) -> subst::Substs { /*! * Creates a concatenated set of substitutions which includes * those from the impl and those from the method. This are * some subtle complications here. Statically, we have a list * of type parameters like `[T0, T1, T2, M1, M2, M3]` where * `Tn` are type parameters that appear on the receiver. For * example, if the receiver is a method parameter `A` with a * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`. * * The weird part is that the type `A` might now be bound to * any other type, such as `foo<X>`. In that case, the vector * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is * to slice off the method type parameters and append them to * the type parameters from the type that the receiver is * mapped to. */ let ccx = bcx.ccx(); let node_substs = node_id_substs(bcx, node); debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx())); debug!("node_substs={}", node_substs.repr(ccx.tcx())); // Break apart the type parameters from the node and type // parameters from the receiver. let node_method = node_substs.types.split().fns; let subst::SeparateVecsPerParamSpace { types: rcvr_type, selfs: rcvr_self, assocs: rcvr_assoc, fns: rcvr_method } = rcvr_substs.types.clone().split(); assert!(rcvr_method.is_empty()); subst::Substs { regions: subst::ErasedRegions, types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, rcvr_assoc, node_method) } } fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, method_ty: ty::t, n_method: uint, self_expr: &ast::Expr, arg_cleanup_scope: cleanup::ScopeId) -> Callee<'blk, 'tcx> { /*! * Create a method callee where the method is coming from a trait * object (e.g., Box<Trait> type). In this case, we must pull the fn * pointer out of the vtable that is packaged up with the object. * Objects are represented as a pair, so we first evaluate the self * expression and then extract the self data and vtable out of the * pair. */ let _icx = push_ctxt("meth::trans_trait_callee"); let mut bcx = bcx; // Translate self_datum and take ownership of the value by // converting to an rvalue. let self_datum = unpack_datum!( bcx, expr::trans(bcx, self_expr)); let llval = if ty::type_needs_drop(bcx.tcx(), self_datum.ty) { let self_datum = unpack_datum!( bcx, self_datum.to_rvalue_datum(bcx, "trait_callee")); // Convert to by-ref since `trans_trait_callee_from_llval` wants it // that way. let self_datum = unpack_datum!( bcx, self_datum.to_ref_datum(bcx)); // Arrange cleanup in case something should go wrong before the // actual call occurs. self_datum.add_clean(bcx.fcx, arg_cleanup_scope) } else { // We don't have to do anything about cleanups for &Trait and &mut Trait. assert!(self_datum.kind.is_by_ref()); self_datum.val }; trans_trait_callee_from_llval(bcx, method_ty, n_method, llval) } pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, callee_ty: ty::t, n_method: uint, llpair: ValueRef) -> Callee<'blk, 'tcx> { /*! * Same as `trans_trait_callee()` above, except that it is given * a by-ref pointer to the object pair. */ let _icx = push_ctxt("meth::trans_trait_callee"); let ccx = bcx.ccx(); // Load the data pointer from the object. debug!("(translating trait callee) loading second index from pair"); let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]); let llbox = Load(bcx, llboxptr); let llself = PointerCast(bcx, llbox, Type::i8p(ccx)); // Load the function from the vtable and cast it to the expected type. debug!("(translating trait callee) loading method"); // Replace the self type (&Self or Box<Self>) with an opaque pointer. let llcallee_ty = match ty::get(callee_ty).sty { ty::ty_bare_fn(ref f) if f.abi == Rust || f.abi == RustCall => { type_of_rust_fn(ccx, Some(Type::i8p(ccx)), f.sig.inputs.slice_from(1), f.sig.output, f.abi) } _ => { ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn"); } }; let llvtable = Load(bcx, PointerCast(bcx, GEPi(bcx, llpair, [0u, abi::trt_field_vtable]), Type::vtable(ccx).ptr_to().ptr_to())); let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + VTABLE_OFFSET])); let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to()); return Callee { bcx: bcx, data: TraitItem(MethodData { llfn: mptr, llself: llself, }) }; } /// Creates a returns a dynamic vtable for the given type and vtable origin. /// This is used only for objects. /// /// The `trait_ref` encodes the erased self type. Hence if we are /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then /// `trait_ref` would map `T:Trait`, but `box_ty` would be /// `Foo<T>`. This `box_ty` is primarily used to encode the destructor. /// This will hopefully change now that DST is underway. pub fn get_vtable(bcx: Block, box_ty: ty::t, trait_ref: Rc<ty::TraitRef>)
{ match ccx.impl_method_cache().borrow().find_copy(&(impl_id, name)) { Some(m) => return m, None => {} } let impl_items = ccx.tcx().impl_items.borrow(); let impl_items = impl_items.get(&impl_id) .expect("could not find impl while translating"); let meth_did = impl_items.iter() .find(|&did| { ty::impl_or_trait_item(ccx.tcx(), did.def_id()).name() == name }).expect("could not find method while \ translating"); ccx.impl_method_cache().borrow_mut().insert((impl_id, name), meth_did.def_id()); meth_did.def_id() }
identifier_body
meth.rs
method_num, origin) } typeck::MethodTraitObject(ref mt) => { let self_expr = match self_expr { Some(self_expr) => self_expr, None => { bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id), "self expr wasn't provided for trait object \ callee (trying to call overloaded op?)") } }; trans_trait_callee(bcx, monomorphize_type(bcx, method_ty), mt.real_index, self_expr, arg_cleanup_scope) } } } pub fn trans_static_method_callee(bcx: Block, method_id: ast::DefId, trait_id: ast::DefId, expr_id: ast::NodeId) -> ValueRef { let _icx = push_ctxt("meth::trans_static_method_callee"); let ccx = bcx.ccx(); debug!("trans_static_method_callee(method_id={}, trait_id={}, \ expr_id={})", method_id, ty::item_path_str(bcx.tcx(), trait_id), expr_id); let mname = if method_id.krate == ast::LOCAL_CRATE { match bcx.tcx().map.get(method_id.node) { ast_map::NodeTraitItem(method) => { let ident = match *method { ast::RequiredMethod(ref m) => m.ident, ast::ProvidedMethod(ref m) => m.pe_ident(), ast::TypeTraitItem(_) => { bcx.tcx().sess.bug("trans_static_method_callee() on \ an associated type?!") } }; ident.name } _ => panic!("callee is not a trait method") } } else { csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name() }; debug!("trans_static_method_callee: method_id={}, expr_id={}, \ name={}", method_id, expr_id, token::get_name(mname)); // Find the substitutions for the fn itself. This includes // type parameters that belong to the trait but also some that // belong to the method: let rcvr_substs = node_id_substs(bcx, ExprId(expr_id)); let subst::SeparateVecsPerParamSpace { types: rcvr_type, selfs: rcvr_self, assocs: rcvr_assoc, fns: rcvr_method } = rcvr_substs.types.split(); // Lookup the precise impl being called. To do that, we need to // create a trait reference identifying the self type and other // input type parameters. To create that trait reference, we have // to pick apart the type parameters to identify just those that // pertain to the trait. This is easiest to explain by example: // // trait Convert { // fn from<U:Foo>(n: U) -> Option<Self>; // } // ... // let f = <Vec<int> as Convert>::from::<String>(...) // // Here, in this call, which I've written with explicit UFCS // notation, the set of type parameters will be: // // rcvr_type: [] <-- nothing declared on the trait itself // rcvr_self: [Vec<int>] <-- the self type // rcvr_method: [String] <-- method type parameter // // So we create a trait reference using the first two, // basically corresponding to `<Vec<int> as Convert>`. // The remaining type parameters (`rcvr_method`) will be used below. let trait_substs = Substs::erased(VecPerParamSpace::new(rcvr_type, rcvr_self, rcvr_assoc, Vec::new())); debug!("trait_substs={}", trait_substs.repr(bcx.tcx())); let trait_ref = Rc::new(ty::TraitRef { def_id: trait_id, substs: trait_substs }); let vtbl = fulfill_obligation(bcx.ccx(), DUMMY_SP, trait_ref); // Now that we know which impl is being used, we can dispatch to // the actual function: match vtbl { traits::VtableImpl(traits::VtableImplData { impl_def_id: impl_did, substs: impl_substs, nested: _ }) => { assert!(impl_substs.types.all(|t|!ty::type_needs_infer(*t))); // Create the substitutions that are in scope. This combines // the type parameters from the impl with those declared earlier. // To see what I mean, consider a possible impl: // // impl<T> Convert for Vec<T> { // fn from<U:Foo>(n: U) {... } // } // // Recall that we matched `<Vec<int> as Convert>`. Trait // resolution will have given us a substitution // containing `impl_substs=[[T=int],[],[]]` (the type // parameters defined on the impl). We combine // that with the `rcvr_method` from before, which tells us // the type parameters from the *method*, to yield // `callee_substs=[[T=int],[],[U=String]]`. let subst::SeparateVecsPerParamSpace { types: impl_type, selfs: impl_self, assocs: impl_assoc, fns: _ } = impl_substs.types.split(); let callee_substs = Substs::erased(VecPerParamSpace::new(impl_type, impl_self, impl_assoc, rcvr_method)); let mth_id = method_with_name(ccx, impl_did, mname); let llfn = trans_fn_ref_with_substs(bcx, mth_id, ExprId(expr_id), callee_substs); let callee_ty = node_id_type(bcx, expr_id); let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to(); PointerCast(bcx, llfn, llty) } _ => { bcx.tcx().sess.bug( format!("static call to invalid vtable: {}", vtbl.repr(bcx.tcx())).as_slice()); } } } fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name) -> ast::DefId { match ccx.impl_method_cache().borrow().find_copy(&(impl_id, name)) { Some(m) => return m, None => {} } let impl_items = ccx.tcx().impl_items.borrow(); let impl_items = impl_items.get(&impl_id) .expect("could not find impl while translating"); let meth_did = impl_items.iter() .find(|&did| { ty::impl_or_trait_item(ccx.tcx(), did.def_id()).name() == name }).expect("could not find method while \ translating"); ccx.impl_method_cache().borrow_mut().insert((impl_id, name), meth_did.def_id()); meth_did.def_id() } fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, method_call: MethodCall, trait_id: ast::DefId, n_method: uint, vtable: traits::Vtable<()>) -> Callee<'blk, 'tcx> { let _icx = push_ctxt("meth::trans_monomorphized_callee"); match vtable { traits::VtableImpl(vtable_impl) => { let ccx = bcx.ccx(); let impl_did = vtable_impl.impl_def_id; let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) { ty::MethodTraitItem(method) => method.name, ty::TypeTraitItem(_) => { bcx.tcx().sess.bug("can't monomorphize an associated \ type") } }; let mth_id = method_with_name(bcx.ccx(), impl_did, mname); // create a concatenated set of substitutions which includes // those from the impl and those from the method: let callee_substs = combine_impl_and_methods_tps( bcx, MethodCall(method_call), vtable_impl.substs); // translate the function let llfn = trans_fn_ref_with_substs(bcx, mth_id, MethodCall(method_call), callee_substs); Callee { bcx: bcx, data: Fn(llfn) } } traits::VtableUnboxedClosure(closure_def_id, substs) => { // The substitutions should have no type parameters remaining // after passing through fulfill_obligation let llfn = trans_fn_ref_with_substs(bcx, closure_def_id, MethodCall(method_call), substs); Callee { bcx: bcx, data: Fn(llfn), } } _ => { bcx.tcx().sess.bug( "vtable_param left in monomorphized function's vtable substs"); } } } fn combine_impl_and_methods_tps(bcx: Block, node: ExprOrMethodCall, rcvr_substs: subst::Substs) -> subst::Substs { /*! * Creates a concatenated set of substitutions which includes * those from the impl and those from the method. This are * some subtle complications here. Statically, we have a list * of type parameters like `[T0, T1, T2, M1, M2, M3]` where * `Tn` are type parameters that appear on the receiver. For * example, if the receiver is a method parameter `A` with a * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`. * * The weird part is that the type `A` might now be bound to * any other type, such as `foo<X>`. In that case, the vector * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is * to slice off the method type parameters and append them to * the type parameters from the type that the receiver is * mapped to. */ let ccx = bcx.ccx(); let node_substs = node_id_substs(bcx, node); debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx())); debug!("node_substs={}", node_substs.repr(ccx.tcx())); // Break apart the type parameters from the node and type // parameters from the receiver. let node_method = node_substs.types.split().fns; let subst::SeparateVecsPerParamSpace { types: rcvr_type, selfs: rcvr_self, assocs: rcvr_assoc, fns: rcvr_method } = rcvr_substs.types.clone().split(); assert!(rcvr_method.is_empty()); subst::Substs { regions: subst::ErasedRegions, types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, rcvr_assoc, node_method) } } fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, method_ty: ty::t, n_method: uint, self_expr: &ast::Expr, arg_cleanup_scope: cleanup::ScopeId) -> Callee<'blk, 'tcx> { /*! * Create a method callee where the method is coming from a trait * object (e.g., Box<Trait> type). In this case, we must pull the fn * pointer out of the vtable that is packaged up with the object. * Objects are represented as a pair, so we first evaluate the self * expression and then extract the self data and vtable out of the * pair. */ let _icx = push_ctxt("meth::trans_trait_callee"); let mut bcx = bcx; // Translate self_datum and take ownership of the value by // converting to an rvalue. let self_datum = unpack_datum!( bcx, expr::trans(bcx, self_expr)); let llval = if ty::type_needs_drop(bcx.tcx(), self_datum.ty) { let self_datum = unpack_datum!( bcx, self_datum.to_rvalue_datum(bcx, "trait_callee")); // Convert to by-ref since `trans_trait_callee_from_llval` wants it // that way. let self_datum = unpack_datum!( bcx, self_datum.to_ref_datum(bcx)); // Arrange cleanup in case something should go wrong before the // actual call occurs. self_datum.add_clean(bcx.fcx, arg_cleanup_scope) } else { // We don't have to do anything about cleanups for &Trait and &mut Trait. assert!(self_datum.kind.is_by_ref()); self_datum.val }; trans_trait_callee_from_llval(bcx, method_ty, n_method, llval) } pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, callee_ty: ty::t, n_method: uint, llpair: ValueRef) -> Callee<'blk, 'tcx> { /*! * Same as `trans_trait_callee()` above, except that it is given * a by-ref pointer to the object pair. */ let _icx = push_ctxt("meth::trans_trait_callee"); let ccx = bcx.ccx(); // Load the data pointer from the object. debug!("(translating trait callee) loading second index from pair"); let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]); let llbox = Load(bcx, llboxptr); let llself = PointerCast(bcx, llbox, Type::i8p(ccx)); // Load the function from the vtable and cast it to the expected type. debug!("(translating trait callee) loading method"); // Replace the self type (&Self or Box<Self>) with an opaque pointer. let llcallee_ty = match ty::get(callee_ty).sty { ty::ty_bare_fn(ref f) if f.abi == Rust || f.abi == RustCall => { type_of_rust_fn(ccx, Some(Type::i8p(ccx)), f.sig.inputs.slice_from(1), f.sig.output, f.abi) } _ =>
}; let llvtable = Load(bcx, PointerCast(bcx, GEPi(bcx, llpair, [0u, abi::trt_field_vtable]), Type::vtable(ccx).ptr_to().ptr_to())); let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + VTABLE_OFFSET])); let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to()); return Callee { bcx: bcx, data: TraitItem(MethodData { llfn: mptr, llself: llself, }) }; } /// Creates a returns a dynamic vtable for the given type and vtable origin. /// This is used only for objects. /// /// The `trait_ref` encodes the erased self type. Hence if we are /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then /// `trait_ref` would map `T:Trait`, but `box_ty` would be /// `Foo<T>`. This `box_ty` is primarily used to encode the destructor. /// This will hopefully change now that DST is underway. pub fn get_vtable(bcx: Block, box_ty: ty::t, trait_ref: Rc<ty::TraitRef>)
{ ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn"); }
conditional_block
meth.rs
Some(self_expr) => self_expr, None => { bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id), "self expr wasn't provided for trait object \ callee (trying to call overloaded op?)") } }; trans_trait_callee(bcx, monomorphize_type(bcx, method_ty), mt.real_index, self_expr, arg_cleanup_scope) } } } pub fn trans_static_method_callee(bcx: Block, method_id: ast::DefId, trait_id: ast::DefId, expr_id: ast::NodeId) -> ValueRef { let _icx = push_ctxt("meth::trans_static_method_callee"); let ccx = bcx.ccx(); debug!("trans_static_method_callee(method_id={}, trait_id={}, \ expr_id={})", method_id, ty::item_path_str(bcx.tcx(), trait_id), expr_id); let mname = if method_id.krate == ast::LOCAL_CRATE { match bcx.tcx().map.get(method_id.node) { ast_map::NodeTraitItem(method) => { let ident = match *method { ast::RequiredMethod(ref m) => m.ident, ast::ProvidedMethod(ref m) => m.pe_ident(), ast::TypeTraitItem(_) => { bcx.tcx().sess.bug("trans_static_method_callee() on \ an associated type?!") } }; ident.name } _ => panic!("callee is not a trait method") } } else { csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name() }; debug!("trans_static_method_callee: method_id={}, expr_id={}, \ name={}", method_id, expr_id, token::get_name(mname)); // Find the substitutions for the fn itself. This includes // type parameters that belong to the trait but also some that // belong to the method: let rcvr_substs = node_id_substs(bcx, ExprId(expr_id)); let subst::SeparateVecsPerParamSpace { types: rcvr_type, selfs: rcvr_self, assocs: rcvr_assoc, fns: rcvr_method } = rcvr_substs.types.split(); // Lookup the precise impl being called. To do that, we need to // create a trait reference identifying the self type and other // input type parameters. To create that trait reference, we have // to pick apart the type parameters to identify just those that // pertain to the trait. This is easiest to explain by example: // // trait Convert { // fn from<U:Foo>(n: U) -> Option<Self>; // } // ... // let f = <Vec<int> as Convert>::from::<String>(...) // // Here, in this call, which I've written with explicit UFCS // notation, the set of type parameters will be: // // rcvr_type: [] <-- nothing declared on the trait itself // rcvr_self: [Vec<int>] <-- the self type // rcvr_method: [String] <-- method type parameter // // So we create a trait reference using the first two, // basically corresponding to `<Vec<int> as Convert>`. // The remaining type parameters (`rcvr_method`) will be used below. let trait_substs = Substs::erased(VecPerParamSpace::new(rcvr_type, rcvr_self, rcvr_assoc, Vec::new())); debug!("trait_substs={}", trait_substs.repr(bcx.tcx())); let trait_ref = Rc::new(ty::TraitRef { def_id: trait_id, substs: trait_substs }); let vtbl = fulfill_obligation(bcx.ccx(), DUMMY_SP, trait_ref); // Now that we know which impl is being used, we can dispatch to // the actual function: match vtbl { traits::VtableImpl(traits::VtableImplData { impl_def_id: impl_did, substs: impl_substs, nested: _ }) => { assert!(impl_substs.types.all(|t|!ty::type_needs_infer(*t))); // Create the substitutions that are in scope. This combines // the type parameters from the impl with those declared earlier. // To see what I mean, consider a possible impl: // // impl<T> Convert for Vec<T> { // fn from<U:Foo>(n: U) {... } // } // // Recall that we matched `<Vec<int> as Convert>`. Trait // resolution will have given us a substitution // containing `impl_substs=[[T=int],[],[]]` (the type // parameters defined on the impl). We combine // that with the `rcvr_method` from before, which tells us // the type parameters from the *method*, to yield // `callee_substs=[[T=int],[],[U=String]]`. let subst::SeparateVecsPerParamSpace { types: impl_type, selfs: impl_self, assocs: impl_assoc, fns: _ } = impl_substs.types.split(); let callee_substs = Substs::erased(VecPerParamSpace::new(impl_type, impl_self, impl_assoc, rcvr_method)); let mth_id = method_with_name(ccx, impl_did, mname); let llfn = trans_fn_ref_with_substs(bcx, mth_id, ExprId(expr_id), callee_substs); let callee_ty = node_id_type(bcx, expr_id); let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to(); PointerCast(bcx, llfn, llty) } _ => { bcx.tcx().sess.bug( format!("static call to invalid vtable: {}", vtbl.repr(bcx.tcx())).as_slice()); } } } fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name) -> ast::DefId { match ccx.impl_method_cache().borrow().find_copy(&(impl_id, name)) { Some(m) => return m, None => {} } let impl_items = ccx.tcx().impl_items.borrow(); let impl_items = impl_items.get(&impl_id) .expect("could not find impl while translating"); let meth_did = impl_items.iter() .find(|&did| { ty::impl_or_trait_item(ccx.tcx(), did.def_id()).name() == name }).expect("could not find method while \ translating"); ccx.impl_method_cache().borrow_mut().insert((impl_id, name), meth_did.def_id()); meth_did.def_id() } fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, method_call: MethodCall, trait_id: ast::DefId, n_method: uint, vtable: traits::Vtable<()>) -> Callee<'blk, 'tcx> { let _icx = push_ctxt("meth::trans_monomorphized_callee"); match vtable { traits::VtableImpl(vtable_impl) => { let ccx = bcx.ccx(); let impl_did = vtable_impl.impl_def_id; let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) { ty::MethodTraitItem(method) => method.name, ty::TypeTraitItem(_) => { bcx.tcx().sess.bug("can't monomorphize an associated \ type") } }; let mth_id = method_with_name(bcx.ccx(), impl_did, mname); // create a concatenated set of substitutions which includes // those from the impl and those from the method: let callee_substs = combine_impl_and_methods_tps( bcx, MethodCall(method_call), vtable_impl.substs); // translate the function let llfn = trans_fn_ref_with_substs(bcx, mth_id, MethodCall(method_call), callee_substs); Callee { bcx: bcx, data: Fn(llfn) } } traits::VtableUnboxedClosure(closure_def_id, substs) => { // The substitutions should have no type parameters remaining // after passing through fulfill_obligation let llfn = trans_fn_ref_with_substs(bcx, closure_def_id, MethodCall(method_call), substs); Callee { bcx: bcx, data: Fn(llfn), } } _ => { bcx.tcx().sess.bug( "vtable_param left in monomorphized function's vtable substs"); } } } fn combine_impl_and_methods_tps(bcx: Block, node: ExprOrMethodCall, rcvr_substs: subst::Substs) -> subst::Substs { /*! * Creates a concatenated set of substitutions which includes * those from the impl and those from the method. This are * some subtle complications here. Statically, we have a list * of type parameters like `[T0, T1, T2, M1, M2, M3]` where * `Tn` are type parameters that appear on the receiver. For * example, if the receiver is a method parameter `A` with a * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`. * * The weird part is that the type `A` might now be bound to * any other type, such as `foo<X>`. In that case, the vector * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is * to slice off the method type parameters and append them to * the type parameters from the type that the receiver is * mapped to. */ let ccx = bcx.ccx(); let node_substs = node_id_substs(bcx, node); debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx())); debug!("node_substs={}", node_substs.repr(ccx.tcx())); // Break apart the type parameters from the node and type // parameters from the receiver. let node_method = node_substs.types.split().fns; let subst::SeparateVecsPerParamSpace { types: rcvr_type, selfs: rcvr_self, assocs: rcvr_assoc, fns: rcvr_method } = rcvr_substs.types.clone().split(); assert!(rcvr_method.is_empty()); subst::Substs { regions: subst::ErasedRegions, types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, rcvr_assoc, node_method) } } fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, method_ty: ty::t, n_method: uint, self_expr: &ast::Expr, arg_cleanup_scope: cleanup::ScopeId) -> Callee<'blk, 'tcx> { /*! * Create a method callee where the method is coming from a trait * object (e.g., Box<Trait> type). In this case, we must pull the fn * pointer out of the vtable that is packaged up with the object. * Objects are represented as a pair, so we first evaluate the self * expression and then extract the self data and vtable out of the * pair. */ let _icx = push_ctxt("meth::trans_trait_callee"); let mut bcx = bcx; // Translate self_datum and take ownership of the value by // converting to an rvalue. let self_datum = unpack_datum!( bcx, expr::trans(bcx, self_expr)); let llval = if ty::type_needs_drop(bcx.tcx(), self_datum.ty) { let self_datum = unpack_datum!( bcx, self_datum.to_rvalue_datum(bcx, "trait_callee")); // Convert to by-ref since `trans_trait_callee_from_llval` wants it // that way. let self_datum = unpack_datum!( bcx, self_datum.to_ref_datum(bcx)); // Arrange cleanup in case something should go wrong before the // actual call occurs. self_datum.add_clean(bcx.fcx, arg_cleanup_scope) } else { // We don't have to do anything about cleanups for &Trait and &mut Trait. assert!(self_datum.kind.is_by_ref()); self_datum.val }; trans_trait_callee_from_llval(bcx, method_ty, n_method, llval) } pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, callee_ty: ty::t, n_method: uint, llpair: ValueRef) -> Callee<'blk, 'tcx> { /*! * Same as `trans_trait_callee()` above, except that it is given * a by-ref pointer to the object pair. */ let _icx = push_ctxt("meth::trans_trait_callee"); let ccx = bcx.ccx(); // Load the data pointer from the object. debug!("(translating trait callee) loading second index from pair"); let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]); let llbox = Load(bcx, llboxptr); let llself = PointerCast(bcx, llbox, Type::i8p(ccx)); // Load the function from the vtable and cast it to the expected type. debug!("(translating trait callee) loading method"); // Replace the self type (&Self or Box<Self>) with an opaque pointer. let llcallee_ty = match ty::get(callee_ty).sty { ty::ty_bare_fn(ref f) if f.abi == Rust || f.abi == RustCall => { type_of_rust_fn(ccx, Some(Type::i8p(ccx)), f.sig.inputs.slice_from(1), f.sig.output, f.abi) } _ => { ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn"); } }; let llvtable = Load(bcx, PointerCast(bcx, GEPi(bcx, llpair, [0u, abi::trt_field_vtable]), Type::vtable(ccx).ptr_to().ptr_to())); let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + VTABLE_OFFSET])); let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to()); return Callee { bcx: bcx, data: TraitItem(MethodData { llfn: mptr, llself: llself, }) }; } /// Creates a returns a dynamic vtable for the given type and vtable origin. /// This is used only for objects. /// /// The `trait_ref` encodes the erased self type. Hence if we are /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then /// `trait_ref` would map `T:Trait`, but `box_ty` would be /// `Foo<T>`. This `box_ty` is primarily used to encode the destructor. /// This will hopefully change now that DST is underway. pub fn get_vtable(bcx: Block, box_ty: ty::t, trait_ref: Rc<ty::TraitRef>) -> ValueRef { debug!("get_vtable(box_ty={}, trait_ref={})",
box_ty.repr(bcx.tcx()), trait_ref.repr(bcx.tcx())); let tcx = bcx.tcx(); let ccx = bcx.ccx();
random_line_split
re_trait.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Slot is a single saved capture location. Note that there are two slots for /// every capture in a regular expression (one slot each for the start and end /// of the capture). pub type Slot = Option<usize>; /// RegularExpression describes types that can implement regex searching. /// /// This trait is my attempt at reducing code duplication and to standardize /// the internal API. Specific duplication that is avoided are the `find` /// and `capture` iterators, which are slightly tricky. /// /// It's not clear whether this trait is worth it, and it also isn't /// clear whether it's useful as a public trait or not. Methods like /// `next_after_empty` reak of bad design, but the rest of the methods seem /// somewhat reasonable. One particular thing this trait would expose would be /// the ability to start the search of a regex anywhere in a haystack, which /// isn't possible in the current public API. pub trait RegularExpression: Sized { /// The type of the haystack. type Text:?Sized; /// The number of capture slots in the compiled regular expression. This is /// always two times the number of capture groups (two slots per group). fn slots_len(&self) -> usize; /// Returns the position of the next character after `i`. /// /// For example, a haystack with type `&[u8]` probably returns `i+1`, /// whereas a haystack with type `&str` probably returns `i` plus the /// length of the next UTF-8 sequence. fn next_after_empty(&self, text: &Self::Text, i: usize) -> usize; /// Returns the location of the shortest match. fn shortest_match_at( &self, text: &Self::Text, start: usize, ) -> Option<usize>; /// Returns whether the regex matches the text given. fn is_match_at( &self, text: &Self::Text, start: usize, ) -> bool; /// Returns the leftmost-first match location if one exists. fn find_at( &self, text: &Self::Text, start: usize, ) -> Option<(usize, usize)>; /// Returns the leftmost-first match location if one exists, and also /// fills in any matching capture slot locations. fn read_captures_at( &self, slots: &mut [Slot], text: &Self::Text, start: usize, ) -> Option<(usize, usize)>; /// Returns an iterator over all non-overlapping successive leftmost-first /// matches. fn
<'t>( self, text: &'t Self::Text, ) -> FindMatches<'t, Self> { FindMatches { re: self, text: text, last_end: 0, last_match: None, } } /// Returns an iterator over all non-overlapping successive leftmost-first /// matches with captures. fn captures_iter<'t>( self, text: &'t Self::Text, ) -> FindCaptures<'t, Self> { FindCaptures(self.find_iter(text)) } } /// An iterator over all non-overlapping successive leftmost-first matches. pub struct FindMatches<'t, R> where R: RegularExpression, R::Text: 't { re: R, text: &'t R::Text, last_end: usize, last_match: Option<usize>, } impl<'t, R> FindMatches<'t, R> where R: RegularExpression, R::Text: 't { /// Return the text being searched. pub fn text(&self) -> &'t R::Text { self.text } /// Return the underlying regex. pub fn regex(&self) -> &R { &self.re } } impl<'t, R> Iterator for FindMatches<'t, R> where R: RegularExpression, R::Text: 't + AsRef<[u8]> { type Item = (usize, usize); fn next(&mut self) -> Option<(usize, usize)> { if self.last_end > self.text.as_ref().len() { return None; } let (s, e) = match self.re.find_at(self.text, self.last_end) { None => return None, Some((s, e)) => (s, e), }; if s == e { // This is an empty match. To ensure we make progress, start // the next search at the smallest possible starting position // of the next match following this one. self.last_end = self.re.next_after_empty(&self.text, e); // Don't accept empty matches immediately following a match. // Just move on to the next match. if Some(e) == self.last_match { return self.next(); } } else { self.last_end = e; } self.last_match = Some(e); Some((s, e)) } } /// An iterator over all non-overlapping successive leftmost-first matches with /// captures. pub struct FindCaptures<'t, R>(FindMatches<'t, R>) where R: RegularExpression, R::Text: 't; impl<'t, R> FindCaptures<'t, R> where R: RegularExpression, R::Text: 't { /// Return the text being searched. pub fn text(&self) -> &'t R::Text { self.0.text() } /// Return the underlying regex. pub fn regex(&self) -> &R { self.0.regex() } } impl<'t, R> Iterator for FindCaptures<'t, R> where R: RegularExpression, R::Text: 't + AsRef<[u8]> { type Item = Vec<Slot>; fn next(&mut self) -> Option<Vec<Slot>> { if self.0.last_end > self.0.text.as_ref().len() { return None } let mut slots = vec![None; self.0.re.slots_len()]; let (s, e) = match self.0.re.read_captures_at( &mut slots, self.0.text, self.0.last_end, ) { None => return None, Some((s, e)) => (s, e), }; if s == e { self.0.last_end = self.0.re.next_after_empty(&self.0.text, e); if Some(e) == self.0.last_match { return self.next(); } } else { self.0.last_end = e; } self.0.last_match = Some(e); Some(slots) } }
find_iter
identifier_name
re_trait.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Slot is a single saved capture location. Note that there are two slots for /// every capture in a regular expression (one slot each for the start and end /// of the capture). pub type Slot = Option<usize>; /// RegularExpression describes types that can implement regex searching. /// /// This trait is my attempt at reducing code duplication and to standardize /// the internal API. Specific duplication that is avoided are the `find` /// and `capture` iterators, which are slightly tricky. /// /// It's not clear whether this trait is worth it, and it also isn't /// clear whether it's useful as a public trait or not. Methods like /// `next_after_empty` reak of bad design, but the rest of the methods seem /// somewhat reasonable. One particular thing this trait would expose would be /// the ability to start the search of a regex anywhere in a haystack, which /// isn't possible in the current public API. pub trait RegularExpression: Sized { /// The type of the haystack. type Text:?Sized; /// The number of capture slots in the compiled regular expression. This is /// always two times the number of capture groups (two slots per group). fn slots_len(&self) -> usize; /// Returns the position of the next character after `i`. /// /// For example, a haystack with type `&[u8]` probably returns `i+1`, /// whereas a haystack with type `&str` probably returns `i` plus the /// length of the next UTF-8 sequence. fn next_after_empty(&self, text: &Self::Text, i: usize) -> usize; /// Returns the location of the shortest match. fn shortest_match_at( &self, text: &Self::Text, start: usize, ) -> Option<usize>; /// Returns whether the regex matches the text given. fn is_match_at( &self, text: &Self::Text, start: usize, ) -> bool; /// Returns the leftmost-first match location if one exists. fn find_at( &self, text: &Self::Text, start: usize, ) -> Option<(usize, usize)>; /// Returns the leftmost-first match location if one exists, and also /// fills in any matching capture slot locations. fn read_captures_at( &self, slots: &mut [Slot], text: &Self::Text, start: usize, ) -> Option<(usize, usize)>; /// Returns an iterator over all non-overlapping successive leftmost-first /// matches. fn find_iter<'t>( self, text: &'t Self::Text, ) -> FindMatches<'t, Self> { FindMatches { re: self, text: text, last_end: 0, last_match: None, } } /// Returns an iterator over all non-overlapping successive leftmost-first /// matches with captures. fn captures_iter<'t>( self, text: &'t Self::Text, ) -> FindCaptures<'t, Self> { FindCaptures(self.find_iter(text)) } } /// An iterator over all non-overlapping successive leftmost-first matches. pub struct FindMatches<'t, R> where R: RegularExpression, R::Text: 't { re: R, text: &'t R::Text, last_end: usize, last_match: Option<usize>, } impl<'t, R> FindMatches<'t, R> where R: RegularExpression, R::Text: 't { /// Return the text being searched. pub fn text(&self) -> &'t R::Text { self.text } /// Return the underlying regex. pub fn regex(&self) -> &R { &self.re } } impl<'t, R> Iterator for FindMatches<'t, R> where R: RegularExpression, R::Text: 't + AsRef<[u8]> { type Item = (usize, usize); fn next(&mut self) -> Option<(usize, usize)> { if self.last_end > self.text.as_ref().len() { return None; } let (s, e) = match self.re.find_at(self.text, self.last_end) { None => return None, Some((s, e)) => (s, e), }; if s == e { // This is an empty match. To ensure we make progress, start // the next search at the smallest possible starting position // of the next match following this one. self.last_end = self.re.next_after_empty(&self.text, e); // Don't accept empty matches immediately following a match. // Just move on to the next match. if Some(e) == self.last_match { return self.next(); } } else { self.last_end = e; } self.last_match = Some(e); Some((s, e)) } } /// An iterator over all non-overlapping successive leftmost-first matches with /// captures. pub struct FindCaptures<'t, R>(FindMatches<'t, R>) where R: RegularExpression, R::Text: 't; impl<'t, R> FindCaptures<'t, R> where R: RegularExpression, R::Text: 't { /// Return the text being searched. pub fn text(&self) -> &'t R::Text { self.0.text() } /// Return the underlying regex. pub fn regex(&self) -> &R { self.0.regex() } } impl<'t, R> Iterator for FindCaptures<'t, R> where R: RegularExpression, R::Text: 't + AsRef<[u8]> { type Item = Vec<Slot>; fn next(&mut self) -> Option<Vec<Slot>> { if self.0.last_end > self.0.text.as_ref().len() { return None } let mut slots = vec![None; self.0.re.slots_len()]; let (s, e) = match self.0.re.read_captures_at( &mut slots, self.0.text, self.0.last_end, ) { None => return None, Some((s, e)) => (s, e), }; if s == e
else { self.0.last_end = e; } self.0.last_match = Some(e); Some(slots) } }
{ self.0.last_end = self.0.re.next_after_empty(&self.0.text, e); if Some(e) == self.0.last_match { return self.next(); } }
conditional_block
re_trait.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Slot is a single saved capture location. Note that there are two slots for /// every capture in a regular expression (one slot each for the start and end /// of the capture). pub type Slot = Option<usize>; /// RegularExpression describes types that can implement regex searching. /// /// This trait is my attempt at reducing code duplication and to standardize /// the internal API. Specific duplication that is avoided are the `find` /// and `capture` iterators, which are slightly tricky. /// /// It's not clear whether this trait is worth it, and it also isn't /// clear whether it's useful as a public trait or not. Methods like /// `next_after_empty` reak of bad design, but the rest of the methods seem /// somewhat reasonable. One particular thing this trait would expose would be /// the ability to start the search of a regex anywhere in a haystack, which /// isn't possible in the current public API. pub trait RegularExpression: Sized { /// The type of the haystack. type Text:?Sized; /// The number of capture slots in the compiled regular expression. This is /// always two times the number of capture groups (two slots per group). fn slots_len(&self) -> usize; /// Returns the position of the next character after `i`. /// /// For example, a haystack with type `&[u8]` probably returns `i+1`, /// whereas a haystack with type `&str` probably returns `i` plus the /// length of the next UTF-8 sequence. fn next_after_empty(&self, text: &Self::Text, i: usize) -> usize; /// Returns the location of the shortest match. fn shortest_match_at( &self, text: &Self::Text, start: usize, ) -> Option<usize>; /// Returns whether the regex matches the text given. fn is_match_at( &self, text: &Self::Text, start: usize, ) -> bool; /// Returns the leftmost-first match location if one exists. fn find_at( &self, text: &Self::Text, start: usize, ) -> Option<(usize, usize)>; /// Returns the leftmost-first match location if one exists, and also /// fills in any matching capture slot locations. fn read_captures_at( &self, slots: &mut [Slot], text: &Self::Text, start: usize, ) -> Option<(usize, usize)>; /// Returns an iterator over all non-overlapping successive leftmost-first /// matches. fn find_iter<'t>( self, text: &'t Self::Text, ) -> FindMatches<'t, Self> { FindMatches { re: self, text: text, last_end: 0, last_match: None, } } /// Returns an iterator over all non-overlapping successive leftmost-first /// matches with captures. fn captures_iter<'t>( self, text: &'t Self::Text, ) -> FindCaptures<'t, Self> { FindCaptures(self.find_iter(text)) } } /// An iterator over all non-overlapping successive leftmost-first matches. pub struct FindMatches<'t, R> where R: RegularExpression, R::Text: 't { re: R, text: &'t R::Text, last_end: usize, last_match: Option<usize>, } impl<'t, R> FindMatches<'t, R> where R: RegularExpression, R::Text: 't { /// Return the text being searched. pub fn text(&self) -> &'t R::Text { self.text }
} } impl<'t, R> Iterator for FindMatches<'t, R> where R: RegularExpression, R::Text: 't + AsRef<[u8]> { type Item = (usize, usize); fn next(&mut self) -> Option<(usize, usize)> { if self.last_end > self.text.as_ref().len() { return None; } let (s, e) = match self.re.find_at(self.text, self.last_end) { None => return None, Some((s, e)) => (s, e), }; if s == e { // This is an empty match. To ensure we make progress, start // the next search at the smallest possible starting position // of the next match following this one. self.last_end = self.re.next_after_empty(&self.text, e); // Don't accept empty matches immediately following a match. // Just move on to the next match. if Some(e) == self.last_match { return self.next(); } } else { self.last_end = e; } self.last_match = Some(e); Some((s, e)) } } /// An iterator over all non-overlapping successive leftmost-first matches with /// captures. pub struct FindCaptures<'t, R>(FindMatches<'t, R>) where R: RegularExpression, R::Text: 't; impl<'t, R> FindCaptures<'t, R> where R: RegularExpression, R::Text: 't { /// Return the text being searched. pub fn text(&self) -> &'t R::Text { self.0.text() } /// Return the underlying regex. pub fn regex(&self) -> &R { self.0.regex() } } impl<'t, R> Iterator for FindCaptures<'t, R> where R: RegularExpression, R::Text: 't + AsRef<[u8]> { type Item = Vec<Slot>; fn next(&mut self) -> Option<Vec<Slot>> { if self.0.last_end > self.0.text.as_ref().len() { return None } let mut slots = vec![None; self.0.re.slots_len()]; let (s, e) = match self.0.re.read_captures_at( &mut slots, self.0.text, self.0.last_end, ) { None => return None, Some((s, e)) => (s, e), }; if s == e { self.0.last_end = self.0.re.next_after_empty(&self.0.text, e); if Some(e) == self.0.last_match { return self.next(); } } else { self.0.last_end = e; } self.0.last_match = Some(e); Some(slots) } }
/// Return the underlying regex. pub fn regex(&self) -> &R { &self.re
random_line_split
re_trait.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Slot is a single saved capture location. Note that there are two slots for /// every capture in a regular expression (one slot each for the start and end /// of the capture). pub type Slot = Option<usize>; /// RegularExpression describes types that can implement regex searching. /// /// This trait is my attempt at reducing code duplication and to standardize /// the internal API. Specific duplication that is avoided are the `find` /// and `capture` iterators, which are slightly tricky. /// /// It's not clear whether this trait is worth it, and it also isn't /// clear whether it's useful as a public trait or not. Methods like /// `next_after_empty` reak of bad design, but the rest of the methods seem /// somewhat reasonable. One particular thing this trait would expose would be /// the ability to start the search of a regex anywhere in a haystack, which /// isn't possible in the current public API. pub trait RegularExpression: Sized { /// The type of the haystack. type Text:?Sized; /// The number of capture slots in the compiled regular expression. This is /// always two times the number of capture groups (two slots per group). fn slots_len(&self) -> usize; /// Returns the position of the next character after `i`. /// /// For example, a haystack with type `&[u8]` probably returns `i+1`, /// whereas a haystack with type `&str` probably returns `i` plus the /// length of the next UTF-8 sequence. fn next_after_empty(&self, text: &Self::Text, i: usize) -> usize; /// Returns the location of the shortest match. fn shortest_match_at( &self, text: &Self::Text, start: usize, ) -> Option<usize>; /// Returns whether the regex matches the text given. fn is_match_at( &self, text: &Self::Text, start: usize, ) -> bool; /// Returns the leftmost-first match location if one exists. fn find_at( &self, text: &Self::Text, start: usize, ) -> Option<(usize, usize)>; /// Returns the leftmost-first match location if one exists, and also /// fills in any matching capture slot locations. fn read_captures_at( &self, slots: &mut [Slot], text: &Self::Text, start: usize, ) -> Option<(usize, usize)>; /// Returns an iterator over all non-overlapping successive leftmost-first /// matches. fn find_iter<'t>( self, text: &'t Self::Text, ) -> FindMatches<'t, Self> { FindMatches { re: self, text: text, last_end: 0, last_match: None, } } /// Returns an iterator over all non-overlapping successive leftmost-first /// matches with captures. fn captures_iter<'t>( self, text: &'t Self::Text, ) -> FindCaptures<'t, Self> { FindCaptures(self.find_iter(text)) } } /// An iterator over all non-overlapping successive leftmost-first matches. pub struct FindMatches<'t, R> where R: RegularExpression, R::Text: 't { re: R, text: &'t R::Text, last_end: usize, last_match: Option<usize>, } impl<'t, R> FindMatches<'t, R> where R: RegularExpression, R::Text: 't { /// Return the text being searched. pub fn text(&self) -> &'t R::Text { self.text } /// Return the underlying regex. pub fn regex(&self) -> &R { &self.re } } impl<'t, R> Iterator for FindMatches<'t, R> where R: RegularExpression, R::Text: 't + AsRef<[u8]> { type Item = (usize, usize); fn next(&mut self) -> Option<(usize, usize)> { if self.last_end > self.text.as_ref().len() { return None; } let (s, e) = match self.re.find_at(self.text, self.last_end) { None => return None, Some((s, e)) => (s, e), }; if s == e { // This is an empty match. To ensure we make progress, start // the next search at the smallest possible starting position // of the next match following this one. self.last_end = self.re.next_after_empty(&self.text, e); // Don't accept empty matches immediately following a match. // Just move on to the next match. if Some(e) == self.last_match { return self.next(); } } else { self.last_end = e; } self.last_match = Some(e); Some((s, e)) } } /// An iterator over all non-overlapping successive leftmost-first matches with /// captures. pub struct FindCaptures<'t, R>(FindMatches<'t, R>) where R: RegularExpression, R::Text: 't; impl<'t, R> FindCaptures<'t, R> where R: RegularExpression, R::Text: 't { /// Return the text being searched. pub fn text(&self) -> &'t R::Text { self.0.text() } /// Return the underlying regex. pub fn regex(&self) -> &R
} impl<'t, R> Iterator for FindCaptures<'t, R> where R: RegularExpression, R::Text: 't + AsRef<[u8]> { type Item = Vec<Slot>; fn next(&mut self) -> Option<Vec<Slot>> { if self.0.last_end > self.0.text.as_ref().len() { return None } let mut slots = vec![None; self.0.re.slots_len()]; let (s, e) = match self.0.re.read_captures_at( &mut slots, self.0.text, self.0.last_end, ) { None => return None, Some((s, e)) => (s, e), }; if s == e { self.0.last_end = self.0.re.next_after_empty(&self.0.text, e); if Some(e) == self.0.last_match { return self.next(); } } else { self.0.last_end = e; } self.0.last_match = Some(e); Some(slots) } }
{ self.0.regex() }
identifier_body
issue-3794.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait T { fn print(&self); } struct S { s: int, } impl T for S { fn print(&self) { println!("{:?}", self); } } fn print_t(t: &T)
fn print_s(s: &S) { s.print(); } pub fn main() { let s: Box<S> = box S { s: 5 }; print_s(s); let t: Box<T> = s as Box<T>; print_t(t); }
{ t.print(); }
identifier_body
issue-3794.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait T { fn print(&self); } struct S { s: int, } impl T for S { fn
(&self) { println!("{:?}", self); } } fn print_t(t: &T) { t.print(); } fn print_s(s: &S) { s.print(); } pub fn main() { let s: Box<S> = box S { s: 5 }; print_s(s); let t: Box<T> = s as Box<T>; print_t(t); }
print
identifier_name
issue-3794.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait T { fn print(&self); } struct S { s: int, } impl T for S { fn print(&self) { println!("{:?}", self); } } fn print_t(t: &T) { t.print(); } fn print_s(s: &S) { s.print();
let t: Box<T> = s as Box<T>; print_t(t); }
} pub fn main() { let s: Box<S> = box S { s: 5 }; print_s(s);
random_line_split
acl.rs
use std::fmt; use std::ops; use std::string::ToString; /// Describes the ability of a user to perform a certain action. /// /// Permissions can be mixed together like integers with `|` and `&`. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Permission(u32); impl Permission { /// No permissions are set (server could have been configured without ACL support). pub const NONE: Permission = Permission(0b00000); /// You can access the data of a node and can list its children. pub const READ: Permission = Permission(0b00001); /// You can set the data of a node. pub const WRITE: Permission = Permission(0b00010); /// You can create a child node. pub const CREATE: Permission = Permission(0b00100); /// You can delete a child node (but not necessarily this one). pub const DELETE: Permission = Permission(0b01000); /// You can alter permissions on this node. pub const ADMIN: Permission = Permission(0b10000); /// You can do anything. pub const ALL: Permission = Permission(0b11111); /// Extract a permission value from raw `bits`. pub(crate) fn from_raw(bits: u32) -> Permission { Permission(bits) }
self.0 } /// Check that all `permissions` are set. /// /// ``` /// use zookeeper::Permission; /// /// (Permission::READ | Permission::WRITE).can(Permission::WRITE); // -> true /// Permission::ADMIN.can(Permission::CREATE); // -> false /// ``` pub fn can(self, permissions: Permission) -> bool { (self & permissions) == permissions } } impl ops::BitAnd for Permission { type Output = Self; fn bitand(self, rhs: Self) -> Self { Permission::from_raw(self.0 & rhs.0) } } impl ops::BitOr for Permission { type Output = Self; fn bitor(self, rhs: Self) -> Self { Permission::from_raw(self.0 | rhs.0) } } impl fmt::Display for Permission { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if *self == Permission::ALL { write!(f, "ALL") } else if *self == Permission::NONE { write!(f, "NONE") } else { let mut first = true; let mut tick = || { if first { first = false; "" } else { "|" } }; if self.can(Permission::READ) { write!(f, "{}READ", tick())?; } if self.can(Permission::WRITE) { write!(f, "{}WRITE", tick())?; } if self.can(Permission::CREATE) { write!(f, "{}CREATE", tick())?; } if self.can(Permission::DELETE) { write!(f, "{}DELETE", tick())?; } if self.can(Permission::ADMIN) { write!(f, "{}ADMIN", tick())?; } Ok(()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn permission_bitor() { let all = Permission::READ | Permission::WRITE | Permission::CREATE | Permission::DELETE | Permission::ADMIN; assert_eq!(Permission::ALL, all); } #[test] fn permission_can() { assert!(Permission::ALL.can(Permission::WRITE)); assert!(!Permission::WRITE.can(Permission::READ)); } #[test] fn permission_format() { assert_eq!("ALL", Permission::ALL.to_string()); assert_eq!("NONE", Permission::NONE.to_string()); assert_eq!("READ|WRITE", (Permission::READ | Permission::WRITE).to_string()); assert_eq!("CREATE|DELETE", (Permission::CREATE | Permission::DELETE).to_string()); assert_eq!("ADMIN", Permission::ADMIN.to_string()); } } /// An access control list. /// /// In general, the ACL system is similar to UNIX file access permissions, where znodes act as /// files. Unlike UNIX, each znode can have any number of ACLs to correspond with the potentially /// limitless (and pluggable) authentication schemes. A more surprising difference is that ACLs are /// not recursive: If `/path` is only readable by a single user, but `/path/sub` is world-readable, /// then anyone will be able to read `/path/sub`. /// /// See the [ZooKeeper Programmer's Guide](https://zookeeper.apache.org/doc/trunk/zookeeperProgrammers.html#sc_ZooKeeperAccessControl) /// for more information. #[derive(Clone, Debug, PartialEq)] pub struct Acl { /// The permissions associated with this ACL. pub perms: Permission, /// The authentication scheme this list is used for. The most common scheme is `"auth"`, which /// allows any authenticated user to do anything (see `creator_all`). pub scheme: String, /// The ID of the user under the `scheme`. For example, with the `"ip"` `scheme`, this is an IP /// address or CIDR netmask. pub id: String, } impl Acl { /// Create a new ACL with the given `permissions`, `scheme`, and `id`. pub fn new<T, U>(permissions: Permission, scheme: T, id: U) -> Acl where T: ToString, U: ToString { Acl { perms: permissions, scheme: scheme.to_string(), id: id.to_string(), } } /// This ACL gives the creators authentication id's all permissions. pub fn creator_all() -> &'static Vec<Acl> { &ACL_CREATOR_ALL } /// This is a completely open ACL. pub fn open_unsafe() -> &'static Vec<Acl> { &ACL_OPEN_UNSAFE } /// This ACL gives the world the ability to read. pub fn read_unsafe() -> &'static Vec<Acl> { &ACL_READ_UNSAFE } } lazy_static! { static ref ACL_CREATOR_ALL: Vec<Acl> = vec![Acl::new(Permission::ALL, "auth", "")]; static ref ACL_OPEN_UNSAFE: Vec<Acl> = vec![Acl::new(Permission::ALL, "world", "anyone")]; static ref ACL_READ_UNSAFE: Vec<Acl> = vec![Acl::new(Permission::READ, "world", "anyone")]; } impl fmt::Display for Acl { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}:{}, {})", self.scheme, self.id, self.perms) } }
pub(crate) fn code(&self) -> u32 {
random_line_split
acl.rs
use std::fmt; use std::ops; use std::string::ToString; /// Describes the ability of a user to perform a certain action. /// /// Permissions can be mixed together like integers with `|` and `&`. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Permission(u32); impl Permission { /// No permissions are set (server could have been configured without ACL support). pub const NONE: Permission = Permission(0b00000); /// You can access the data of a node and can list its children. pub const READ: Permission = Permission(0b00001); /// You can set the data of a node. pub const WRITE: Permission = Permission(0b00010); /// You can create a child node. pub const CREATE: Permission = Permission(0b00100); /// You can delete a child node (but not necessarily this one). pub const DELETE: Permission = Permission(0b01000); /// You can alter permissions on this node. pub const ADMIN: Permission = Permission(0b10000); /// You can do anything. pub const ALL: Permission = Permission(0b11111); /// Extract a permission value from raw `bits`. pub(crate) fn from_raw(bits: u32) -> Permission { Permission(bits) } pub(crate) fn code(&self) -> u32 { self.0 } /// Check that all `permissions` are set. /// /// ``` /// use zookeeper::Permission; /// /// (Permission::READ | Permission::WRITE).can(Permission::WRITE); // -> true /// Permission::ADMIN.can(Permission::CREATE); // -> false /// ``` pub fn can(self, permissions: Permission) -> bool { (self & permissions) == permissions } } impl ops::BitAnd for Permission { type Output = Self; fn bitand(self, rhs: Self) -> Self { Permission::from_raw(self.0 & rhs.0) } } impl ops::BitOr for Permission { type Output = Self; fn bitor(self, rhs: Self) -> Self { Permission::from_raw(self.0 | rhs.0) } } impl fmt::Display for Permission { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if *self == Permission::ALL { write!(f, "ALL") } else if *self == Permission::NONE { write!(f, "NONE") } else { let mut first = true; let mut tick = || { if first { first = false; "" } else { "|" } }; if self.can(Permission::READ) { write!(f, "{}READ", tick())?; } if self.can(Permission::WRITE) { write!(f, "{}WRITE", tick())?; } if self.can(Permission::CREATE) { write!(f, "{}CREATE", tick())?; } if self.can(Permission::DELETE) { write!(f, "{}DELETE", tick())?; } if self.can(Permission::ADMIN) { write!(f, "{}ADMIN", tick())?; } Ok(()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn permission_bitor() { let all = Permission::READ | Permission::WRITE | Permission::CREATE | Permission::DELETE | Permission::ADMIN; assert_eq!(Permission::ALL, all); } #[test] fn permission_can() { assert!(Permission::ALL.can(Permission::WRITE)); assert!(!Permission::WRITE.can(Permission::READ)); } #[test] fn permission_format() { assert_eq!("ALL", Permission::ALL.to_string()); assert_eq!("NONE", Permission::NONE.to_string()); assert_eq!("READ|WRITE", (Permission::READ | Permission::WRITE).to_string()); assert_eq!("CREATE|DELETE", (Permission::CREATE | Permission::DELETE).to_string()); assert_eq!("ADMIN", Permission::ADMIN.to_string()); } } /// An access control list. /// /// In general, the ACL system is similar to UNIX file access permissions, where znodes act as /// files. Unlike UNIX, each znode can have any number of ACLs to correspond with the potentially /// limitless (and pluggable) authentication schemes. A more surprising difference is that ACLs are /// not recursive: If `/path` is only readable by a single user, but `/path/sub` is world-readable, /// then anyone will be able to read `/path/sub`. /// /// See the [ZooKeeper Programmer's Guide](https://zookeeper.apache.org/doc/trunk/zookeeperProgrammers.html#sc_ZooKeeperAccessControl) /// for more information. #[derive(Clone, Debug, PartialEq)] pub struct Acl { /// The permissions associated with this ACL. pub perms: Permission, /// The authentication scheme this list is used for. The most common scheme is `"auth"`, which /// allows any authenticated user to do anything (see `creator_all`). pub scheme: String, /// The ID of the user under the `scheme`. For example, with the `"ip"` `scheme`, this is an IP /// address or CIDR netmask. pub id: String, } impl Acl { /// Create a new ACL with the given `permissions`, `scheme`, and `id`. pub fn new<T, U>(permissions: Permission, scheme: T, id: U) -> Acl where T: ToString, U: ToString { Acl { perms: permissions, scheme: scheme.to_string(), id: id.to_string(), } } /// This ACL gives the creators authentication id's all permissions. pub fn creator_all() -> &'static Vec<Acl> { &ACL_CREATOR_ALL } /// This is a completely open ACL. pub fn
() -> &'static Vec<Acl> { &ACL_OPEN_UNSAFE } /// This ACL gives the world the ability to read. pub fn read_unsafe() -> &'static Vec<Acl> { &ACL_READ_UNSAFE } } lazy_static! { static ref ACL_CREATOR_ALL: Vec<Acl> = vec![Acl::new(Permission::ALL, "auth", "")]; static ref ACL_OPEN_UNSAFE: Vec<Acl> = vec![Acl::new(Permission::ALL, "world", "anyone")]; static ref ACL_READ_UNSAFE: Vec<Acl> = vec![Acl::new(Permission::READ, "world", "anyone")]; } impl fmt::Display for Acl { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}:{}, {})", self.scheme, self.id, self.perms) } }
open_unsafe
identifier_name
acl.rs
use std::fmt; use std::ops; use std::string::ToString; /// Describes the ability of a user to perform a certain action. /// /// Permissions can be mixed together like integers with `|` and `&`. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Permission(u32); impl Permission { /// No permissions are set (server could have been configured without ACL support). pub const NONE: Permission = Permission(0b00000); /// You can access the data of a node and can list its children. pub const READ: Permission = Permission(0b00001); /// You can set the data of a node. pub const WRITE: Permission = Permission(0b00010); /// You can create a child node. pub const CREATE: Permission = Permission(0b00100); /// You can delete a child node (but not necessarily this one). pub const DELETE: Permission = Permission(0b01000); /// You can alter permissions on this node. pub const ADMIN: Permission = Permission(0b10000); /// You can do anything. pub const ALL: Permission = Permission(0b11111); /// Extract a permission value from raw `bits`. pub(crate) fn from_raw(bits: u32) -> Permission { Permission(bits) } pub(crate) fn code(&self) -> u32 { self.0 } /// Check that all `permissions` are set. /// /// ``` /// use zookeeper::Permission; /// /// (Permission::READ | Permission::WRITE).can(Permission::WRITE); // -> true /// Permission::ADMIN.can(Permission::CREATE); // -> false /// ``` pub fn can(self, permissions: Permission) -> bool { (self & permissions) == permissions } } impl ops::BitAnd for Permission { type Output = Self; fn bitand(self, rhs: Self) -> Self { Permission::from_raw(self.0 & rhs.0) } } impl ops::BitOr for Permission { type Output = Self; fn bitor(self, rhs: Self) -> Self { Permission::from_raw(self.0 | rhs.0) } } impl fmt::Display for Permission { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if *self == Permission::ALL { write!(f, "ALL") } else if *self == Permission::NONE { write!(f, "NONE") } else { let mut first = true; let mut tick = || { if first { first = false; "" } else { "|" } }; if self.can(Permission::READ) { write!(f, "{}READ", tick())?; } if self.can(Permission::WRITE) { write!(f, "{}WRITE", tick())?; } if self.can(Permission::CREATE) { write!(f, "{}CREATE", tick())?; } if self.can(Permission::DELETE)
if self.can(Permission::ADMIN) { write!(f, "{}ADMIN", tick())?; } Ok(()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn permission_bitor() { let all = Permission::READ | Permission::WRITE | Permission::CREATE | Permission::DELETE | Permission::ADMIN; assert_eq!(Permission::ALL, all); } #[test] fn permission_can() { assert!(Permission::ALL.can(Permission::WRITE)); assert!(!Permission::WRITE.can(Permission::READ)); } #[test] fn permission_format() { assert_eq!("ALL", Permission::ALL.to_string()); assert_eq!("NONE", Permission::NONE.to_string()); assert_eq!("READ|WRITE", (Permission::READ | Permission::WRITE).to_string()); assert_eq!("CREATE|DELETE", (Permission::CREATE | Permission::DELETE).to_string()); assert_eq!("ADMIN", Permission::ADMIN.to_string()); } } /// An access control list. /// /// In general, the ACL system is similar to UNIX file access permissions, where znodes act as /// files. Unlike UNIX, each znode can have any number of ACLs to correspond with the potentially /// limitless (and pluggable) authentication schemes. A more surprising difference is that ACLs are /// not recursive: If `/path` is only readable by a single user, but `/path/sub` is world-readable, /// then anyone will be able to read `/path/sub`. /// /// See the [ZooKeeper Programmer's Guide](https://zookeeper.apache.org/doc/trunk/zookeeperProgrammers.html#sc_ZooKeeperAccessControl) /// for more information. #[derive(Clone, Debug, PartialEq)] pub struct Acl { /// The permissions associated with this ACL. pub perms: Permission, /// The authentication scheme this list is used for. The most common scheme is `"auth"`, which /// allows any authenticated user to do anything (see `creator_all`). pub scheme: String, /// The ID of the user under the `scheme`. For example, with the `"ip"` `scheme`, this is an IP /// address or CIDR netmask. pub id: String, } impl Acl { /// Create a new ACL with the given `permissions`, `scheme`, and `id`. pub fn new<T, U>(permissions: Permission, scheme: T, id: U) -> Acl where T: ToString, U: ToString { Acl { perms: permissions, scheme: scheme.to_string(), id: id.to_string(), } } /// This ACL gives the creators authentication id's all permissions. pub fn creator_all() -> &'static Vec<Acl> { &ACL_CREATOR_ALL } /// This is a completely open ACL. pub fn open_unsafe() -> &'static Vec<Acl> { &ACL_OPEN_UNSAFE } /// This ACL gives the world the ability to read. pub fn read_unsafe() -> &'static Vec<Acl> { &ACL_READ_UNSAFE } } lazy_static! { static ref ACL_CREATOR_ALL: Vec<Acl> = vec![Acl::new(Permission::ALL, "auth", "")]; static ref ACL_OPEN_UNSAFE: Vec<Acl> = vec![Acl::new(Permission::ALL, "world", "anyone")]; static ref ACL_READ_UNSAFE: Vec<Acl> = vec![Acl::new(Permission::READ, "world", "anyone")]; } impl fmt::Display for Acl { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}:{}, {})", self.scheme, self.id, self.perms) } }
{ write!(f, "{}DELETE", tick())?; }
conditional_block
acl.rs
use std::fmt; use std::ops; use std::string::ToString; /// Describes the ability of a user to perform a certain action. /// /// Permissions can be mixed together like integers with `|` and `&`. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Permission(u32); impl Permission { /// No permissions are set (server could have been configured without ACL support). pub const NONE: Permission = Permission(0b00000); /// You can access the data of a node and can list its children. pub const READ: Permission = Permission(0b00001); /// You can set the data of a node. pub const WRITE: Permission = Permission(0b00010); /// You can create a child node. pub const CREATE: Permission = Permission(0b00100); /// You can delete a child node (but not necessarily this one). pub const DELETE: Permission = Permission(0b01000); /// You can alter permissions on this node. pub const ADMIN: Permission = Permission(0b10000); /// You can do anything. pub const ALL: Permission = Permission(0b11111); /// Extract a permission value from raw `bits`. pub(crate) fn from_raw(bits: u32) -> Permission { Permission(bits) } pub(crate) fn code(&self) -> u32 { self.0 } /// Check that all `permissions` are set. /// /// ``` /// use zookeeper::Permission; /// /// (Permission::READ | Permission::WRITE).can(Permission::WRITE); // -> true /// Permission::ADMIN.can(Permission::CREATE); // -> false /// ``` pub fn can(self, permissions: Permission) -> bool { (self & permissions) == permissions } } impl ops::BitAnd for Permission { type Output = Self; fn bitand(self, rhs: Self) -> Self { Permission::from_raw(self.0 & rhs.0) } } impl ops::BitOr for Permission { type Output = Self; fn bitor(self, rhs: Self) -> Self
} impl fmt::Display for Permission { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if *self == Permission::ALL { write!(f, "ALL") } else if *self == Permission::NONE { write!(f, "NONE") } else { let mut first = true; let mut tick = || { if first { first = false; "" } else { "|" } }; if self.can(Permission::READ) { write!(f, "{}READ", tick())?; } if self.can(Permission::WRITE) { write!(f, "{}WRITE", tick())?; } if self.can(Permission::CREATE) { write!(f, "{}CREATE", tick())?; } if self.can(Permission::DELETE) { write!(f, "{}DELETE", tick())?; } if self.can(Permission::ADMIN) { write!(f, "{}ADMIN", tick())?; } Ok(()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn permission_bitor() { let all = Permission::READ | Permission::WRITE | Permission::CREATE | Permission::DELETE | Permission::ADMIN; assert_eq!(Permission::ALL, all); } #[test] fn permission_can() { assert!(Permission::ALL.can(Permission::WRITE)); assert!(!Permission::WRITE.can(Permission::READ)); } #[test] fn permission_format() { assert_eq!("ALL", Permission::ALL.to_string()); assert_eq!("NONE", Permission::NONE.to_string()); assert_eq!("READ|WRITE", (Permission::READ | Permission::WRITE).to_string()); assert_eq!("CREATE|DELETE", (Permission::CREATE | Permission::DELETE).to_string()); assert_eq!("ADMIN", Permission::ADMIN.to_string()); } } /// An access control list. /// /// In general, the ACL system is similar to UNIX file access permissions, where znodes act as /// files. Unlike UNIX, each znode can have any number of ACLs to correspond with the potentially /// limitless (and pluggable) authentication schemes. A more surprising difference is that ACLs are /// not recursive: If `/path` is only readable by a single user, but `/path/sub` is world-readable, /// then anyone will be able to read `/path/sub`. /// /// See the [ZooKeeper Programmer's Guide](https://zookeeper.apache.org/doc/trunk/zookeeperProgrammers.html#sc_ZooKeeperAccessControl) /// for more information. #[derive(Clone, Debug, PartialEq)] pub struct Acl { /// The permissions associated with this ACL. pub perms: Permission, /// The authentication scheme this list is used for. The most common scheme is `"auth"`, which /// allows any authenticated user to do anything (see `creator_all`). pub scheme: String, /// The ID of the user under the `scheme`. For example, with the `"ip"` `scheme`, this is an IP /// address or CIDR netmask. pub id: String, } impl Acl { /// Create a new ACL with the given `permissions`, `scheme`, and `id`. pub fn new<T, U>(permissions: Permission, scheme: T, id: U) -> Acl where T: ToString, U: ToString { Acl { perms: permissions, scheme: scheme.to_string(), id: id.to_string(), } } /// This ACL gives the creators authentication id's all permissions. pub fn creator_all() -> &'static Vec<Acl> { &ACL_CREATOR_ALL } /// This is a completely open ACL. pub fn open_unsafe() -> &'static Vec<Acl> { &ACL_OPEN_UNSAFE } /// This ACL gives the world the ability to read. pub fn read_unsafe() -> &'static Vec<Acl> { &ACL_READ_UNSAFE } } lazy_static! { static ref ACL_CREATOR_ALL: Vec<Acl> = vec![Acl::new(Permission::ALL, "auth", "")]; static ref ACL_OPEN_UNSAFE: Vec<Acl> = vec![Acl::new(Permission::ALL, "world", "anyone")]; static ref ACL_READ_UNSAFE: Vec<Acl> = vec![Acl::new(Permission::READ, "world", "anyone")]; } impl fmt::Display for Acl { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}:{}, {})", self.scheme, self.id, self.perms) } }
{ Permission::from_raw(self.0 | rhs.0) }
identifier_body
helloworld.rs
#include <constants.rh> #include <crctools.rh> #include <math.rh> #include <util.rh> ; vim: syntax=fasm ; Test RAR assembly file that just demonstrates the syntax. ; ; Usage: ; ; $ unrar p -inul helloworld.rar ; Hello, World! ; _start: ; Install our message in the output buffer mov r3, #0x1000 ; Output buffer. mov [r3+#0], #0x6c6c6548 ; 'lleH'
call $_success
mov [r3+#4], #0x57202c6f ; 'W ,o' mov [r3+#8], #0x646c726f ; 'dlro' mov [r3+#12], #0x00000a21 ; '!\n' mov [VMADDR_NEWBLOCKPOS], r3 ; Pointer mov [VMADDR_NEWBLOCKSIZE], #14 ; Size
random_line_split
mod.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <[email protected]> | // | | // | This file is part of System Syzygy. | // | | // | System Syzygy 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. | // | | // | System Syzygy 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 details. | // | |
mod view; pub use self::control::run_title_screen; // ========================================================================= //
// | You should have received a copy of the GNU General Public License along | // | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. | // +--------------------------------------------------------------------------+ mod control;
random_line_split
token.rs
use combine::primitives::Positioner; use conv::ValueFrom; use std::fmt; #[derive(Clone, Debug, PartialEq)] pub enum Literal { Bool(bool), Int(i64), Flt(f64), Str(String), } #[derive(Clone, Debug, PartialEq)] pub enum Token { LParen, RParen, LBracket, RBracket, Quote, Literal(Literal), Symbol(String), } impl Positioner for Token { type Position = <char as Positioner>::Position; fn start() -> Self::Position { char::start() } fn update(&self, position: &mut Self::Position) { match *self { Token::LParen => position.column += 1, Token::RParen => position.column += 1, Token::LBracket => position.column += 1, Token::RBracket => position.column += 1, Token::Quote => position.column += 1, Token::Literal(ref l) => { position.column += i32::value_from(l.to_string().len()).unwrap() } Token::Symbol(ref s) => position.column += i32::value_from(s.len()).unwrap(), } } } impl fmt::Display for Literal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Literal::Bool(ref b) => write!(f, "{}", b), Literal::Int(ref i) => write!(f, "{}", i), Literal::Flt(ref x) => write!(f, "{}", x), Literal::Str(ref s) => write!(f, "{}", s), } } } impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} impl From<i32> for Literal { fn from(x: i32) -> Self { Literal::Int(x.into()) } } impl From<i64> for Literal { fn from(x: i64) -> Self { Literal::Int(x) } } impl From<f32> for Literal { fn from(x: f32) -> Self { Literal::Flt(x.into()) } } impl From<f64> for Literal { fn from(x: f64) -> Self { Literal::Flt(x) } } impl From<bool> for Literal { fn from(x: bool) -> Self { Literal::Bool(x) } } impl<'a> From<&'a str> for Literal { fn from(x: &'a str) -> Self { Literal::Str(x.to_owned()) } } impl From<String> for Literal { fn from(x: String) -> Self { Literal::Str(x) } } impl<T> From<T> for Token where T: Into<Literal>, { fn from(x: T) -> Self { Token::Literal(x.into()) } } #[cfg(test)] mod test { use super::*; #[test] fn format_literal() { let int = Literal::from(32i64); let flt = Literal::from(3.14f64); let boolean = Literal::from(true); let string = Literal::from("jkl;"); assert_eq!("32", int.to_string()); assert_eq!("3.14", flt.to_string()); assert_eq!("true", boolean.to_string()); assert_eq!("jkl;", string.to_string()); } #[test] fn format_token() { let lparen = Token::LParen; // Literal let literal = Token::from(1); assert_eq!("LParen", lparen.to_string()); assert_eq!("1", literal.to_string()); } }
{ match *self { Token::Literal(ref lit) => write!(f, "{}", lit), Token::Symbol(ref s) => write!(f, "{}", s), _ => write!(f, "{:#?}", self), } }
identifier_body
token.rs
use combine::primitives::Positioner; use conv::ValueFrom; use std::fmt; #[derive(Clone, Debug, PartialEq)] pub enum Literal { Bool(bool), Int(i64), Flt(f64), Str(String), } #[derive(Clone, Debug, PartialEq)] pub enum Token { LParen, RParen, LBracket, RBracket, Quote, Literal(Literal), Symbol(String), } impl Positioner for Token { type Position = <char as Positioner>::Position; fn start() -> Self::Position { char::start() } fn update(&self, position: &mut Self::Position) { match *self { Token::LParen => position.column += 1, Token::RParen => position.column += 1, Token::LBracket => position.column += 1, Token::RBracket => position.column += 1, Token::Quote => position.column += 1, Token::Literal(ref l) => { position.column += i32::value_from(l.to_string().len()).unwrap() } Token::Symbol(ref s) => position.column += i32::value_from(s.len()).unwrap(), } } } impl fmt::Display for Literal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Literal::Bool(ref b) => write!(f, "{}", b), Literal::Int(ref i) => write!(f, "{}", i), Literal::Flt(ref x) => write!(f, "{}", x), Literal::Str(ref s) => write!(f, "{}", s), } } } impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Token::Literal(ref lit) => write!(f, "{}", lit), Token::Symbol(ref s) => write!(f, "{}", s), _ => write!(f, "{:#?}", self), } } } impl From<i32> for Literal { fn from(x: i32) -> Self { Literal::Int(x.into()) } } impl From<i64> for Literal { fn from(x: i64) -> Self { Literal::Int(x) } } impl From<f32> for Literal {
} impl From<f64> for Literal { fn from(x: f64) -> Self { Literal::Flt(x) } } impl From<bool> for Literal { fn from(x: bool) -> Self { Literal::Bool(x) } } impl<'a> From<&'a str> for Literal { fn from(x: &'a str) -> Self { Literal::Str(x.to_owned()) } } impl From<String> for Literal { fn from(x: String) -> Self { Literal::Str(x) } } impl<T> From<T> for Token where T: Into<Literal>, { fn from(x: T) -> Self { Token::Literal(x.into()) } } #[cfg(test)] mod test { use super::*; #[test] fn format_literal() { let int = Literal::from(32i64); let flt = Literal::from(3.14f64); let boolean = Literal::from(true); let string = Literal::from("jkl;"); assert_eq!("32", int.to_string()); assert_eq!("3.14", flt.to_string()); assert_eq!("true", boolean.to_string()); assert_eq!("jkl;", string.to_string()); } #[test] fn format_token() { let lparen = Token::LParen; // Literal let literal = Token::from(1); assert_eq!("LParen", lparen.to_string()); assert_eq!("1", literal.to_string()); } }
fn from(x: f32) -> Self { Literal::Flt(x.into()) }
random_line_split
token.rs
use combine::primitives::Positioner; use conv::ValueFrom; use std::fmt; #[derive(Clone, Debug, PartialEq)] pub enum Literal { Bool(bool), Int(i64), Flt(f64), Str(String), } #[derive(Clone, Debug, PartialEq)] pub enum Token { LParen, RParen, LBracket, RBracket, Quote, Literal(Literal), Symbol(String), } impl Positioner for Token { type Position = <char as Positioner>::Position; fn start() -> Self::Position { char::start() } fn update(&self, position: &mut Self::Position) { match *self { Token::LParen => position.column += 1, Token::RParen => position.column += 1, Token::LBracket => position.column += 1, Token::RBracket => position.column += 1, Token::Quote => position.column += 1, Token::Literal(ref l) => { position.column += i32::value_from(l.to_string().len()).unwrap() } Token::Symbol(ref s) => position.column += i32::value_from(s.len()).unwrap(), } } } impl fmt::Display for Literal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Literal::Bool(ref b) => write!(f, "{}", b), Literal::Int(ref i) => write!(f, "{}", i), Literal::Flt(ref x) => write!(f, "{}", x), Literal::Str(ref s) => write!(f, "{}", s), } } } impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Token::Literal(ref lit) => write!(f, "{}", lit), Token::Symbol(ref s) => write!(f, "{}", s), _ => write!(f, "{:#?}", self), } } } impl From<i32> for Literal { fn from(x: i32) -> Self { Literal::Int(x.into()) } } impl From<i64> for Literal { fn from(x: i64) -> Self { Literal::Int(x) } } impl From<f32> for Literal { fn from(x: f32) -> Self { Literal::Flt(x.into()) } } impl From<f64> for Literal { fn from(x: f64) -> Self { Literal::Flt(x) } } impl From<bool> for Literal { fn from(x: bool) -> Self { Literal::Bool(x) } } impl<'a> From<&'a str> for Literal { fn from(x: &'a str) -> Self { Literal::Str(x.to_owned()) } } impl From<String> for Literal { fn
(x: String) -> Self { Literal::Str(x) } } impl<T> From<T> for Token where T: Into<Literal>, { fn from(x: T) -> Self { Token::Literal(x.into()) } } #[cfg(test)] mod test { use super::*; #[test] fn format_literal() { let int = Literal::from(32i64); let flt = Literal::from(3.14f64); let boolean = Literal::from(true); let string = Literal::from("jkl;"); assert_eq!("32", int.to_string()); assert_eq!("3.14", flt.to_string()); assert_eq!("true", boolean.to_string()); assert_eq!("jkl;", string.to_string()); } #[test] fn format_token() { let lparen = Token::LParen; // Literal let literal = Token::from(1); assert_eq!("LParen", lparen.to_string()); assert_eq!("1", literal.to_string()); } }
from
identifier_name
error.rs
use std::error::Error; use std::fmt; use std::io; use std::result; pub type Result<T> = result::Result<T, StreamDelimitError>; #[derive(Debug)] pub enum StreamDelimitError { #[cfg(feature = "with_kafka")] KafkaInitializeError(::kafka::error::Error), VarintDecodeError(io::Error), InvalidStreamTypeError(String), VarintDecodeMaxBytesError, } impl fmt::Display for StreamDelimitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(ref e) => { write!(f, "Couldn't initialize kafka consumer: {}", e) } StreamDelimitError::VarintDecodeError(ref e) => { write!(f, "Couldn't decode leading varint: {}", e) } StreamDelimitError::InvalidStreamTypeError(ref t) => write!( f, "Invalid stream type: {} (only support single,leb128,varint)", t ), StreamDelimitError::VarintDecodeMaxBytesError => { write!(f, "Exceeded max attempts to decode leading varint") } } } } impl Error for StreamDelimitError { fn
(&self) -> &str { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(_) => "couldn't initialize kafka consumer", StreamDelimitError::VarintDecodeError(_) | StreamDelimitError::VarintDecodeMaxBytesError => "couldn't decode leading varint", StreamDelimitError::InvalidStreamTypeError(_) => "invalid stream type", } } fn cause(&self) -> Option<&dyn Error> { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(ref e) => Some(e), StreamDelimitError::VarintDecodeError(ref e) => Some(e), StreamDelimitError::InvalidStreamTypeError(_) | StreamDelimitError::VarintDecodeMaxBytesError => None, } } }
description
identifier_name
error.rs
use std::error::Error; use std::fmt; use std::io; use std::result;
pub type Result<T> = result::Result<T, StreamDelimitError>; #[derive(Debug)] pub enum StreamDelimitError { #[cfg(feature = "with_kafka")] KafkaInitializeError(::kafka::error::Error), VarintDecodeError(io::Error), InvalidStreamTypeError(String), VarintDecodeMaxBytesError, } impl fmt::Display for StreamDelimitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(ref e) => { write!(f, "Couldn't initialize kafka consumer: {}", e) } StreamDelimitError::VarintDecodeError(ref e) => { write!(f, "Couldn't decode leading varint: {}", e) } StreamDelimitError::InvalidStreamTypeError(ref t) => write!( f, "Invalid stream type: {} (only support single,leb128,varint)", t ), StreamDelimitError::VarintDecodeMaxBytesError => { write!(f, "Exceeded max attempts to decode leading varint") } } } } impl Error for StreamDelimitError { fn description(&self) -> &str { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(_) => "couldn't initialize kafka consumer", StreamDelimitError::VarintDecodeError(_) | StreamDelimitError::VarintDecodeMaxBytesError => "couldn't decode leading varint", StreamDelimitError::InvalidStreamTypeError(_) => "invalid stream type", } } fn cause(&self) -> Option<&dyn Error> { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(ref e) => Some(e), StreamDelimitError::VarintDecodeError(ref e) => Some(e), StreamDelimitError::InvalidStreamTypeError(_) | StreamDelimitError::VarintDecodeMaxBytesError => None, } } }
random_line_split
error.rs
use std::error::Error; use std::fmt; use std::io; use std::result; pub type Result<T> = result::Result<T, StreamDelimitError>; #[derive(Debug)] pub enum StreamDelimitError { #[cfg(feature = "with_kafka")] KafkaInitializeError(::kafka::error::Error), VarintDecodeError(io::Error), InvalidStreamTypeError(String), VarintDecodeMaxBytesError, } impl fmt::Display for StreamDelimitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} impl Error for StreamDelimitError { fn description(&self) -> &str { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(_) => "couldn't initialize kafka consumer", StreamDelimitError::VarintDecodeError(_) | StreamDelimitError::VarintDecodeMaxBytesError => "couldn't decode leading varint", StreamDelimitError::InvalidStreamTypeError(_) => "invalid stream type", } } fn cause(&self) -> Option<&dyn Error> { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(ref e) => Some(e), StreamDelimitError::VarintDecodeError(ref e) => Some(e), StreamDelimitError::InvalidStreamTypeError(_) | StreamDelimitError::VarintDecodeMaxBytesError => None, } } }
{ match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(ref e) => { write!(f, "Couldn't initialize kafka consumer: {}", e) } StreamDelimitError::VarintDecodeError(ref e) => { write!(f, "Couldn't decode leading varint: {}", e) } StreamDelimitError::InvalidStreamTypeError(ref t) => write!( f, "Invalid stream type: {} (only support single,leb128,varint)", t ), StreamDelimitError::VarintDecodeMaxBytesError => { write!(f, "Exceeded max attempts to decode leading varint") } } }
identifier_body
publish.rs
use std::path::PathBuf; use std::io::prelude::*; use std::fs::{self, File}; use support::paths; use support::git::{repo, Repository}; use url::Url; pub fn
() -> Repository { let config = paths::root().join(".cargo/config"); t!(fs::create_dir_all(config.parent().unwrap())); t!(t!(File::create(&config)).write_all(format!(r#" [registry] token = "api-token" [registries.alternative] index = "{registry}" "#, registry = registry().to_string()).as_bytes())); let credentials = paths::root().join("home/.cargo/credentials"); t!(fs::create_dir_all(credentials.parent().unwrap())); t!(t!(File::create(&credentials)).write_all(br#" [alternative] token = "api-token" "#)); t!(fs::create_dir_all(&upload_path().join("api/v1/crates"))); repo(&registry_path()) .file("config.json", &format!(r#"{{ "dl": "{0}", "api": "{0}" }}"#, upload())) .build() } fn registry_path() -> PathBuf { paths::root().join("registry") } pub fn registry() -> Url { Url::from_file_path(&*registry_path()).ok().unwrap() } pub fn upload_path() -> PathBuf { paths::root().join("upload") } fn upload() -> Url { Url::from_file_path(&*upload_path()).ok().unwrap() }
setup
identifier_name
publish.rs
use std::path::PathBuf; use std::io::prelude::*; use std::fs::{self, File}; use support::paths; use support::git::{repo, Repository}; use url::Url; pub fn setup() -> Repository
repo(&registry_path()) .file("config.json", &format!(r#"{{ "dl": "{0}", "api": "{0}" }}"#, upload())) .build() } fn registry_path() -> PathBuf { paths::root().join("registry") } pub fn registry() -> Url { Url::from_file_path(&*registry_path()).ok().unwrap() } pub fn upload_path() -> PathBuf { paths::root().join("upload") } fn upload() -> Url { Url::from_file_path(&*upload_path()).ok().unwrap() }
{ let config = paths::root().join(".cargo/config"); t!(fs::create_dir_all(config.parent().unwrap())); t!(t!(File::create(&config)).write_all(format!(r#" [registry] token = "api-token" [registries.alternative] index = "{registry}" "#, registry = registry().to_string()).as_bytes())); let credentials = paths::root().join("home/.cargo/credentials"); t!(fs::create_dir_all(credentials.parent().unwrap())); t!(t!(File::create(&credentials)).write_all(br#" [alternative] token = "api-token" "#)); t!(fs::create_dir_all(&upload_path().join("api/v1/crates")));
identifier_body
publish.rs
use std::path::PathBuf; use std::io::prelude::*; use std::fs::{self, File}; use support::paths; use support::git::{repo, Repository}; use url::Url; pub fn setup() -> Repository { let config = paths::root().join(".cargo/config"); t!(fs::create_dir_all(config.parent().unwrap())); t!(t!(File::create(&config)).write_all(format!(r#" [registry] token = "api-token" [registries.alternative] index = "{registry}" "#, registry = registry().to_string()).as_bytes())); let credentials = paths::root().join("home/.cargo/credentials"); t!(fs::create_dir_all(credentials.parent().unwrap())); t!(t!(File::create(&credentials)).write_all(br#" [alternative] token = "api-token" "#)); t!(fs::create_dir_all(&upload_path().join("api/v1/crates"))); repo(&registry_path()) .file("config.json", &format!(r#"{{ "dl": "{0}", "api": "{0}" }}"#, upload())) .build() } fn registry_path() -> PathBuf { paths::root().join("registry") }
pub fn upload_path() -> PathBuf { paths::root().join("upload") } fn upload() -> Url { Url::from_file_path(&*upload_path()).ok().unwrap() }
pub fn registry() -> Url { Url::from_file_path(&*registry_path()).ok().unwrap() }
random_line_split
timeout.rs
// * This file is part of the uutils coreutils package. // * // * (c) Alex Lyon <[email protected]> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. // spell-checker:ignore (ToDO) tstr sigstr cmdname setpgid sigchld #[macro_use] extern crate uucore; extern crate clap; use clap::{crate_version, App, AppSettings, Arg}; use std::io::ErrorKind; use std::process::{Command, Stdio}; use std::time::Duration; use uucore::display::Quotable; use uucore::error::{UResult, USimpleError}; use uucore::process::ChildExt; use uucore::signals::{signal_by_name_or_value, signal_name_by_value}; use uucore::{format_usage, InvalidEncodingHandling}; static ABOUT: &str = "Start COMMAND, and kill it if still running after DURATION."; const USAGE: &str = "{} [OPTION] DURATION COMMAND..."; const ERR_EXIT_STATUS: i32 = 125; pub mod options { pub static FOREGROUND: &str = "foreground"; pub static KILL_AFTER: &str = "kill-after"; pub static SIGNAL: &str = "signal"; pub static PRESERVE_STATUS: &str = "preserve-status"; pub static VERBOSE: &str = "verbose"; // Positional args. pub static DURATION: &str = "duration"; pub static COMMAND: &str = "command"; } struct Config { foreground: bool, kill_after: Option<Duration>, signal: usize, duration: Duration, preserve_status: bool, verbose: bool, command: Vec<String>, } impl Config { fn from(options: &clap::ArgMatches) -> UResult<Self> { let signal = match options.value_of(options::SIGNAL) { Some(signal_) => { let signal_result = signal_by_name_or_value(signal_); match signal_result { None => { unreachable!("invalid signal {}", signal_.quote()); } Some(signal_value) => signal_value, } } _ => uucore::signals::signal_by_name_or_value("TERM").unwrap(), }; let kill_after = options .value_of(options::KILL_AFTER) .map(|time| uucore::parse_time::from_str(time).unwrap()); let duration = match uucore::parse_time::from_str(options.value_of(options::DURATION).unwrap()) { Ok(duration) => duration, Err(err) => return Err(USimpleError::new(1, err)), }; let preserve_status: bool = options.is_present(options::PRESERVE_STATUS); let foreground = options.is_present(options::FOREGROUND); let verbose = options.is_present(options::VERBOSE); let command = options .values_of(options::COMMAND) .unwrap() .map(String::from) .collect::<Vec<_>>(); Ok(Self { foreground, kill_after, signal, duration, preserve_status, verbose, command, }) } } #[uucore::main] pub fn
(args: impl uucore::Args) -> UResult<()> { let args = args .collect_str(InvalidEncodingHandling::ConvertLossy) .accept_any(); let app = uu_app(); let matches = app.get_matches_from(args); let config = Config::from(&matches)?; timeout( &config.command, config.duration, config.signal, config.kill_after, config.foreground, config.preserve_status, config.verbose, ) } pub fn uu_app<'a>() -> App<'a> { App::new("timeout") .version(crate_version!()) .about(ABOUT) .override_usage(format_usage(USAGE)) .arg( Arg::new(options::FOREGROUND) .long(options::FOREGROUND) .help("when not running timeout directly from a shell prompt, allow COMMAND to read from the TTY and get TTY signals; in this mode, children of COMMAND will not be timed out") ) .arg( Arg::new(options::KILL_AFTER) .short('k') .takes_value(true)) .arg( Arg::new(options::PRESERVE_STATUS) .long(options::PRESERVE_STATUS) .help("exit with the same status as COMMAND, even when the command times out") ) .arg( Arg::new(options::SIGNAL) .short('s') .long(options::SIGNAL) .help("specify the signal to be sent on timeout; SIGNAL may be a name like 'HUP' or a number; see 'kill -l' for a list of signals") .takes_value(true) ) .arg( Arg::new(options::VERBOSE) .short('v') .long(options::VERBOSE) .help("diagnose to stderr any signal sent upon timeout") ) .arg( Arg::new(options::DURATION) .index(1) .required(true) ) .arg( Arg::new(options::COMMAND) .index(2) .required(true) .multiple_occurrences(true) ) .setting(AppSettings::TrailingVarArg) .setting(AppSettings::InferLongArgs) } /// Remove pre-existing SIGCHLD handlers that would make waiting for the child's exit code fail. fn unblock_sigchld() { unsafe { nix::sys::signal::signal( nix::sys::signal::Signal::SIGCHLD, nix::sys::signal::SigHandler::SigDfl, ) .unwrap(); } } /// TODO: Improve exit codes, and make them consistent with the GNU Coreutils exit codes. fn timeout( cmd: &[String], duration: Duration, signal: usize, kill_after: Option<Duration>, foreground: bool, preserve_status: bool, verbose: bool, ) -> UResult<()> { if!foreground { unsafe { libc::setpgid(0, 0) }; } let mut process = Command::new(&cmd[0]) .args(&cmd[1..]) .stdin(Stdio::inherit()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .spawn() .map_err(|err| { let status_code = if err.kind() == ErrorKind::NotFound { // FIXME: not sure which to use 127 } else { // FIXME: this may not be 100% correct... 126 }; USimpleError::new(status_code, format!("failed to execute process: {}", err)) })?; unblock_sigchld(); match process.wait_or_timeout(duration) { Ok(Some(status)) => { let status_code = status.code().unwrap_or_else(|| status.signal().unwrap()); if status_code == 0 { Ok(()) } else { Err(status_code.into()) } } Ok(None) => { if verbose { show_error!( "sending signal {} to command {}", signal_name_by_value(signal).unwrap(), cmd[0].quote() ); } process .send_signal(signal) .map_err(|e| USimpleError::new(ERR_EXIT_STATUS, format!("{}", e)))?; if let Some(kill_after) = kill_after { match process.wait_or_timeout(kill_after) { Ok(Some(status)) => { if preserve_status { let status_code = status.code().unwrap_or_else(|| status.signal().unwrap()); if status_code == 0 { Ok(()) } else { Err(status_code.into()) } } else { Err(124.into()) } } Ok(None) => { if verbose { show_error!("sending signal KILL to command {}", cmd[0].quote()); } process .send_signal(uucore::signals::signal_by_name_or_value("KILL").unwrap()) .map_err(|e| USimpleError::new(ERR_EXIT_STATUS, format!("{}", e)))?; process .wait() .map_err(|e| USimpleError::new(ERR_EXIT_STATUS, format!("{}", e)))?; Err(137.into()) } Err(_) => Err(124.into()), } } else { Err(124.into()) } } Err(_) => { // We're going to return ERR_EXIT_STATUS regardless of // whether `send_signal()` succeeds or fails, so just // ignore the return value. process .send_signal(signal) .map_err(|e| USimpleError::new(ERR_EXIT_STATUS, format!("{}", e)))?; Err(ERR_EXIT_STATUS.into()) } } }
uumain
identifier_name
timeout.rs
// * This file is part of the uutils coreutils package. // * // * (c) Alex Lyon <[email protected]> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. // spell-checker:ignore (ToDO) tstr sigstr cmdname setpgid sigchld #[macro_use] extern crate uucore; extern crate clap; use clap::{crate_version, App, AppSettings, Arg}; use std::io::ErrorKind; use std::process::{Command, Stdio}; use std::time::Duration; use uucore::display::Quotable; use uucore::error::{UResult, USimpleError}; use uucore::process::ChildExt; use uucore::signals::{signal_by_name_or_value, signal_name_by_value}; use uucore::{format_usage, InvalidEncodingHandling}; static ABOUT: &str = "Start COMMAND, and kill it if still running after DURATION."; const USAGE: &str = "{} [OPTION] DURATION COMMAND..."; const ERR_EXIT_STATUS: i32 = 125; pub mod options { pub static FOREGROUND: &str = "foreground"; pub static KILL_AFTER: &str = "kill-after"; pub static SIGNAL: &str = "signal"; pub static PRESERVE_STATUS: &str = "preserve-status"; pub static VERBOSE: &str = "verbose"; // Positional args. pub static DURATION: &str = "duration"; pub static COMMAND: &str = "command"; } struct Config { foreground: bool, kill_after: Option<Duration>, signal: usize, duration: Duration, preserve_status: bool, verbose: bool, command: Vec<String>, } impl Config { fn from(options: &clap::ArgMatches) -> UResult<Self> { let signal = match options.value_of(options::SIGNAL) { Some(signal_) => { let signal_result = signal_by_name_or_value(signal_); match signal_result { None => { unreachable!("invalid signal {}", signal_.quote()); } Some(signal_value) => signal_value, } } _ => uucore::signals::signal_by_name_or_value("TERM").unwrap(), }; let kill_after = options .value_of(options::KILL_AFTER) .map(|time| uucore::parse_time::from_str(time).unwrap()); let duration = match uucore::parse_time::from_str(options.value_of(options::DURATION).unwrap()) { Ok(duration) => duration, Err(err) => return Err(USimpleError::new(1, err)), }; let preserve_status: bool = options.is_present(options::PRESERVE_STATUS); let foreground = options.is_present(options::FOREGROUND); let verbose = options.is_present(options::VERBOSE); let command = options .values_of(options::COMMAND) .unwrap() .map(String::from) .collect::<Vec<_>>(); Ok(Self { foreground, kill_after, signal, duration, preserve_status, verbose, command, }) } } #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let args = args .collect_str(InvalidEncodingHandling::ConvertLossy) .accept_any(); let app = uu_app(); let matches = app.get_matches_from(args); let config = Config::from(&matches)?; timeout( &config.command, config.duration, config.signal, config.kill_after, config.foreground, config.preserve_status, config.verbose, ) } pub fn uu_app<'a>() -> App<'a> { App::new("timeout") .version(crate_version!()) .about(ABOUT) .override_usage(format_usage(USAGE)) .arg( Arg::new(options::FOREGROUND) .long(options::FOREGROUND) .help("when not running timeout directly from a shell prompt, allow COMMAND to read from the TTY and get TTY signals; in this mode, children of COMMAND will not be timed out") ) .arg( Arg::new(options::KILL_AFTER) .short('k') .takes_value(true)) .arg( Arg::new(options::PRESERVE_STATUS) .long(options::PRESERVE_STATUS) .help("exit with the same status as COMMAND, even when the command times out") ) .arg( Arg::new(options::SIGNAL) .short('s') .long(options::SIGNAL) .help("specify the signal to be sent on timeout; SIGNAL may be a name like 'HUP' or a number; see 'kill -l' for a list of signals") .takes_value(true) ) .arg( Arg::new(options::VERBOSE) .short('v') .long(options::VERBOSE) .help("diagnose to stderr any signal sent upon timeout") ) .arg( Arg::new(options::DURATION) .index(1) .required(true) ) .arg( Arg::new(options::COMMAND) .index(2) .required(true) .multiple_occurrences(true) ) .setting(AppSettings::TrailingVarArg) .setting(AppSettings::InferLongArgs) } /// Remove pre-existing SIGCHLD handlers that would make waiting for the child's exit code fail. fn unblock_sigchld() { unsafe { nix::sys::signal::signal( nix::sys::signal::Signal::SIGCHLD, nix::sys::signal::SigHandler::SigDfl, ) .unwrap(); } }
fn timeout( cmd: &[String], duration: Duration, signal: usize, kill_after: Option<Duration>, foreground: bool, preserve_status: bool, verbose: bool, ) -> UResult<()> { if!foreground { unsafe { libc::setpgid(0, 0) }; } let mut process = Command::new(&cmd[0]) .args(&cmd[1..]) .stdin(Stdio::inherit()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .spawn() .map_err(|err| { let status_code = if err.kind() == ErrorKind::NotFound { // FIXME: not sure which to use 127 } else { // FIXME: this may not be 100% correct... 126 }; USimpleError::new(status_code, format!("failed to execute process: {}", err)) })?; unblock_sigchld(); match process.wait_or_timeout(duration) { Ok(Some(status)) => { let status_code = status.code().unwrap_or_else(|| status.signal().unwrap()); if status_code == 0 { Ok(()) } else { Err(status_code.into()) } } Ok(None) => { if verbose { show_error!( "sending signal {} to command {}", signal_name_by_value(signal).unwrap(), cmd[0].quote() ); } process .send_signal(signal) .map_err(|e| USimpleError::new(ERR_EXIT_STATUS, format!("{}", e)))?; if let Some(kill_after) = kill_after { match process.wait_or_timeout(kill_after) { Ok(Some(status)) => { if preserve_status { let status_code = status.code().unwrap_or_else(|| status.signal().unwrap()); if status_code == 0 { Ok(()) } else { Err(status_code.into()) } } else { Err(124.into()) } } Ok(None) => { if verbose { show_error!("sending signal KILL to command {}", cmd[0].quote()); } process .send_signal(uucore::signals::signal_by_name_or_value("KILL").unwrap()) .map_err(|e| USimpleError::new(ERR_EXIT_STATUS, format!("{}", e)))?; process .wait() .map_err(|e| USimpleError::new(ERR_EXIT_STATUS, format!("{}", e)))?; Err(137.into()) } Err(_) => Err(124.into()), } } else { Err(124.into()) } } Err(_) => { // We're going to return ERR_EXIT_STATUS regardless of // whether `send_signal()` succeeds or fails, so just // ignore the return value. process .send_signal(signal) .map_err(|e| USimpleError::new(ERR_EXIT_STATUS, format!("{}", e)))?; Err(ERR_EXIT_STATUS.into()) } } }
/// TODO: Improve exit codes, and make them consistent with the GNU Coreutils exit codes.
random_line_split
lib.rs
// Copyright 2017 The Gfx-rs Developers. // // 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. #[macro_use] extern crate log; extern crate comptr; extern crate d3d12; extern crate d3dcompiler; extern crate dxgi; extern crate dxguid; extern crate gfx_corell as core; extern crate winapi; extern crate winit; use comptr::ComPtr; use std::ptr; use std::os::raw::c_void; use std::os::windows::ffi::OsStringExt; use std::ops::Deref; use std::collections::VecDeque; use std::ffi::OsString; use winapi::BOOL; use winit::os::windows::WindowExt; use core::command::Submit; mod command; mod data; mod factory; mod mirror; mod native; mod pool; mod state; pub use pool::{GeneralCommandPool, GraphicsCommandPool, ComputeCommandPool, TransferCommandPool, SubpassCommandPool}; #[derive(Clone)] pub struct QueueFamily; impl core::QueueFamily for QueueFamily { type Surface = Surface; fn supports_present(&self, _surface: &Surface) -> bool { // true } fn num_queues(&self) -> u32 { // TODO: actually infinite, need to find a good way to handle this 1 } } #[derive(Clone)] pub struct Adapter { adapter: ComPtr<winapi::IDXGIAdapter2>, info: core::AdapterInfo, queue_families: Vec<QueueFamily>, } impl core::Adapter for Adapter { type CommandQueue = CommandQueue; type Resources = Resources; type Factory = Factory; type QueueFamily = QueueFamily; fn open<'a, I>(&self, queue_descs: I) -> core::Device<Resources, Factory, CommandQueue> where I: Iterator<Item=(&'a QueueFamily, u32)> { // Create D3D12 device let mut device = ComPtr::<winapi::ID3D12Device>::new(ptr::null_mut()); let hr = unsafe { d3d12::D3D12CreateDevice( self.adapter.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, winapi::D3D_FEATURE_LEVEL_12_0, // TODO: correct feature level? &dxguid::IID_ID3D12Device, device.as_mut() as *mut *mut _ as *mut *mut c_void, ) }; if!winapi::SUCCEEDED(hr) { error!("error on device creation: {:x}", hr); } // TODO: other queue types // Create command queues let mut general_queues = queue_descs.flat_map(|(_family, queue_count)| { (0..queue_count).map(|_| { let mut queue = ComPtr::<winapi::ID3D12CommandQueue>::new(ptr::null_mut()); let queue_desc = winapi::D3D12_COMMAND_QUEUE_DESC { Type: winapi::D3D12_COMMAND_LIST_TYPE_DIRECT, // TODO: correct queue type Priority: 0, Flags: winapi::D3D12_COMMAND_QUEUE_FLAG_NONE, NodeMask: 0, }; let hr = unsafe { device.CreateCommandQueue( &queue_desc, &dxguid::IID_ID3D12CommandQueue, queue.as_mut() as *mut *mut _ as *mut *mut c_void, ) }; if!winapi::SUCCEEDED(hr) { error!("error on queue creation: {:x}", hr); } unsafe { core::GeneralQueue::new( CommandQueue { inner: queue, device: device.clone(), list_type: winapi::D3D12_COMMAND_LIST_TYPE_DIRECT, // TODO } ) } }).collect::<Vec<_>>() }).collect(); let factory = Factory { inner: device }; core::Device { factory: factory, general_queues: general_queues, graphics_queues: Vec::new(), compute_queues: Vec::new(), transfer_queues: Vec::new(), _marker: std::marker::PhantomData, } } fn get_info(&self) -> &core::AdapterInfo { &self.info } fn get_queue_families(&self) -> std::slice::Iter<QueueFamily> { self.queue_families.iter() } } pub struct Factory { inner: ComPtr<winapi::ID3D12Device>, } pub struct CommandQueue { inner: ComPtr<winapi::ID3D12CommandQueue>, device: ComPtr<winapi::ID3D12Device>, list_type: winapi::D3D12_COMMAND_LIST_TYPE, } impl core::CommandQueue for CommandQueue { type R = Resources; type SubmitInfo = command::SubmitInfo; type GeneralCommandBuffer = native::GeneralCommandBuffer; type GraphicsCommandBuffer = native::GraphicsCommandBuffer; type ComputeCommandBuffer = native::ComputeCommandBuffer; type TransferCommandBuffer = native::TransferCommandBuffer; type SubpassCommandBuffer = native::SubpassCommandBuffer; unsafe fn submit<C>(&mut self, cmd_buffers: &[Submit<C>]) where C: core::CommandBuffer<SubmitInfo = command::SubmitInfo> { let mut command_lists = cmd_buffers.iter().map(|cmd_buffer| { cmd_buffer.get_info().0.as_mut_ptr() }).collect::<Vec<_>>(); self.inner.ExecuteCommandLists(command_lists.len() as u32, command_lists.as_mut_ptr() as *mut *mut _); } } pub struct Surface { factory: ComPtr<winapi::IDXGIFactory4>, wnd_handle: winapi::HWND, width: u32, height: u32, } impl core::Surface for Surface { type Queue = CommandQueue; type SwapChain = SwapChain; fn build_swapchain<T: core::format::RenderFormat>(&self, present_queue: &CommandQueue) -> SwapChain { let mut swap_chain = ComPtr::<winapi::IDXGISwapChain1>::new(ptr::null_mut()); // TODO: double-check values let desc = winapi::DXGI_SWAP_CHAIN_DESC1 { AlphaMode: winapi::DXGI_ALPHA_MODE(0), BufferCount: 2, Width: self.width, Height: self.height, Format: data::map_format(T::get_format(), true).unwrap(), // TODO: error handling Flags: 0, BufferUsage: winapi::DXGI_USAGE_RENDER_TARGET_OUTPUT, SampleDesc: winapi::DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, Scaling: winapi::DXGI_SCALING(0), Stereo: false as BOOL, SwapEffect: winapi::DXGI_SWAP_EFFECT(4), // TODO: FLIP_DISCARD }; let hr = unsafe { (**self.factory.as_ref()).CreateSwapChainForHwnd( present_queue.inner.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, self.wnd_handle, &desc, ptr::null(), ptr::null_mut(), swap_chain.as_mut() as *mut *mut _, ) }; if!winapi::SUCCEEDED(hr) { error!("error on swapchain creation {:x}", hr); } SwapChain { inner: swap_chain, next_frame: 0, frame_queue: VecDeque::new(), } } } pub struct SwapChain { inner: ComPtr<winapi::IDXGISwapChain1>, next_frame: usize, frame_queue: VecDeque<usize>, } impl<'a> core::SwapChain for SwapChain{ fn acquire_frame(&mut self) -> core::Frame { // TODO: we need to block this at some point? let index = self.next_frame; self.frame_queue.push_back(index); self.next_frame = (self.next_frame + 1) % 2; // TODO: remove magic swap buffer count unsafe { core::Frame::new(index) } } fn present(&mut self) { unsafe { self.inner.Present(1, 0); } } } pub struct Instance { inner: ComPtr<winapi::IDXGIFactory4>, adapters: Vec<Adapter>, } impl core::Instance for Instance { type Adapter = Adapter; type Surface = Surface; type Window = winit::Window; fn create() -> Instance { // Enable debug layer { let mut debug_controller = ComPtr::<winapi::ID3D12Debug>::new(ptr::null_mut()); let hr = unsafe { d3d12::D3D12GetDebugInterface( &dxguid::IID_ID3D12Debug, debug_controller.as_mut() as *mut *mut _ as *mut *mut c_void) }; if winapi::SUCCEEDED(hr) { unsafe { debug_controller.EnableDebugLayer() }; } } // Create DXGI factory let mut dxgi_factory = ComPtr::<winapi::IDXGIFactory4>::new(ptr::null_mut()); let hr = unsafe { dxgi::CreateDXGIFactory2( winapi::DXGI_CREATE_FACTORY_DEBUG, &dxguid::IID_IDXGIFactory4, dxgi_factory.as_mut() as *mut *mut _ as *mut *mut c_void) }; if!winapi::SUCCEEDED(hr) { error!("Failed on dxgi factory creation: {:?}", hr); } // Enumerate adapters let mut cur_index = 0; let mut devices = Vec::new(); loop { let mut adapter = ComPtr::<winapi::IDXGIAdapter2>::new(ptr::null_mut()); let hr = unsafe { dxgi_factory.EnumAdapters1( cur_index, adapter.as_mut() as *mut *mut _ as *mut *mut winapi::IDXGIAdapter1) }; if hr == winapi::DXGI_ERROR_NOT_FOUND { break; } // Check for D3D12 support let hr = unsafe { d3d12::D3D12CreateDevice( adapter.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, winapi::D3D_FEATURE_LEVEL_11_0, // TODO: correct feature level? &dxguid::IID_ID3D12Device, ptr::null_mut(), ) }; if winapi::SUCCEEDED(hr)
Adapter { adapter: adapter, info: info, queue_families: vec![QueueFamily], // TODO: }); } cur_index += 1; } Instance { inner: dxgi_factory, adapters: devices, } } fn enumerate_adapters(&self) -> Vec<Adapter> { self.adapters.clone() } fn create_surface(&self, window: &winit::Window) -> Surface { let (width, height) = window.get_inner_size_pixels().unwrap(); Surface { factory: self.inner.clone(), wnd_handle: window.get_hwnd() as *mut _, width: width, height: height, } } } pub enum Backend { } impl core::Backend for Backend { type CommandQueue = CommandQueue; type Factory = Factory; type Instance = Instance; type Adapter = Adapter; type Resources = Resources; type Surface = Surface; type SwapChain = SwapChain; } #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub enum Resources { } impl core::Resources for Resources { type ShaderLib = native::ShaderLib; type RenderPass = (); type PipelineLayout = native::PipelineLayout; type PipelineStateObject = native::Pipeline; type Buffer = native::Buffer; type Image = native::Image; type ShaderResourceView = (); type UnorderedAccessView = (); type RenderTargetView = native::RenderTargetView; type DepthStencilView = (); type Sampler = (); }
{ // We have found a possible adapter // acquire the device information let mut desc: winapi::DXGI_ADAPTER_DESC2 = unsafe { std::mem::uninitialized() }; unsafe { adapter.GetDesc2(&mut desc); } let device_name = { let len = desc.Description.iter().take_while(|&&c| c != 0).count(); let name = <OsString as OsStringExt>::from_wide(&desc.Description[..len]); name.to_string_lossy().into_owned() }; let info = core::AdapterInfo { name: device_name, vendor: desc.VendorId as usize, device: desc.DeviceId as usize, software_rendering: false, // TODO: check for WARP adapter (software rasterizer)? }; devices.push(
conditional_block
lib.rs
// Copyright 2017 The Gfx-rs Developers. // // 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. #[macro_use] extern crate log; extern crate comptr; extern crate d3d12; extern crate d3dcompiler; extern crate dxgi; extern crate dxguid; extern crate gfx_corell as core; extern crate winapi; extern crate winit; use comptr::ComPtr; use std::ptr; use std::os::raw::c_void; use std::os::windows::ffi::OsStringExt; use std::ops::Deref; use std::collections::VecDeque; use std::ffi::OsString; use winapi::BOOL; use winit::os::windows::WindowExt; use core::command::Submit; mod command; mod data; mod factory; mod mirror; mod native; mod pool; mod state; pub use pool::{GeneralCommandPool, GraphicsCommandPool, ComputeCommandPool, TransferCommandPool, SubpassCommandPool}; #[derive(Clone)] pub struct QueueFamily; impl core::QueueFamily for QueueFamily { type Surface = Surface; fn supports_present(&self, _surface: &Surface) -> bool { // true } fn num_queues(&self) -> u32 { // TODO: actually infinite, need to find a good way to handle this 1 } } #[derive(Clone)] pub struct Adapter { adapter: ComPtr<winapi::IDXGIAdapter2>, info: core::AdapterInfo, queue_families: Vec<QueueFamily>, } impl core::Adapter for Adapter { type CommandQueue = CommandQueue; type Resources = Resources; type Factory = Factory; type QueueFamily = QueueFamily; fn open<'a, I>(&self, queue_descs: I) -> core::Device<Resources, Factory, CommandQueue> where I: Iterator<Item=(&'a QueueFamily, u32)> { // Create D3D12 device let mut device = ComPtr::<winapi::ID3D12Device>::new(ptr::null_mut()); let hr = unsafe { d3d12::D3D12CreateDevice( self.adapter.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, winapi::D3D_FEATURE_LEVEL_12_0, // TODO: correct feature level? &dxguid::IID_ID3D12Device, device.as_mut() as *mut *mut _ as *mut *mut c_void, ) }; if!winapi::SUCCEEDED(hr) { error!("error on device creation: {:x}", hr); } // TODO: other queue types // Create command queues let mut general_queues = queue_descs.flat_map(|(_family, queue_count)| { (0..queue_count).map(|_| { let mut queue = ComPtr::<winapi::ID3D12CommandQueue>::new(ptr::null_mut()); let queue_desc = winapi::D3D12_COMMAND_QUEUE_DESC { Type: winapi::D3D12_COMMAND_LIST_TYPE_DIRECT, // TODO: correct queue type Priority: 0, Flags: winapi::D3D12_COMMAND_QUEUE_FLAG_NONE, NodeMask: 0, }; let hr = unsafe { device.CreateCommandQueue( &queue_desc, &dxguid::IID_ID3D12CommandQueue, queue.as_mut() as *mut *mut _ as *mut *mut c_void, ) }; if!winapi::SUCCEEDED(hr) { error!("error on queue creation: {:x}", hr); } unsafe { core::GeneralQueue::new( CommandQueue { inner: queue, device: device.clone(), list_type: winapi::D3D12_COMMAND_LIST_TYPE_DIRECT, // TODO } ) } }).collect::<Vec<_>>() }).collect(); let factory = Factory { inner: device }; core::Device { factory: factory, general_queues: general_queues, graphics_queues: Vec::new(), compute_queues: Vec::new(), transfer_queues: Vec::new(), _marker: std::marker::PhantomData, } } fn get_info(&self) -> &core::AdapterInfo { &self.info } fn get_queue_families(&self) -> std::slice::Iter<QueueFamily> { self.queue_families.iter() } } pub struct Factory { inner: ComPtr<winapi::ID3D12Device>, } pub struct CommandQueue { inner: ComPtr<winapi::ID3D12CommandQueue>, device: ComPtr<winapi::ID3D12Device>, list_type: winapi::D3D12_COMMAND_LIST_TYPE, } impl core::CommandQueue for CommandQueue { type R = Resources; type SubmitInfo = command::SubmitInfo; type GeneralCommandBuffer = native::GeneralCommandBuffer; type GraphicsCommandBuffer = native::GraphicsCommandBuffer; type ComputeCommandBuffer = native::ComputeCommandBuffer; type TransferCommandBuffer = native::TransferCommandBuffer; type SubpassCommandBuffer = native::SubpassCommandBuffer; unsafe fn submit<C>(&mut self, cmd_buffers: &[Submit<C>]) where C: core::CommandBuffer<SubmitInfo = command::SubmitInfo> { let mut command_lists = cmd_buffers.iter().map(|cmd_buffer| { cmd_buffer.get_info().0.as_mut_ptr() }).collect::<Vec<_>>(); self.inner.ExecuteCommandLists(command_lists.len() as u32, command_lists.as_mut_ptr() as *mut *mut _); } } pub struct Surface { factory: ComPtr<winapi::IDXGIFactory4>, wnd_handle: winapi::HWND, width: u32, height: u32, } impl core::Surface for Surface { type Queue = CommandQueue; type SwapChain = SwapChain; fn build_swapchain<T: core::format::RenderFormat>(&self, present_queue: &CommandQueue) -> SwapChain { let mut swap_chain = ComPtr::<winapi::IDXGISwapChain1>::new(ptr::null_mut()); // TODO: double-check values let desc = winapi::DXGI_SWAP_CHAIN_DESC1 { AlphaMode: winapi::DXGI_ALPHA_MODE(0), BufferCount: 2, Width: self.width, Height: self.height, Format: data::map_format(T::get_format(), true).unwrap(), // TODO: error handling Flags: 0, BufferUsage: winapi::DXGI_USAGE_RENDER_TARGET_OUTPUT, SampleDesc: winapi::DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, Scaling: winapi::DXGI_SCALING(0), Stereo: false as BOOL, SwapEffect: winapi::DXGI_SWAP_EFFECT(4), // TODO: FLIP_DISCARD }; let hr = unsafe { (**self.factory.as_ref()).CreateSwapChainForHwnd( present_queue.inner.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, self.wnd_handle, &desc, ptr::null(), ptr::null_mut(), swap_chain.as_mut() as *mut *mut _, ) }; if!winapi::SUCCEEDED(hr) { error!("error on swapchain creation {:x}", hr); } SwapChain { inner: swap_chain, next_frame: 0, frame_queue: VecDeque::new(), } } } pub struct SwapChain { inner: ComPtr<winapi::IDXGISwapChain1>, next_frame: usize, frame_queue: VecDeque<usize>, } impl<'a> core::SwapChain for SwapChain{ fn acquire_frame(&mut self) -> core::Frame { // TODO: we need to block this at some point? let index = self.next_frame; self.frame_queue.push_back(index); self.next_frame = (self.next_frame + 1) % 2; // TODO: remove magic swap buffer count unsafe { core::Frame::new(index) } } fn present(&mut self) { unsafe { self.inner.Present(1, 0); } } } pub struct Instance { inner: ComPtr<winapi::IDXGIFactory4>, adapters: Vec<Adapter>, } impl core::Instance for Instance { type Adapter = Adapter; type Surface = Surface; type Window = winit::Window; fn create() -> Instance { // Enable debug layer { let mut debug_controller = ComPtr::<winapi::ID3D12Debug>::new(ptr::null_mut()); let hr = unsafe { d3d12::D3D12GetDebugInterface( &dxguid::IID_ID3D12Debug, debug_controller.as_mut() as *mut *mut _ as *mut *mut c_void) }; if winapi::SUCCEEDED(hr) { unsafe { debug_controller.EnableDebugLayer() }; } } // Create DXGI factory let mut dxgi_factory = ComPtr::<winapi::IDXGIFactory4>::new(ptr::null_mut()); let hr = unsafe { dxgi::CreateDXGIFactory2( winapi::DXGI_CREATE_FACTORY_DEBUG, &dxguid::IID_IDXGIFactory4, dxgi_factory.as_mut() as *mut *mut _ as *mut *mut c_void) }; if!winapi::SUCCEEDED(hr) { error!("Failed on dxgi factory creation: {:?}", hr); } // Enumerate adapters let mut cur_index = 0; let mut devices = Vec::new(); loop { let mut adapter = ComPtr::<winapi::IDXGIAdapter2>::new(ptr::null_mut()); let hr = unsafe { dxgi_factory.EnumAdapters1( cur_index, adapter.as_mut() as *mut *mut _ as *mut *mut winapi::IDXGIAdapter1) }; if hr == winapi::DXGI_ERROR_NOT_FOUND { break; } // Check for D3D12 support let hr = unsafe { d3d12::D3D12CreateDevice( adapter.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, winapi::D3D_FEATURE_LEVEL_11_0, // TODO: correct feature level? &dxguid::IID_ID3D12Device, ptr::null_mut(), ) }; if winapi::SUCCEEDED(hr) {
let device_name = { let len = desc.Description.iter().take_while(|&&c| c!= 0).count(); let name = <OsString as OsStringExt>::from_wide(&desc.Description[..len]); name.to_string_lossy().into_owned() }; let info = core::AdapterInfo { name: device_name, vendor: desc.VendorId as usize, device: desc.DeviceId as usize, software_rendering: false, // TODO: check for WARP adapter (software rasterizer)? }; devices.push( Adapter { adapter: adapter, info: info, queue_families: vec![QueueFamily], // TODO: }); } cur_index += 1; } Instance { inner: dxgi_factory, adapters: devices, } } fn enumerate_adapters(&self) -> Vec<Adapter> { self.adapters.clone() } fn create_surface(&self, window: &winit::Window) -> Surface { let (width, height) = window.get_inner_size_pixels().unwrap(); Surface { factory: self.inner.clone(), wnd_handle: window.get_hwnd() as *mut _, width: width, height: height, } } } pub enum Backend { } impl core::Backend for Backend { type CommandQueue = CommandQueue; type Factory = Factory; type Instance = Instance; type Adapter = Adapter; type Resources = Resources; type Surface = Surface; type SwapChain = SwapChain; } #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub enum Resources { } impl core::Resources for Resources { type ShaderLib = native::ShaderLib; type RenderPass = (); type PipelineLayout = native::PipelineLayout; type PipelineStateObject = native::Pipeline; type Buffer = native::Buffer; type Image = native::Image; type ShaderResourceView = (); type UnorderedAccessView = (); type RenderTargetView = native::RenderTargetView; type DepthStencilView = (); type Sampler = (); }
// We have found a possible adapter // acquire the device information let mut desc: winapi::DXGI_ADAPTER_DESC2 = unsafe { std::mem::uninitialized() }; unsafe { adapter.GetDesc2(&mut desc); }
random_line_split
lib.rs
// Copyright 2017 The Gfx-rs Developers. // // 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. #[macro_use] extern crate log; extern crate comptr; extern crate d3d12; extern crate d3dcompiler; extern crate dxgi; extern crate dxguid; extern crate gfx_corell as core; extern crate winapi; extern crate winit; use comptr::ComPtr; use std::ptr; use std::os::raw::c_void; use std::os::windows::ffi::OsStringExt; use std::ops::Deref; use std::collections::VecDeque; use std::ffi::OsString; use winapi::BOOL; use winit::os::windows::WindowExt; use core::command::Submit; mod command; mod data; mod factory; mod mirror; mod native; mod pool; mod state; pub use pool::{GeneralCommandPool, GraphicsCommandPool, ComputeCommandPool, TransferCommandPool, SubpassCommandPool}; #[derive(Clone)] pub struct QueueFamily; impl core::QueueFamily for QueueFamily { type Surface = Surface; fn supports_present(&self, _surface: &Surface) -> bool { // true } fn num_queues(&self) -> u32 { // TODO: actually infinite, need to find a good way to handle this 1 } } #[derive(Clone)] pub struct Adapter { adapter: ComPtr<winapi::IDXGIAdapter2>, info: core::AdapterInfo, queue_families: Vec<QueueFamily>, } impl core::Adapter for Adapter { type CommandQueue = CommandQueue; type Resources = Resources; type Factory = Factory; type QueueFamily = QueueFamily; fn open<'a, I>(&self, queue_descs: I) -> core::Device<Resources, Factory, CommandQueue> where I: Iterator<Item=(&'a QueueFamily, u32)> { // Create D3D12 device let mut device = ComPtr::<winapi::ID3D12Device>::new(ptr::null_mut()); let hr = unsafe { d3d12::D3D12CreateDevice( self.adapter.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, winapi::D3D_FEATURE_LEVEL_12_0, // TODO: correct feature level? &dxguid::IID_ID3D12Device, device.as_mut() as *mut *mut _ as *mut *mut c_void, ) }; if!winapi::SUCCEEDED(hr) { error!("error on device creation: {:x}", hr); } // TODO: other queue types // Create command queues let mut general_queues = queue_descs.flat_map(|(_family, queue_count)| { (0..queue_count).map(|_| { let mut queue = ComPtr::<winapi::ID3D12CommandQueue>::new(ptr::null_mut()); let queue_desc = winapi::D3D12_COMMAND_QUEUE_DESC { Type: winapi::D3D12_COMMAND_LIST_TYPE_DIRECT, // TODO: correct queue type Priority: 0, Flags: winapi::D3D12_COMMAND_QUEUE_FLAG_NONE, NodeMask: 0, }; let hr = unsafe { device.CreateCommandQueue( &queue_desc, &dxguid::IID_ID3D12CommandQueue, queue.as_mut() as *mut *mut _ as *mut *mut c_void, ) }; if!winapi::SUCCEEDED(hr) { error!("error on queue creation: {:x}", hr); } unsafe { core::GeneralQueue::new( CommandQueue { inner: queue, device: device.clone(), list_type: winapi::D3D12_COMMAND_LIST_TYPE_DIRECT, // TODO } ) } }).collect::<Vec<_>>() }).collect(); let factory = Factory { inner: device }; core::Device { factory: factory, general_queues: general_queues, graphics_queues: Vec::new(), compute_queues: Vec::new(), transfer_queues: Vec::new(), _marker: std::marker::PhantomData, } } fn
(&self) -> &core::AdapterInfo { &self.info } fn get_queue_families(&self) -> std::slice::Iter<QueueFamily> { self.queue_families.iter() } } pub struct Factory { inner: ComPtr<winapi::ID3D12Device>, } pub struct CommandQueue { inner: ComPtr<winapi::ID3D12CommandQueue>, device: ComPtr<winapi::ID3D12Device>, list_type: winapi::D3D12_COMMAND_LIST_TYPE, } impl core::CommandQueue for CommandQueue { type R = Resources; type SubmitInfo = command::SubmitInfo; type GeneralCommandBuffer = native::GeneralCommandBuffer; type GraphicsCommandBuffer = native::GraphicsCommandBuffer; type ComputeCommandBuffer = native::ComputeCommandBuffer; type TransferCommandBuffer = native::TransferCommandBuffer; type SubpassCommandBuffer = native::SubpassCommandBuffer; unsafe fn submit<C>(&mut self, cmd_buffers: &[Submit<C>]) where C: core::CommandBuffer<SubmitInfo = command::SubmitInfo> { let mut command_lists = cmd_buffers.iter().map(|cmd_buffer| { cmd_buffer.get_info().0.as_mut_ptr() }).collect::<Vec<_>>(); self.inner.ExecuteCommandLists(command_lists.len() as u32, command_lists.as_mut_ptr() as *mut *mut _); } } pub struct Surface { factory: ComPtr<winapi::IDXGIFactory4>, wnd_handle: winapi::HWND, width: u32, height: u32, } impl core::Surface for Surface { type Queue = CommandQueue; type SwapChain = SwapChain; fn build_swapchain<T: core::format::RenderFormat>(&self, present_queue: &CommandQueue) -> SwapChain { let mut swap_chain = ComPtr::<winapi::IDXGISwapChain1>::new(ptr::null_mut()); // TODO: double-check values let desc = winapi::DXGI_SWAP_CHAIN_DESC1 { AlphaMode: winapi::DXGI_ALPHA_MODE(0), BufferCount: 2, Width: self.width, Height: self.height, Format: data::map_format(T::get_format(), true).unwrap(), // TODO: error handling Flags: 0, BufferUsage: winapi::DXGI_USAGE_RENDER_TARGET_OUTPUT, SampleDesc: winapi::DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, Scaling: winapi::DXGI_SCALING(0), Stereo: false as BOOL, SwapEffect: winapi::DXGI_SWAP_EFFECT(4), // TODO: FLIP_DISCARD }; let hr = unsafe { (**self.factory.as_ref()).CreateSwapChainForHwnd( present_queue.inner.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, self.wnd_handle, &desc, ptr::null(), ptr::null_mut(), swap_chain.as_mut() as *mut *mut _, ) }; if!winapi::SUCCEEDED(hr) { error!("error on swapchain creation {:x}", hr); } SwapChain { inner: swap_chain, next_frame: 0, frame_queue: VecDeque::new(), } } } pub struct SwapChain { inner: ComPtr<winapi::IDXGISwapChain1>, next_frame: usize, frame_queue: VecDeque<usize>, } impl<'a> core::SwapChain for SwapChain{ fn acquire_frame(&mut self) -> core::Frame { // TODO: we need to block this at some point? let index = self.next_frame; self.frame_queue.push_back(index); self.next_frame = (self.next_frame + 1) % 2; // TODO: remove magic swap buffer count unsafe { core::Frame::new(index) } } fn present(&mut self) { unsafe { self.inner.Present(1, 0); } } } pub struct Instance { inner: ComPtr<winapi::IDXGIFactory4>, adapters: Vec<Adapter>, } impl core::Instance for Instance { type Adapter = Adapter; type Surface = Surface; type Window = winit::Window; fn create() -> Instance { // Enable debug layer { let mut debug_controller = ComPtr::<winapi::ID3D12Debug>::new(ptr::null_mut()); let hr = unsafe { d3d12::D3D12GetDebugInterface( &dxguid::IID_ID3D12Debug, debug_controller.as_mut() as *mut *mut _ as *mut *mut c_void) }; if winapi::SUCCEEDED(hr) { unsafe { debug_controller.EnableDebugLayer() }; } } // Create DXGI factory let mut dxgi_factory = ComPtr::<winapi::IDXGIFactory4>::new(ptr::null_mut()); let hr = unsafe { dxgi::CreateDXGIFactory2( winapi::DXGI_CREATE_FACTORY_DEBUG, &dxguid::IID_IDXGIFactory4, dxgi_factory.as_mut() as *mut *mut _ as *mut *mut c_void) }; if!winapi::SUCCEEDED(hr) { error!("Failed on dxgi factory creation: {:?}", hr); } // Enumerate adapters let mut cur_index = 0; let mut devices = Vec::new(); loop { let mut adapter = ComPtr::<winapi::IDXGIAdapter2>::new(ptr::null_mut()); let hr = unsafe { dxgi_factory.EnumAdapters1( cur_index, adapter.as_mut() as *mut *mut _ as *mut *mut winapi::IDXGIAdapter1) }; if hr == winapi::DXGI_ERROR_NOT_FOUND { break; } // Check for D3D12 support let hr = unsafe { d3d12::D3D12CreateDevice( adapter.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, winapi::D3D_FEATURE_LEVEL_11_0, // TODO: correct feature level? &dxguid::IID_ID3D12Device, ptr::null_mut(), ) }; if winapi::SUCCEEDED(hr) { // We have found a possible adapter // acquire the device information let mut desc: winapi::DXGI_ADAPTER_DESC2 = unsafe { std::mem::uninitialized() }; unsafe { adapter.GetDesc2(&mut desc); } let device_name = { let len = desc.Description.iter().take_while(|&&c| c!= 0).count(); let name = <OsString as OsStringExt>::from_wide(&desc.Description[..len]); name.to_string_lossy().into_owned() }; let info = core::AdapterInfo { name: device_name, vendor: desc.VendorId as usize, device: desc.DeviceId as usize, software_rendering: false, // TODO: check for WARP adapter (software rasterizer)? }; devices.push( Adapter { adapter: adapter, info: info, queue_families: vec![QueueFamily], // TODO: }); } cur_index += 1; } Instance { inner: dxgi_factory, adapters: devices, } } fn enumerate_adapters(&self) -> Vec<Adapter> { self.adapters.clone() } fn create_surface(&self, window: &winit::Window) -> Surface { let (width, height) = window.get_inner_size_pixels().unwrap(); Surface { factory: self.inner.clone(), wnd_handle: window.get_hwnd() as *mut _, width: width, height: height, } } } pub enum Backend { } impl core::Backend for Backend { type CommandQueue = CommandQueue; type Factory = Factory; type Instance = Instance; type Adapter = Adapter; type Resources = Resources; type Surface = Surface; type SwapChain = SwapChain; } #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub enum Resources { } impl core::Resources for Resources { type ShaderLib = native::ShaderLib; type RenderPass = (); type PipelineLayout = native::PipelineLayout; type PipelineStateObject = native::Pipeline; type Buffer = native::Buffer; type Image = native::Image; type ShaderResourceView = (); type UnorderedAccessView = (); type RenderTargetView = native::RenderTargetView; type DepthStencilView = (); type Sampler = (); }
get_info
identifier_name
lib.rs
// Copyright 2017 The Gfx-rs Developers. // // 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. #[macro_use] extern crate log; extern crate comptr; extern crate d3d12; extern crate d3dcompiler; extern crate dxgi; extern crate dxguid; extern crate gfx_corell as core; extern crate winapi; extern crate winit; use comptr::ComPtr; use std::ptr; use std::os::raw::c_void; use std::os::windows::ffi::OsStringExt; use std::ops::Deref; use std::collections::VecDeque; use std::ffi::OsString; use winapi::BOOL; use winit::os::windows::WindowExt; use core::command::Submit; mod command; mod data; mod factory; mod mirror; mod native; mod pool; mod state; pub use pool::{GeneralCommandPool, GraphicsCommandPool, ComputeCommandPool, TransferCommandPool, SubpassCommandPool}; #[derive(Clone)] pub struct QueueFamily; impl core::QueueFamily for QueueFamily { type Surface = Surface; fn supports_present(&self, _surface: &Surface) -> bool { // true } fn num_queues(&self) -> u32 { // TODO: actually infinite, need to find a good way to handle this 1 } } #[derive(Clone)] pub struct Adapter { adapter: ComPtr<winapi::IDXGIAdapter2>, info: core::AdapterInfo, queue_families: Vec<QueueFamily>, } impl core::Adapter for Adapter { type CommandQueue = CommandQueue; type Resources = Resources; type Factory = Factory; type QueueFamily = QueueFamily; fn open<'a, I>(&self, queue_descs: I) -> core::Device<Resources, Factory, CommandQueue> where I: Iterator<Item=(&'a QueueFamily, u32)>
let queue_desc = winapi::D3D12_COMMAND_QUEUE_DESC { Type: winapi::D3D12_COMMAND_LIST_TYPE_DIRECT, // TODO: correct queue type Priority: 0, Flags: winapi::D3D12_COMMAND_QUEUE_FLAG_NONE, NodeMask: 0, }; let hr = unsafe { device.CreateCommandQueue( &queue_desc, &dxguid::IID_ID3D12CommandQueue, queue.as_mut() as *mut *mut _ as *mut *mut c_void, ) }; if!winapi::SUCCEEDED(hr) { error!("error on queue creation: {:x}", hr); } unsafe { core::GeneralQueue::new( CommandQueue { inner: queue, device: device.clone(), list_type: winapi::D3D12_COMMAND_LIST_TYPE_DIRECT, // TODO } ) } }).collect::<Vec<_>>() }).collect(); let factory = Factory { inner: device }; core::Device { factory: factory, general_queues: general_queues, graphics_queues: Vec::new(), compute_queues: Vec::new(), transfer_queues: Vec::new(), _marker: std::marker::PhantomData, } } fn get_info(&self) -> &core::AdapterInfo { &self.info } fn get_queue_families(&self) -> std::slice::Iter<QueueFamily> { self.queue_families.iter() } } pub struct Factory { inner: ComPtr<winapi::ID3D12Device>, } pub struct CommandQueue { inner: ComPtr<winapi::ID3D12CommandQueue>, device: ComPtr<winapi::ID3D12Device>, list_type: winapi::D3D12_COMMAND_LIST_TYPE, } impl core::CommandQueue for CommandQueue { type R = Resources; type SubmitInfo = command::SubmitInfo; type GeneralCommandBuffer = native::GeneralCommandBuffer; type GraphicsCommandBuffer = native::GraphicsCommandBuffer; type ComputeCommandBuffer = native::ComputeCommandBuffer; type TransferCommandBuffer = native::TransferCommandBuffer; type SubpassCommandBuffer = native::SubpassCommandBuffer; unsafe fn submit<C>(&mut self, cmd_buffers: &[Submit<C>]) where C: core::CommandBuffer<SubmitInfo = command::SubmitInfo> { let mut command_lists = cmd_buffers.iter().map(|cmd_buffer| { cmd_buffer.get_info().0.as_mut_ptr() }).collect::<Vec<_>>(); self.inner.ExecuteCommandLists(command_lists.len() as u32, command_lists.as_mut_ptr() as *mut *mut _); } } pub struct Surface { factory: ComPtr<winapi::IDXGIFactory4>, wnd_handle: winapi::HWND, width: u32, height: u32, } impl core::Surface for Surface { type Queue = CommandQueue; type SwapChain = SwapChain; fn build_swapchain<T: core::format::RenderFormat>(&self, present_queue: &CommandQueue) -> SwapChain { let mut swap_chain = ComPtr::<winapi::IDXGISwapChain1>::new(ptr::null_mut()); // TODO: double-check values let desc = winapi::DXGI_SWAP_CHAIN_DESC1 { AlphaMode: winapi::DXGI_ALPHA_MODE(0), BufferCount: 2, Width: self.width, Height: self.height, Format: data::map_format(T::get_format(), true).unwrap(), // TODO: error handling Flags: 0, BufferUsage: winapi::DXGI_USAGE_RENDER_TARGET_OUTPUT, SampleDesc: winapi::DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, Scaling: winapi::DXGI_SCALING(0), Stereo: false as BOOL, SwapEffect: winapi::DXGI_SWAP_EFFECT(4), // TODO: FLIP_DISCARD }; let hr = unsafe { (**self.factory.as_ref()).CreateSwapChainForHwnd( present_queue.inner.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, self.wnd_handle, &desc, ptr::null(), ptr::null_mut(), swap_chain.as_mut() as *mut *mut _, ) }; if!winapi::SUCCEEDED(hr) { error!("error on swapchain creation {:x}", hr); } SwapChain { inner: swap_chain, next_frame: 0, frame_queue: VecDeque::new(), } } } pub struct SwapChain { inner: ComPtr<winapi::IDXGISwapChain1>, next_frame: usize, frame_queue: VecDeque<usize>, } impl<'a> core::SwapChain for SwapChain{ fn acquire_frame(&mut self) -> core::Frame { // TODO: we need to block this at some point? let index = self.next_frame; self.frame_queue.push_back(index); self.next_frame = (self.next_frame + 1) % 2; // TODO: remove magic swap buffer count unsafe { core::Frame::new(index) } } fn present(&mut self) { unsafe { self.inner.Present(1, 0); } } } pub struct Instance { inner: ComPtr<winapi::IDXGIFactory4>, adapters: Vec<Adapter>, } impl core::Instance for Instance { type Adapter = Adapter; type Surface = Surface; type Window = winit::Window; fn create() -> Instance { // Enable debug layer { let mut debug_controller = ComPtr::<winapi::ID3D12Debug>::new(ptr::null_mut()); let hr = unsafe { d3d12::D3D12GetDebugInterface( &dxguid::IID_ID3D12Debug, debug_controller.as_mut() as *mut *mut _ as *mut *mut c_void) }; if winapi::SUCCEEDED(hr) { unsafe { debug_controller.EnableDebugLayer() }; } } // Create DXGI factory let mut dxgi_factory = ComPtr::<winapi::IDXGIFactory4>::new(ptr::null_mut()); let hr = unsafe { dxgi::CreateDXGIFactory2( winapi::DXGI_CREATE_FACTORY_DEBUG, &dxguid::IID_IDXGIFactory4, dxgi_factory.as_mut() as *mut *mut _ as *mut *mut c_void) }; if!winapi::SUCCEEDED(hr) { error!("Failed on dxgi factory creation: {:?}", hr); } // Enumerate adapters let mut cur_index = 0; let mut devices = Vec::new(); loop { let mut adapter = ComPtr::<winapi::IDXGIAdapter2>::new(ptr::null_mut()); let hr = unsafe { dxgi_factory.EnumAdapters1( cur_index, adapter.as_mut() as *mut *mut _ as *mut *mut winapi::IDXGIAdapter1) }; if hr == winapi::DXGI_ERROR_NOT_FOUND { break; } // Check for D3D12 support let hr = unsafe { d3d12::D3D12CreateDevice( adapter.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, winapi::D3D_FEATURE_LEVEL_11_0, // TODO: correct feature level? &dxguid::IID_ID3D12Device, ptr::null_mut(), ) }; if winapi::SUCCEEDED(hr) { // We have found a possible adapter // acquire the device information let mut desc: winapi::DXGI_ADAPTER_DESC2 = unsafe { std::mem::uninitialized() }; unsafe { adapter.GetDesc2(&mut desc); } let device_name = { let len = desc.Description.iter().take_while(|&&c| c!= 0).count(); let name = <OsString as OsStringExt>::from_wide(&desc.Description[..len]); name.to_string_lossy().into_owned() }; let info = core::AdapterInfo { name: device_name, vendor: desc.VendorId as usize, device: desc.DeviceId as usize, software_rendering: false, // TODO: check for WARP adapter (software rasterizer)? }; devices.push( Adapter { adapter: adapter, info: info, queue_families: vec![QueueFamily], // TODO: }); } cur_index += 1; } Instance { inner: dxgi_factory, adapters: devices, } } fn enumerate_adapters(&self) -> Vec<Adapter> { self.adapters.clone() } fn create_surface(&self, window: &winit::Window) -> Surface { let (width, height) = window.get_inner_size_pixels().unwrap(); Surface { factory: self.inner.clone(), wnd_handle: window.get_hwnd() as *mut _, width: width, height: height, } } } pub enum Backend { } impl core::Backend for Backend { type CommandQueue = CommandQueue; type Factory = Factory; type Instance = Instance; type Adapter = Adapter; type Resources = Resources; type Surface = Surface; type SwapChain = SwapChain; } #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub enum Resources { } impl core::Resources for Resources { type ShaderLib = native::ShaderLib; type RenderPass = (); type PipelineLayout = native::PipelineLayout; type PipelineStateObject = native::Pipeline; type Buffer = native::Buffer; type Image = native::Image; type ShaderResourceView = (); type UnorderedAccessView = (); type RenderTargetView = native::RenderTargetView; type DepthStencilView = (); type Sampler = (); }
{ // Create D3D12 device let mut device = ComPtr::<winapi::ID3D12Device>::new(ptr::null_mut()); let hr = unsafe { d3d12::D3D12CreateDevice( self.adapter.as_mut_ptr() as *mut _ as *mut winapi::IUnknown, winapi::D3D_FEATURE_LEVEL_12_0, // TODO: correct feature level? &dxguid::IID_ID3D12Device, device.as_mut() as *mut *mut _ as *mut *mut c_void, ) }; if !winapi::SUCCEEDED(hr) { error!("error on device creation: {:x}", hr); } // TODO: other queue types // Create command queues let mut general_queues = queue_descs.flat_map(|(_family, queue_count)| { (0..queue_count).map(|_| { let mut queue = ComPtr::<winapi::ID3D12CommandQueue>::new(ptr::null_mut());
identifier_body
test.rs
pub fn config_read_word(bus: u8, slot: u8, func: u8, offset: u8) -> u16 { let device: i32 = match (bus, slot, func) { // root PCI controller (0, 0, 0) => 0, // secondary bus controller (for bus 1) (0, 1, 0) => 1, (9, 0, 0) => 2, (_, _, _) => -1, }; match offset { // vendor ID 0x00 => match device { 0 => 0x1022, 1 => 0x1022, 2 => 0x1013, _ => 0xFFFF, }, // device ID 0x02 => match device {
_ => 0xFFFF, }, // classes 0x0A => match device { 0 => 0x0600, 1 => 0x0604, 2 => 0x0300, _ => 0xFFFF, }, // header type 0x0E => match device { 1 => 0x0001, _ => 0x0000, }, // secondary bus 0x18 => match device { 1 => 0x0900, _ => 0x0000, }, _ => 0xFFFF, } }
0 => 0x15D0, 1 => 0x15D3, 2 => 0x00B8,
random_line_split
test.rs
pub fn config_read_word(bus: u8, slot: u8, func: u8, offset: u8) -> u16
}, // device ID 0x02 => match device { 0 => 0x15D0, 1 => 0x15D3, 2 => 0x00B8, _ => 0xFFFF, }, // classes 0x0A => match device { 0 => 0x0600, 1 => 0x0604, 2 => 0x0300, _ => 0xFFFF, }, // header type 0x0E => match device { 1 => 0x0001, _ => 0x0000, }, // secondary bus 0x18 => match device { 1 => 0x0900, _ => 0x0000, }, _ => 0xFFFF, } }
{ let device: i32 = match (bus, slot, func) { // root PCI controller (0, 0, 0) => 0, // secondary bus controller (for bus 1) (0, 1, 0) => 1, (9, 0, 0) => 2, (_, _, _) => -1, }; match offset { // vendor ID 0x00 => match device { 0 => 0x1022, 1 => 0x1022, 2 => 0x1013, _ => 0xFFFF,
identifier_body
test.rs
pub fn
(bus: u8, slot: u8, func: u8, offset: u8) -> u16 { let device: i32 = match (bus, slot, func) { // root PCI controller (0, 0, 0) => 0, // secondary bus controller (for bus 1) (0, 1, 0) => 1, (9, 0, 0) => 2, (_, _, _) => -1, }; match offset { // vendor ID 0x00 => match device { 0 => 0x1022, 1 => 0x1022, 2 => 0x1013, _ => 0xFFFF, }, // device ID 0x02 => match device { 0 => 0x15D0, 1 => 0x15D3, 2 => 0x00B8, _ => 0xFFFF, }, // classes 0x0A => match device { 0 => 0x0600, 1 => 0x0604, 2 => 0x0300, _ => 0xFFFF, }, // header type 0x0E => match device { 1 => 0x0001, _ => 0x0000, }, // secondary bus 0x18 => match device { 1 => 0x0900, _ => 0x0000, }, _ => 0xFFFF, } }
config_read_word
identifier_name
ecbadmin.rs
use common::{err, ascii, challenge, url}; use common::cipher::{aes, key, padding}; const max_blocksize: usize = 32; pub static info: challenge::Info = challenge::Info { no: 13, title: "ECB cut-and-paste", help: "", execute_fn: interactive }; struct User { email: String, uid: u32, role: String } impl User { fn new(email: &str, uid: u32, role: &str) -> User { User { email: String::from(email), uid: uid, role: String::from(role) } } fn encode(&self) -> Result<String, err::Error> { Ok(try!(url::encode(&vec![ ("email", &self.email), ("uid", &format!("{}", self.uid)), ("role", &self.role)]))) } fn decode(param_string: &str) -> Result<User, err::Error> { let params = try!(url::decode(&param_string)); Ok(User { email: params[0].1.clone(), uid: etry!(params[1].1.parse::<u32>(), "conversion error"), role: params[2].1.clone() }) } } pub struct AuthBox { key: Vec<u8>, mode: aes::Mode } impl AuthBox { fn new() -> Result<Self, err::Error> { let mode = aes::ecb_128_pkcs7; Ok(AuthBox { key: try!(key::random(mode.blocksize.unwrap())), mode: mode }) } fn authenticate(&self, cipher: &Vec<u8>) -> Result<String, err::Error> { let plain_raw = try!(aes::decrypt(&cipher, &self.key, &self.mode)); let plain_str = rts!(&plain_raw); let user = try!(User::decode(&plain_str)); Ok(user.role) } fn profile_for(&self, email: &Vec<u8>) -> Result<Vec<u8>, err::Error> { let email_str = rts!(&email); let user = User::new(&email_str, 10, "user"); let encoded = try!(user.encode()); let enc_raw = raw!(&encoded); Ok(try!(aes::encrypt(&enc_raw, &self.key, &self.mode))) } } pub fn auth_as_admin(authbox: &AuthBox) -> Result<bool, err::Error> { let blocksize = try!(detect_blocksize(&authbox, max_blocksize)); //step1: get cipher block for "admin+padding" let mut email_name = String::from("a"); let email_domain = "b.co"; let len_email = "email=".len() + email_name.len() + 1 + email_domain.len(); let email_padsize = (blocksize - (len_email % blocksize)) % blocksize; email_name.push_str(strn!('a', email_padsize).as_ref()); let email = strjoin!(&email_name, "@", &email_domain); //email that ends on a block boundary let padded_suffix_raw = try!((padding::Pkcs7.pad_fn)(&raw!("admin"), blocksize)); //"admin+padding" let mut email_raw = raw!(&email); email_raw.extend(&padded_suffix_raw); //email + "admin+padding" let token = try!(authbox.profile_for(&email_raw)); let admin_block = token.chunks(blocksize).nth(1).unwrap().to_vec(); //extract cipher block for "admin+padding" //step2: get cipher block(s) for encoded string upto role= email_name = String::from("a"); let len_upto_role = "email=".len() + email_name.len() + 1 + email_domain.len() + "&uid=10&role=".len(); let email_padsize = (blocksize - (len_upto_role % blocksize)) % blocksize; email_name.push_str(strn!('a', email_padsize).as_ref()); let token2 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, "@", &email_domain).as_ref()))); let mut new_token = token2.chunks(len_upto_role + email_padsize).next().unwrap().to_vec(); //get token upto role= //step3: append the "admin+padding" cipher block from step1 to partial token from step 2 new_token.extend(&admin_block); //step4: get the power!! let role = try!(authbox.authenticate(&new_token)); match role.as_ref() { "admin" => { println!("admin access granted!!"); Ok(true) }, _ => { println!("admin access denied :("); Ok(false) } } } fn detect_blocksize(authbox: &AuthBox, max: usize) -> Result<usize, err::Error> { let mut email_name = String::from("a"); let email_domain = "b.co"; let len1 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, &email_domain).as_ref()))).len(); for _ in 0.. max { email_name.push('a');
return Ok(len2 - len1); } } mkerr!("unable to detect cipher block size") } pub fn init_authbox() -> Result<AuthBox, err::Error> { Ok(try!(AuthBox::new())) } pub fn interactive() -> err::ExitCode { let authbox = rtry!(init_authbox(), exit_err!()); rtry!(auth_as_admin(&authbox), exit_err!()); exit_ok!() }
let len2 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, &email_domain).as_ref()))).len(); if len2 > len1 {
random_line_split
ecbadmin.rs
use common::{err, ascii, challenge, url}; use common::cipher::{aes, key, padding}; const max_blocksize: usize = 32; pub static info: challenge::Info = challenge::Info { no: 13, title: "ECB cut-and-paste", help: "", execute_fn: interactive }; struct User { email: String, uid: u32, role: String } impl User { fn new(email: &str, uid: u32, role: &str) -> User { User { email: String::from(email), uid: uid, role: String::from(role) } } fn encode(&self) -> Result<String, err::Error> { Ok(try!(url::encode(&vec![ ("email", &self.email), ("uid", &format!("{}", self.uid)), ("role", &self.role)]))) } fn decode(param_string: &str) -> Result<User, err::Error> { let params = try!(url::decode(&param_string)); Ok(User { email: params[0].1.clone(), uid: etry!(params[1].1.parse::<u32>(), "conversion error"), role: params[2].1.clone() }) } } pub struct AuthBox { key: Vec<u8>, mode: aes::Mode } impl AuthBox { fn new() -> Result<Self, err::Error> { let mode = aes::ecb_128_pkcs7; Ok(AuthBox { key: try!(key::random(mode.blocksize.unwrap())), mode: mode }) } fn authenticate(&self, cipher: &Vec<u8>) -> Result<String, err::Error> { let plain_raw = try!(aes::decrypt(&cipher, &self.key, &self.mode)); let plain_str = rts!(&plain_raw); let user = try!(User::decode(&plain_str)); Ok(user.role) } fn profile_for(&self, email: &Vec<u8>) -> Result<Vec<u8>, err::Error> { let email_str = rts!(&email); let user = User::new(&email_str, 10, "user"); let encoded = try!(user.encode()); let enc_raw = raw!(&encoded); Ok(try!(aes::encrypt(&enc_raw, &self.key, &self.mode))) } } pub fn auth_as_admin(authbox: &AuthBox) -> Result<bool, err::Error> { let blocksize = try!(detect_blocksize(&authbox, max_blocksize)); //step1: get cipher block for "admin+padding" let mut email_name = String::from("a"); let email_domain = "b.co"; let len_email = "email=".len() + email_name.len() + 1 + email_domain.len(); let email_padsize = (blocksize - (len_email % blocksize)) % blocksize; email_name.push_str(strn!('a', email_padsize).as_ref()); let email = strjoin!(&email_name, "@", &email_domain); //email that ends on a block boundary let padded_suffix_raw = try!((padding::Pkcs7.pad_fn)(&raw!("admin"), blocksize)); //"admin+padding" let mut email_raw = raw!(&email); email_raw.extend(&padded_suffix_raw); //email + "admin+padding" let token = try!(authbox.profile_for(&email_raw)); let admin_block = token.chunks(blocksize).nth(1).unwrap().to_vec(); //extract cipher block for "admin+padding" //step2: get cipher block(s) for encoded string upto role= email_name = String::from("a"); let len_upto_role = "email=".len() + email_name.len() + 1 + email_domain.len() + "&uid=10&role=".len(); let email_padsize = (blocksize - (len_upto_role % blocksize)) % blocksize; email_name.push_str(strn!('a', email_padsize).as_ref()); let token2 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, "@", &email_domain).as_ref()))); let mut new_token = token2.chunks(len_upto_role + email_padsize).next().unwrap().to_vec(); //get token upto role= //step3: append the "admin+padding" cipher block from step1 to partial token from step 2 new_token.extend(&admin_block); //step4: get the power!! let role = try!(authbox.authenticate(&new_token)); match role.as_ref() { "admin" =>
, _ => { println!("admin access denied :("); Ok(false) } } } fn detect_blocksize(authbox: &AuthBox, max: usize) -> Result<usize, err::Error> { let mut email_name = String::from("a"); let email_domain = "b.co"; let len1 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, &email_domain).as_ref()))).len(); for _ in 0.. max { email_name.push('a'); let len2 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, &email_domain).as_ref()))).len(); if len2 > len1 { return Ok(len2 - len1); } } mkerr!("unable to detect cipher block size") } pub fn init_authbox() -> Result<AuthBox, err::Error> { Ok(try!(AuthBox::new())) } pub fn interactive() -> err::ExitCode { let authbox = rtry!(init_authbox(), exit_err!()); rtry!(auth_as_admin(&authbox), exit_err!()); exit_ok!() }
{ println!("admin access granted !!"); Ok(true) }
conditional_block
ecbadmin.rs
use common::{err, ascii, challenge, url}; use common::cipher::{aes, key, padding}; const max_blocksize: usize = 32; pub static info: challenge::Info = challenge::Info { no: 13, title: "ECB cut-and-paste", help: "", execute_fn: interactive }; struct User { email: String, uid: u32, role: String } impl User { fn new(email: &str, uid: u32, role: &str) -> User { User { email: String::from(email), uid: uid, role: String::from(role) } } fn encode(&self) -> Result<String, err::Error> { Ok(try!(url::encode(&vec![ ("email", &self.email), ("uid", &format!("{}", self.uid)), ("role", &self.role)]))) } fn decode(param_string: &str) -> Result<User, err::Error> { let params = try!(url::decode(&param_string)); Ok(User { email: params[0].1.clone(), uid: etry!(params[1].1.parse::<u32>(), "conversion error"), role: params[2].1.clone() }) } } pub struct AuthBox { key: Vec<u8>, mode: aes::Mode } impl AuthBox { fn new() -> Result<Self, err::Error> { let mode = aes::ecb_128_pkcs7; Ok(AuthBox { key: try!(key::random(mode.blocksize.unwrap())), mode: mode }) } fn authenticate(&self, cipher: &Vec<u8>) -> Result<String, err::Error> { let plain_raw = try!(aes::decrypt(&cipher, &self.key, &self.mode)); let plain_str = rts!(&plain_raw); let user = try!(User::decode(&plain_str)); Ok(user.role) } fn profile_for(&self, email: &Vec<u8>) -> Result<Vec<u8>, err::Error> { let email_str = rts!(&email); let user = User::new(&email_str, 10, "user"); let encoded = try!(user.encode()); let enc_raw = raw!(&encoded); Ok(try!(aes::encrypt(&enc_raw, &self.key, &self.mode))) } } pub fn auth_as_admin(authbox: &AuthBox) -> Result<bool, err::Error> { let blocksize = try!(detect_blocksize(&authbox, max_blocksize)); //step1: get cipher block for "admin+padding" let mut email_name = String::from("a"); let email_domain = "b.co"; let len_email = "email=".len() + email_name.len() + 1 + email_domain.len(); let email_padsize = (blocksize - (len_email % blocksize)) % blocksize; email_name.push_str(strn!('a', email_padsize).as_ref()); let email = strjoin!(&email_name, "@", &email_domain); //email that ends on a block boundary let padded_suffix_raw = try!((padding::Pkcs7.pad_fn)(&raw!("admin"), blocksize)); //"admin+padding" let mut email_raw = raw!(&email); email_raw.extend(&padded_suffix_raw); //email + "admin+padding" let token = try!(authbox.profile_for(&email_raw)); let admin_block = token.chunks(blocksize).nth(1).unwrap().to_vec(); //extract cipher block for "admin+padding" //step2: get cipher block(s) for encoded string upto role= email_name = String::from("a"); let len_upto_role = "email=".len() + email_name.len() + 1 + email_domain.len() + "&uid=10&role=".len(); let email_padsize = (blocksize - (len_upto_role % blocksize)) % blocksize; email_name.push_str(strn!('a', email_padsize).as_ref()); let token2 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, "@", &email_domain).as_ref()))); let mut new_token = token2.chunks(len_upto_role + email_padsize).next().unwrap().to_vec(); //get token upto role= //step3: append the "admin+padding" cipher block from step1 to partial token from step 2 new_token.extend(&admin_block); //step4: get the power!! let role = try!(authbox.authenticate(&new_token)); match role.as_ref() { "admin" => { println!("admin access granted!!"); Ok(true) }, _ => { println!("admin access denied :("); Ok(false) } } } fn detect_blocksize(authbox: &AuthBox, max: usize) -> Result<usize, err::Error>
pub fn init_authbox() -> Result<AuthBox, err::Error> { Ok(try!(AuthBox::new())) } pub fn interactive() -> err::ExitCode { let authbox = rtry!(init_authbox(), exit_err!()); rtry!(auth_as_admin(&authbox), exit_err!()); exit_ok!() }
{ let mut email_name = String::from("a"); let email_domain = "b.co"; let len1 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, &email_domain).as_ref()))).len(); for _ in 0 .. max { email_name.push('a'); let len2 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, &email_domain).as_ref()))).len(); if len2 > len1 { return Ok(len2 - len1); } } mkerr!("unable to detect cipher block size") }
identifier_body
ecbadmin.rs
use common::{err, ascii, challenge, url}; use common::cipher::{aes, key, padding}; const max_blocksize: usize = 32; pub static info: challenge::Info = challenge::Info { no: 13, title: "ECB cut-and-paste", help: "", execute_fn: interactive }; struct User { email: String, uid: u32, role: String } impl User { fn new(email: &str, uid: u32, role: &str) -> User { User { email: String::from(email), uid: uid, role: String::from(role) } } fn encode(&self) -> Result<String, err::Error> { Ok(try!(url::encode(&vec![ ("email", &self.email), ("uid", &format!("{}", self.uid)), ("role", &self.role)]))) } fn decode(param_string: &str) -> Result<User, err::Error> { let params = try!(url::decode(&param_string)); Ok(User { email: params[0].1.clone(), uid: etry!(params[1].1.parse::<u32>(), "conversion error"), role: params[2].1.clone() }) } } pub struct AuthBox { key: Vec<u8>, mode: aes::Mode } impl AuthBox { fn new() -> Result<Self, err::Error> { let mode = aes::ecb_128_pkcs7; Ok(AuthBox { key: try!(key::random(mode.blocksize.unwrap())), mode: mode }) } fn authenticate(&self, cipher: &Vec<u8>) -> Result<String, err::Error> { let plain_raw = try!(aes::decrypt(&cipher, &self.key, &self.mode)); let plain_str = rts!(&plain_raw); let user = try!(User::decode(&plain_str)); Ok(user.role) } fn profile_for(&self, email: &Vec<u8>) -> Result<Vec<u8>, err::Error> { let email_str = rts!(&email); let user = User::new(&email_str, 10, "user"); let encoded = try!(user.encode()); let enc_raw = raw!(&encoded); Ok(try!(aes::encrypt(&enc_raw, &self.key, &self.mode))) } } pub fn auth_as_admin(authbox: &AuthBox) -> Result<bool, err::Error> { let blocksize = try!(detect_blocksize(&authbox, max_blocksize)); //step1: get cipher block for "admin+padding" let mut email_name = String::from("a"); let email_domain = "b.co"; let len_email = "email=".len() + email_name.len() + 1 + email_domain.len(); let email_padsize = (blocksize - (len_email % blocksize)) % blocksize; email_name.push_str(strn!('a', email_padsize).as_ref()); let email = strjoin!(&email_name, "@", &email_domain); //email that ends on a block boundary let padded_suffix_raw = try!((padding::Pkcs7.pad_fn)(&raw!("admin"), blocksize)); //"admin+padding" let mut email_raw = raw!(&email); email_raw.extend(&padded_suffix_raw); //email + "admin+padding" let token = try!(authbox.profile_for(&email_raw)); let admin_block = token.chunks(blocksize).nth(1).unwrap().to_vec(); //extract cipher block for "admin+padding" //step2: get cipher block(s) for encoded string upto role= email_name = String::from("a"); let len_upto_role = "email=".len() + email_name.len() + 1 + email_domain.len() + "&uid=10&role=".len(); let email_padsize = (blocksize - (len_upto_role % blocksize)) % blocksize; email_name.push_str(strn!('a', email_padsize).as_ref()); let token2 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, "@", &email_domain).as_ref()))); let mut new_token = token2.chunks(len_upto_role + email_padsize).next().unwrap().to_vec(); //get token upto role= //step3: append the "admin+padding" cipher block from step1 to partial token from step 2 new_token.extend(&admin_block); //step4: get the power!! let role = try!(authbox.authenticate(&new_token)); match role.as_ref() { "admin" => { println!("admin access granted!!"); Ok(true) }, _ => { println!("admin access denied :("); Ok(false) } } } fn detect_blocksize(authbox: &AuthBox, max: usize) -> Result<usize, err::Error> { let mut email_name = String::from("a"); let email_domain = "b.co"; let len1 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, &email_domain).as_ref()))).len(); for _ in 0.. max { email_name.push('a'); let len2 = try!(authbox.profile_for(&raw!(strjoin!(&email_name, &email_domain).as_ref()))).len(); if len2 > len1 { return Ok(len2 - len1); } } mkerr!("unable to detect cipher block size") } pub fn init_authbox() -> Result<AuthBox, err::Error> { Ok(try!(AuthBox::new())) } pub fn
() -> err::ExitCode { let authbox = rtry!(init_authbox(), exit_err!()); rtry!(auth_as_admin(&authbox), exit_err!()); exit_ok!() }
interactive
identifier_name
aarch64_unknown_openbsd.rs
// Copyright 2018 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 spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::openbsd_base::opts(); base.max_atomic_width = Some(128);
Ok(Target { llvm_target: "aarch64-unknown-openbsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64".to_string(), target_c_int_width: "32".to_string(), data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(), arch: "aarch64".to_string(), target_os: "openbsd".to_string(), target_env: String::new(), target_vendor: "unknown".to_string(), linker_flavor: LinkerFlavor::Gcc, options: base, }) }
base.abi_blacklist = super::arm_base::abi_blacklist();
random_line_split
aarch64_unknown_openbsd.rs
// Copyright 2018 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 spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult
{ let mut base = super::openbsd_base::opts(); base.max_atomic_width = Some(128); base.abi_blacklist = super::arm_base::abi_blacklist(); Ok(Target { llvm_target: "aarch64-unknown-openbsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64".to_string(), target_c_int_width: "32".to_string(), data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(), arch: "aarch64".to_string(), target_os: "openbsd".to_string(), target_env: String::new(), target_vendor: "unknown".to_string(), linker_flavor: LinkerFlavor::Gcc, options: base, }) }
identifier_body
aarch64_unknown_openbsd.rs
// Copyright 2018 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 spec::{LinkerFlavor, Target, TargetResult}; pub fn
() -> TargetResult { let mut base = super::openbsd_base::opts(); base.max_atomic_width = Some(128); base.abi_blacklist = super::arm_base::abi_blacklist(); Ok(Target { llvm_target: "aarch64-unknown-openbsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64".to_string(), target_c_int_width: "32".to_string(), data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(), arch: "aarch64".to_string(), target_os: "openbsd".to_string(), target_env: String::new(), target_vendor: "unknown".to_string(), linker_flavor: LinkerFlavor::Gcc, options: base, }) }
target
identifier_name
enum_count.rs
use proc_macro2::TokenStream; use quote::quote; use syn::{Data, DeriveInput}; use crate::helpers::{non_enum_error, HasTypeProperties}; pub(crate) fn enum_count_inner(ast: &DeriveInput) -> syn::Result<TokenStream>
}
{ let n = match &ast.data { Data::Enum(v) => v.variants.len(), _ => return Err(non_enum_error()), }; let type_properties = ast.get_type_properties()?; let strum_module_path = type_properties.crate_module_path(); // Used in the quasi-quotation below as `#name` let name = &ast.ident; // Helper is provided for handling complex generic types correctly and effortlessly let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); Ok(quote! { // Implementation impl #impl_generics #strum_module_path::EnumCount for #name #ty_generics #where_clause { const COUNT: usize = #n; } })
identifier_body
enum_count.rs
use proc_macro2::TokenStream; use quote::quote; use syn::{Data, DeriveInput}; use crate::helpers::{non_enum_error, HasTypeProperties}; pub(crate) fn enum_count_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let n = match &ast.data { Data::Enum(v) => v.variants.len(), _ => return Err(non_enum_error()), }; let type_properties = ast.get_type_properties()?; let strum_module_path = type_properties.crate_module_path();
// Helper is provided for handling complex generic types correctly and effortlessly let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); Ok(quote! { // Implementation impl #impl_generics #strum_module_path::EnumCount for #name #ty_generics #where_clause { const COUNT: usize = #n; } }) }
// Used in the quasi-quotation below as `#name` let name = &ast.ident;
random_line_split
enum_count.rs
use proc_macro2::TokenStream; use quote::quote; use syn::{Data, DeriveInput}; use crate::helpers::{non_enum_error, HasTypeProperties}; pub(crate) fn
(ast: &DeriveInput) -> syn::Result<TokenStream> { let n = match &ast.data { Data::Enum(v) => v.variants.len(), _ => return Err(non_enum_error()), }; let type_properties = ast.get_type_properties()?; let strum_module_path = type_properties.crate_module_path(); // Used in the quasi-quotation below as `#name` let name = &ast.ident; // Helper is provided for handling complex generic types correctly and effortlessly let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); Ok(quote! { // Implementation impl #impl_generics #strum_module_path::EnumCount for #name #ty_generics #where_clause { const COUNT: usize = #n; } }) }
enum_count_inner
identifier_name
tr.rs
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "tr"; #[test] fn test_toupper() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["a-z", "A-Z"]).run_piped_stdin(b"!abcd!"); assert_eq!(result.stdout, "!ABCD!"); } #[test] fn test_small_set2() {
let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["0-9", "X"]).run_piped_stdin(b"@0123456789"); assert_eq!(result.stdout, "@XXXXXXXXXX"); } #[test] fn test_unicode() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&[", ┬─┬", "╯︵┻━┻"]) .run_piped_stdin("(,°□°), ┬─┬".as_bytes()); assert_eq!(result.stdout, "(╯°□°)╯︵┻━┻"); } #[test] fn test_delete() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-d", "a-z"]).run_piped_stdin(b"aBcD"); assert_eq!(result.stdout, "BD"); } #[test] fn test_delete_complement() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-d", "-c", "a-z"]).run_piped_stdin(b"aBcD"); assert_eq!(result.stdout, "ac"); }
random_line_split
tr.rs
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "tr"; #[test] fn test_toupper() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["a-z", "A-Z"]).run_piped_stdin(b"!abcd!"); assert_eq!(result.stdout, "!ABCD!"); } #[test] fn test_small_set2() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["0-9", "X"]).run_piped_stdin(b"@0123456789"); assert_eq!(result.stdout, "@XXXXXXXXXX"); } #[test] fn test_unicode() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&[", ┬─┬", "╯︵┻━┻"]) .run_piped_stdin("(,°□°), ┬─┬".as_bytes()); assert_eq!(result.stdout, "(╯°□°)╯︵┻━┻"); } #[test] fn test_delete() { let (_, mut ucmd) = testin
); let result = ucmd.args(&["-d", "a-z"]).run_piped_stdin(b"aBcD"); assert_eq!(result.stdout, "BD"); } #[test] fn test_delete_complement() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-d", "-c", "a-z"]).run_piped_stdin(b"aBcD"); assert_eq!(result.stdout, "ac"); }
g(UTIL_NAME
identifier_name
tr.rs
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "tr"; #[test] fn test_toupper() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["a-z", "A-Z"]).run_piped_stdin(b"!abcd!"); assert_eq!(result.stdout, "!ABCD!"); } #[test] fn test_small_set2() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["0-9", "X"]).run_piped_stdin(b"@0123456789"); assert_eq!(result.stdout, "@XXXXXXXXXX"); } #[test] fn test_unicode()
cmd) = testing(UTIL_NAME); let result = ucmd.args(&["-d", "a-z"]).run_piped_stdin(b"aBcD"); assert_eq!(result.stdout, "BD"); } #[test] fn test_delete_complement() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-d", "-c", "a-z"]).run_piped_stdin(b"aBcD"); assert_eq!(result.stdout, "ac"); }
{ let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&[", ┬─┬", "╯︵┻━┻"]) .run_piped_stdin("(,°□°), ┬─┬".as_bytes()); assert_eq!(result.stdout, "(╯°□°)╯︵┻━┻"); } #[test] fn test_delete() { let (_, mut u
identifier_body
generate.rs
use crate::rclio::CliInputOutput; use crate::rclio::OutputType; use crate::rutil::safe_string::SafeString; use rand::{rngs::OsRng, Rng}; use std::io::Result as IoResult; fn
(alnum: bool, len: usize) -> IoResult<SafeString> { let mut password_as_string = String::new(); let mut rng = OsRng::default(); for _ in 0..len { if alnum { match rng.gen_range(0..3) { // Numbers 0-9 0 => password_as_string.push(rng.gen_range(48..58) as u8 as char), // Uppercase A-Z 1 => password_as_string.push(rng.gen_range(65..91) as u8 as char), // Lowercase a-z 2 => password_as_string.push(rng.gen_range(97..123) as u8 as char), _ => unreachable!(), } } else { password_as_string.push(rng.gen_range(33..127) as u8 as char); } } Ok(SafeString::from_string(password_as_string)) } /// Returns true if the password contains at least one digit, one uppercase letter and one /// lowercase letter. fn password_is_hard(password: &str, alnum: bool) -> bool { let is_punctuation = |c| -> bool { "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".find(c).is_some() }; password.find(char::is_numeric).is_some() && password.find(char::is_lowercase).is_some() && password.find(char::is_uppercase).is_some() && (alnum || password.find(is_punctuation).is_some()) } pub struct PasswordSpec { pub alnum: bool, pub len: usize, } impl PasswordSpec { pub fn new(alnum: bool, password_len: Option<usize>) -> PasswordSpec { PasswordSpec { alnum: alnum, len: password_len.unwrap_or(32), } } pub fn generate_hard_password(&self) -> IoResult<SafeString> { loop { let password = generate_password(self.alnum, self.len)?; if password_is_hard(password.as_ref(), self.alnum) { return Ok(password); } } } } pub fn check_password_len(opt: Option<usize>, io: &mut impl CliInputOutput) -> Option<usize> { match opt { Some(len) => { // We want passwords to contain at least one uppercase letter, one lowercase // letter and one digit. So we need at least 4 characters for each password. // This checks makes sure we don't run into an infinite loop trying to generate // a password of length < 4 with 4 different kinds of characters (uppercase, // lowercase, numeric, punctuation). if len < 4 { io.error("Woops! The length of the password must be at least 4. This allows us to make sure your password is secure.", OutputType::Error); None } else { Some(len) } } None => { io.error( "Woops! The length option must be a valid number, for instance 8 or 16.", OutputType::Error, ); None } } } #[cfg(test)] mod test { use crate::generate::PasswordSpec; use std::ops::Deref; #[test] fn test_default_password_size_is_32() { assert_eq!( PasswordSpec::new(false, None) .generate_hard_password() .unwrap() .len(), 32 ); assert_eq!( PasswordSpec::new(false, Some(16)) .generate_hard_password() .unwrap() .len(), 16 ); } #[test] fn test_generate_password_alnum() { // All alnum let ps = PasswordSpec::new(true, None); let pw = ps.generate_hard_password().unwrap(); for c in pw.deref().chars() { match c { 'a'..='z' | 'A'..='Z' | '0'..='9' => {} _ => panic!(), } } // At least one not alnum let ps = PasswordSpec::new(false, None); let pw = ps.generate_hard_password().unwrap(); let mut ok = false; for c in pw.deref().chars() { match c { 'a'..='z' | 'A'..='Z' | '0'..='9' => {} _ => ok = true, } } assert!(ok); } }
generate_password
identifier_name
generate.rs
use crate::rclio::CliInputOutput; use crate::rclio::OutputType; use crate::rutil::safe_string::SafeString; use rand::{rngs::OsRng, Rng}; use std::io::Result as IoResult; fn generate_password(alnum: bool, len: usize) -> IoResult<SafeString>
/// Returns true if the password contains at least one digit, one uppercase letter and one /// lowercase letter. fn password_is_hard(password: &str, alnum: bool) -> bool { let is_punctuation = |c| -> bool { "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".find(c).is_some() }; password.find(char::is_numeric).is_some() && password.find(char::is_lowercase).is_some() && password.find(char::is_uppercase).is_some() && (alnum || password.find(is_punctuation).is_some()) } pub struct PasswordSpec { pub alnum: bool, pub len: usize, } impl PasswordSpec { pub fn new(alnum: bool, password_len: Option<usize>) -> PasswordSpec { PasswordSpec { alnum: alnum, len: password_len.unwrap_or(32), } } pub fn generate_hard_password(&self) -> IoResult<SafeString> { loop { let password = generate_password(self.alnum, self.len)?; if password_is_hard(password.as_ref(), self.alnum) { return Ok(password); } } } } pub fn check_password_len(opt: Option<usize>, io: &mut impl CliInputOutput) -> Option<usize> { match opt { Some(len) => { // We want passwords to contain at least one uppercase letter, one lowercase // letter and one digit. So we need at least 4 characters for each password. // This checks makes sure we don't run into an infinite loop trying to generate // a password of length < 4 with 4 different kinds of characters (uppercase, // lowercase, numeric, punctuation). if len < 4 { io.error("Woops! The length of the password must be at least 4. This allows us to make sure your password is secure.", OutputType::Error); None } else { Some(len) } } None => { io.error( "Woops! The length option must be a valid number, for instance 8 or 16.", OutputType::Error, ); None } } } #[cfg(test)] mod test { use crate::generate::PasswordSpec; use std::ops::Deref; #[test] fn test_default_password_size_is_32() { assert_eq!( PasswordSpec::new(false, None) .generate_hard_password() .unwrap() .len(), 32 ); assert_eq!( PasswordSpec::new(false, Some(16)) .generate_hard_password() .unwrap() .len(), 16 ); } #[test] fn test_generate_password_alnum() { // All alnum let ps = PasswordSpec::new(true, None); let pw = ps.generate_hard_password().unwrap(); for c in pw.deref().chars() { match c { 'a'..='z' | 'A'..='Z' | '0'..='9' => {} _ => panic!(), } } // At least one not alnum let ps = PasswordSpec::new(false, None); let pw = ps.generate_hard_password().unwrap(); let mut ok = false; for c in pw.deref().chars() { match c { 'a'..='z' | 'A'..='Z' | '0'..='9' => {} _ => ok = true, } } assert!(ok); } }
{ let mut password_as_string = String::new(); let mut rng = OsRng::default(); for _ in 0..len { if alnum { match rng.gen_range(0..3) { // Numbers 0-9 0 => password_as_string.push(rng.gen_range(48..58) as u8 as char), // Uppercase A-Z 1 => password_as_string.push(rng.gen_range(65..91) as u8 as char), // Lowercase a-z 2 => password_as_string.push(rng.gen_range(97..123) as u8 as char), _ => unreachable!(), } } else { password_as_string.push(rng.gen_range(33..127) as u8 as char); } } Ok(SafeString::from_string(password_as_string)) }
identifier_body
generate.rs
use crate::rclio::CliInputOutput; use crate::rclio::OutputType; use crate::rutil::safe_string::SafeString; use rand::{rngs::OsRng, Rng}; use std::io::Result as IoResult; fn generate_password(alnum: bool, len: usize) -> IoResult<SafeString> { let mut password_as_string = String::new(); let mut rng = OsRng::default(); for _ in 0..len { if alnum { match rng.gen_range(0..3) { // Numbers 0-9 0 => password_as_string.push(rng.gen_range(48..58) as u8 as char), // Uppercase A-Z 1 => password_as_string.push(rng.gen_range(65..91) as u8 as char), // Lowercase a-z 2 => password_as_string.push(rng.gen_range(97..123) as u8 as char), _ => unreachable!(), } } else { password_as_string.push(rng.gen_range(33..127) as u8 as char); } } Ok(SafeString::from_string(password_as_string)) } /// Returns true if the password contains at least one digit, one uppercase letter and one /// lowercase letter. fn password_is_hard(password: &str, alnum: bool) -> bool { let is_punctuation = |c| -> bool { "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".find(c).is_some() }; password.find(char::is_numeric).is_some() && password.find(char::is_lowercase).is_some() && password.find(char::is_uppercase).is_some() && (alnum || password.find(is_punctuation).is_some()) } pub struct PasswordSpec { pub alnum: bool,
impl PasswordSpec { pub fn new(alnum: bool, password_len: Option<usize>) -> PasswordSpec { PasswordSpec { alnum: alnum, len: password_len.unwrap_or(32), } } pub fn generate_hard_password(&self) -> IoResult<SafeString> { loop { let password = generate_password(self.alnum, self.len)?; if password_is_hard(password.as_ref(), self.alnum) { return Ok(password); } } } } pub fn check_password_len(opt: Option<usize>, io: &mut impl CliInputOutput) -> Option<usize> { match opt { Some(len) => { // We want passwords to contain at least one uppercase letter, one lowercase // letter and one digit. So we need at least 4 characters for each password. // This checks makes sure we don't run into an infinite loop trying to generate // a password of length < 4 with 4 different kinds of characters (uppercase, // lowercase, numeric, punctuation). if len < 4 { io.error("Woops! The length of the password must be at least 4. This allows us to make sure your password is secure.", OutputType::Error); None } else { Some(len) } } None => { io.error( "Woops! The length option must be a valid number, for instance 8 or 16.", OutputType::Error, ); None } } } #[cfg(test)] mod test { use crate::generate::PasswordSpec; use std::ops::Deref; #[test] fn test_default_password_size_is_32() { assert_eq!( PasswordSpec::new(false, None) .generate_hard_password() .unwrap() .len(), 32 ); assert_eq!( PasswordSpec::new(false, Some(16)) .generate_hard_password() .unwrap() .len(), 16 ); } #[test] fn test_generate_password_alnum() { // All alnum let ps = PasswordSpec::new(true, None); let pw = ps.generate_hard_password().unwrap(); for c in pw.deref().chars() { match c { 'a'..='z' | 'A'..='Z' | '0'..='9' => {} _ => panic!(), } } // At least one not alnum let ps = PasswordSpec::new(false, None); let pw = ps.generate_hard_password().unwrap(); let mut ok = false; for c in pw.deref().chars() { match c { 'a'..='z' | 'A'..='Z' | '0'..='9' => {} _ => ok = true, } } assert!(ok); } }
pub len: usize, }
random_line_split
generate.rs
use crate::rclio::CliInputOutput; use crate::rclio::OutputType; use crate::rutil::safe_string::SafeString; use rand::{rngs::OsRng, Rng}; use std::io::Result as IoResult; fn generate_password(alnum: bool, len: usize) -> IoResult<SafeString> { let mut password_as_string = String::new(); let mut rng = OsRng::default(); for _ in 0..len { if alnum { match rng.gen_range(0..3) { // Numbers 0-9 0 => password_as_string.push(rng.gen_range(48..58) as u8 as char), // Uppercase A-Z 1 => password_as_string.push(rng.gen_range(65..91) as u8 as char), // Lowercase a-z 2 => password_as_string.push(rng.gen_range(97..123) as u8 as char), _ => unreachable!(), } } else
} Ok(SafeString::from_string(password_as_string)) } /// Returns true if the password contains at least one digit, one uppercase letter and one /// lowercase letter. fn password_is_hard(password: &str, alnum: bool) -> bool { let is_punctuation = |c| -> bool { "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".find(c).is_some() }; password.find(char::is_numeric).is_some() && password.find(char::is_lowercase).is_some() && password.find(char::is_uppercase).is_some() && (alnum || password.find(is_punctuation).is_some()) } pub struct PasswordSpec { pub alnum: bool, pub len: usize, } impl PasswordSpec { pub fn new(alnum: bool, password_len: Option<usize>) -> PasswordSpec { PasswordSpec { alnum: alnum, len: password_len.unwrap_or(32), } } pub fn generate_hard_password(&self) -> IoResult<SafeString> { loop { let password = generate_password(self.alnum, self.len)?; if password_is_hard(password.as_ref(), self.alnum) { return Ok(password); } } } } pub fn check_password_len(opt: Option<usize>, io: &mut impl CliInputOutput) -> Option<usize> { match opt { Some(len) => { // We want passwords to contain at least one uppercase letter, one lowercase // letter and one digit. So we need at least 4 characters for each password. // This checks makes sure we don't run into an infinite loop trying to generate // a password of length < 4 with 4 different kinds of characters (uppercase, // lowercase, numeric, punctuation). if len < 4 { io.error("Woops! The length of the password must be at least 4. This allows us to make sure your password is secure.", OutputType::Error); None } else { Some(len) } } None => { io.error( "Woops! The length option must be a valid number, for instance 8 or 16.", OutputType::Error, ); None } } } #[cfg(test)] mod test { use crate::generate::PasswordSpec; use std::ops::Deref; #[test] fn test_default_password_size_is_32() { assert_eq!( PasswordSpec::new(false, None) .generate_hard_password() .unwrap() .len(), 32 ); assert_eq!( PasswordSpec::new(false, Some(16)) .generate_hard_password() .unwrap() .len(), 16 ); } #[test] fn test_generate_password_alnum() { // All alnum let ps = PasswordSpec::new(true, None); let pw = ps.generate_hard_password().unwrap(); for c in pw.deref().chars() { match c { 'a'..='z' | 'A'..='Z' | '0'..='9' => {} _ => panic!(), } } // At least one not alnum let ps = PasswordSpec::new(false, None); let pw = ps.generate_hard_password().unwrap(); let mut ok = false; for c in pw.deref().chars() { match c { 'a'..='z' | 'A'..='Z' | '0'..='9' => {} _ => ok = true, } } assert!(ok); } }
{ password_as_string.push(rng.gen_range(33..127) as u8 as char); }
conditional_block
font.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/. */ //! Generic types for font stuff. use app_units::Au; use byteorder::{BigEndian, ReadBytesExt}; use cssparser::Parser; use num_traits::One; use parser::{Parse, ParserContext}; use std::fmt::{self, Write}; use std::io::Cursor; use style_traits::{CssWriter, KeywordsCollectFn, ParseError}; use style_traits::{SpecifiedValueInfo, StyleParseErrorKind, ToCss}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// https://drafts.csswg.org/css-fonts-4/#feature-tag-value #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FeatureTagValue<Integer> { /// A four-character tag, packed into a u32 (one byte per character). pub tag: FontTag, /// The actual value. pub value: Integer, } impl<Integer> ToCss for FeatureTagValue<Integer> where Integer: One + ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.tag.to_css(dest)?; // Don't serialize the default value. if self.value!= Integer::one() { dest.write_char(' ')?; self.value.to_css(dest)?; } Ok(()) } } /// Variation setting for a single feature, see: /// /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def #[derive(Animate, Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct VariationValue<Number> { /// A four-character tag, packed into a u32 (one byte per character). #[animation(constant)] pub tag: FontTag, /// The actual value. pub value: Number, } impl<Number> ComputeSquaredDistance for VariationValue<Number> where Number: ComputeSquaredDistance, { #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { if self.tag!= other.tag { return Err(()); } self.value.compute_squared_distance(&other.value) } } /// A value both for font-variation-settings and font-feature-settings. #[css(comma)] #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct FontSettings<T>(#[css(if_empty = "normal", iterable)] pub Box<[T]>); impl<T> FontSettings<T> { /// Default value of font settings as `normal`. #[inline] pub fn normal() -> Self { FontSettings(vec![].into_boxed_slice()) } } impl<T: Parse> Parse for FontSettings<T> { /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if input.try(|i| i.expect_ident_matching("normal")).is_ok() { return Ok(Self::normal()); } Ok(FontSettings( input .parse_comma_separated(|i| T::parse(context, i))? .into_boxed_slice(), )) } } /// A font four-character tag, represented as a u32 for convenience. /// /// See: /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FontTag(pub u32); impl ToCss for FontTag { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { use byteorder::{BigEndian, ByteOrder}; use std::str; let mut raw = [0u8; 4]; BigEndian::write_u32(&mut raw, self.0); str::from_utf8(&raw).unwrap_or_default().to_css(dest) } } impl Parse for FontTag { fn parse<'i, 't>( _context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let location = input.current_source_location(); let tag = input.expect_string()?; // allowed strings of length 4 containing chars: <U+20, U+7E> if tag.len()!= 4 || tag.as_bytes().iter().any(|c| *c < b''|| *c > b'~') { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let mut raw = Cursor::new(tag.as_bytes()); Ok(FontTag(raw.read_u32::<BigEndian>().unwrap())) } } #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToCss)] /// Additional information for keyword-derived font sizes. pub struct KeywordInfo<Length> { /// The keyword used pub kw: KeywordSize, /// A factor to be multiplied by the computed size of the keyword #[css(skip)] pub factor: f32, /// An additional Au offset to add to the kw*factor in the case of calcs #[css(skip)] pub offset: Length, } impl<L> KeywordInfo<L> where Au: Into<L>, { /// KeywordInfo value for font-size: medium pub fn medium() -> Self { KeywordSize::Medium.into() } } impl<L> From<KeywordSize> for KeywordInfo<L> where Au: Into<L>, { fn from(x: KeywordSize) -> Self { KeywordInfo { kw: x, factor: 1.,
} } } impl<L> SpecifiedValueInfo for KeywordInfo<L> { fn collect_completion_keywords(f: KeywordsCollectFn) { <KeywordSize as SpecifiedValueInfo>::collect_completion_keywords(f); } } /// CSS font keywords #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] #[allow(missing_docs)] pub enum KeywordSize { #[css(keyword = "xx-small")] XXSmall, XSmall, Small, Medium, Large, XLarge, #[css(keyword = "xx-large")] XXLarge, // This is not a real font keyword and will not parse // HTML font-size 7 corresponds to this value #[css(skip)] XXXLarge, } impl KeywordSize { /// Convert to an HTML <font size> value #[inline] pub fn html_size(self) -> u8 { self as u8 } } impl Default for KeywordSize { fn default() -> Self { KeywordSize::Medium } } /// A generic value for the `font-style` property. /// /// https://drafts.csswg.org/css-fonts-4/#font-style-prop #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero)] pub enum FontStyle<Angle> { #[animation(error)] Normal, #[animation(error)] Italic, #[value_info(starts_with_keyword)] Oblique(Angle), }
offset: Au(0).into(),
random_line_split
font.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/. */ //! Generic types for font stuff. use app_units::Au; use byteorder::{BigEndian, ReadBytesExt}; use cssparser::Parser; use num_traits::One; use parser::{Parse, ParserContext}; use std::fmt::{self, Write}; use std::io::Cursor; use style_traits::{CssWriter, KeywordsCollectFn, ParseError}; use style_traits::{SpecifiedValueInfo, StyleParseErrorKind, ToCss}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// https://drafts.csswg.org/css-fonts-4/#feature-tag-value #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct
<Integer> { /// A four-character tag, packed into a u32 (one byte per character). pub tag: FontTag, /// The actual value. pub value: Integer, } impl<Integer> ToCss for FeatureTagValue<Integer> where Integer: One + ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.tag.to_css(dest)?; // Don't serialize the default value. if self.value!= Integer::one() { dest.write_char(' ')?; self.value.to_css(dest)?; } Ok(()) } } /// Variation setting for a single feature, see: /// /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def #[derive(Animate, Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct VariationValue<Number> { /// A four-character tag, packed into a u32 (one byte per character). #[animation(constant)] pub tag: FontTag, /// The actual value. pub value: Number, } impl<Number> ComputeSquaredDistance for VariationValue<Number> where Number: ComputeSquaredDistance, { #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { if self.tag!= other.tag { return Err(()); } self.value.compute_squared_distance(&other.value) } } /// A value both for font-variation-settings and font-feature-settings. #[css(comma)] #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct FontSettings<T>(#[css(if_empty = "normal", iterable)] pub Box<[T]>); impl<T> FontSettings<T> { /// Default value of font settings as `normal`. #[inline] pub fn normal() -> Self { FontSettings(vec![].into_boxed_slice()) } } impl<T: Parse> Parse for FontSettings<T> { /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if input.try(|i| i.expect_ident_matching("normal")).is_ok() { return Ok(Self::normal()); } Ok(FontSettings( input .parse_comma_separated(|i| T::parse(context, i))? .into_boxed_slice(), )) } } /// A font four-character tag, represented as a u32 for convenience. /// /// See: /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FontTag(pub u32); impl ToCss for FontTag { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { use byteorder::{BigEndian, ByteOrder}; use std::str; let mut raw = [0u8; 4]; BigEndian::write_u32(&mut raw, self.0); str::from_utf8(&raw).unwrap_or_default().to_css(dest) } } impl Parse for FontTag { fn parse<'i, 't>( _context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let location = input.current_source_location(); let tag = input.expect_string()?; // allowed strings of length 4 containing chars: <U+20, U+7E> if tag.len()!= 4 || tag.as_bytes().iter().any(|c| *c < b''|| *c > b'~') { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let mut raw = Cursor::new(tag.as_bytes()); Ok(FontTag(raw.read_u32::<BigEndian>().unwrap())) } } #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToCss)] /// Additional information for keyword-derived font sizes. pub struct KeywordInfo<Length> { /// The keyword used pub kw: KeywordSize, /// A factor to be multiplied by the computed size of the keyword #[css(skip)] pub factor: f32, /// An additional Au offset to add to the kw*factor in the case of calcs #[css(skip)] pub offset: Length, } impl<L> KeywordInfo<L> where Au: Into<L>, { /// KeywordInfo value for font-size: medium pub fn medium() -> Self { KeywordSize::Medium.into() } } impl<L> From<KeywordSize> for KeywordInfo<L> where Au: Into<L>, { fn from(x: KeywordSize) -> Self { KeywordInfo { kw: x, factor: 1., offset: Au(0).into(), } } } impl<L> SpecifiedValueInfo for KeywordInfo<L> { fn collect_completion_keywords(f: KeywordsCollectFn) { <KeywordSize as SpecifiedValueInfo>::collect_completion_keywords(f); } } /// CSS font keywords #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] #[allow(missing_docs)] pub enum KeywordSize { #[css(keyword = "xx-small")] XXSmall, XSmall, Small, Medium, Large, XLarge, #[css(keyword = "xx-large")] XXLarge, // This is not a real font keyword and will not parse // HTML font-size 7 corresponds to this value #[css(skip)] XXXLarge, } impl KeywordSize { /// Convert to an HTML <font size> value #[inline] pub fn html_size(self) -> u8 { self as u8 } } impl Default for KeywordSize { fn default() -> Self { KeywordSize::Medium } } /// A generic value for the `font-style` property. /// /// https://drafts.csswg.org/css-fonts-4/#font-style-prop #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero)] pub enum FontStyle<Angle> { #[animation(error)] Normal, #[animation(error)] Italic, #[value_info(starts_with_keyword)] Oblique(Angle), }
FeatureTagValue
identifier_name
font.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/. */ //! Generic types for font stuff. use app_units::Au; use byteorder::{BigEndian, ReadBytesExt}; use cssparser::Parser; use num_traits::One; use parser::{Parse, ParserContext}; use std::fmt::{self, Write}; use std::io::Cursor; use style_traits::{CssWriter, KeywordsCollectFn, ParseError}; use style_traits::{SpecifiedValueInfo, StyleParseErrorKind, ToCss}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// https://drafts.csswg.org/css-fonts-4/#feature-tag-value #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FeatureTagValue<Integer> { /// A four-character tag, packed into a u32 (one byte per character). pub tag: FontTag, /// The actual value. pub value: Integer, } impl<Integer> ToCss for FeatureTagValue<Integer> where Integer: One + ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.tag.to_css(dest)?; // Don't serialize the default value. if self.value!= Integer::one() { dest.write_char(' ')?; self.value.to_css(dest)?; } Ok(()) } } /// Variation setting for a single feature, see: /// /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def #[derive(Animate, Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct VariationValue<Number> { /// A four-character tag, packed into a u32 (one byte per character). #[animation(constant)] pub tag: FontTag, /// The actual value. pub value: Number, } impl<Number> ComputeSquaredDistance for VariationValue<Number> where Number: ComputeSquaredDistance, { #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { if self.tag!= other.tag { return Err(()); } self.value.compute_squared_distance(&other.value) } } /// A value both for font-variation-settings and font-feature-settings. #[css(comma)] #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct FontSettings<T>(#[css(if_empty = "normal", iterable)] pub Box<[T]>); impl<T> FontSettings<T> { /// Default value of font settings as `normal`. #[inline] pub fn normal() -> Self { FontSettings(vec![].into_boxed_slice()) } } impl<T: Parse> Parse for FontSettings<T> { /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if input.try(|i| i.expect_ident_matching("normal")).is_ok() { return Ok(Self::normal()); } Ok(FontSettings( input .parse_comma_separated(|i| T::parse(context, i))? .into_boxed_slice(), )) } } /// A font four-character tag, represented as a u32 for convenience. /// /// See: /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FontTag(pub u32); impl ToCss for FontTag { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { use byteorder::{BigEndian, ByteOrder}; use std::str; let mut raw = [0u8; 4]; BigEndian::write_u32(&mut raw, self.0); str::from_utf8(&raw).unwrap_or_default().to_css(dest) } } impl Parse for FontTag { fn parse<'i, 't>( _context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let location = input.current_source_location(); let tag = input.expect_string()?; // allowed strings of length 4 containing chars: <U+20, U+7E> if tag.len()!= 4 || tag.as_bytes().iter().any(|c| *c < b''|| *c > b'~') { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let mut raw = Cursor::new(tag.as_bytes()); Ok(FontTag(raw.read_u32::<BigEndian>().unwrap())) } } #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToCss)] /// Additional information for keyword-derived font sizes. pub struct KeywordInfo<Length> { /// The keyword used pub kw: KeywordSize, /// A factor to be multiplied by the computed size of the keyword #[css(skip)] pub factor: f32, /// An additional Au offset to add to the kw*factor in the case of calcs #[css(skip)] pub offset: Length, } impl<L> KeywordInfo<L> where Au: Into<L>, { /// KeywordInfo value for font-size: medium pub fn medium() -> Self { KeywordSize::Medium.into() } } impl<L> From<KeywordSize> for KeywordInfo<L> where Au: Into<L>, { fn from(x: KeywordSize) -> Self { KeywordInfo { kw: x, factor: 1., offset: Au(0).into(), } } } impl<L> SpecifiedValueInfo for KeywordInfo<L> { fn collect_completion_keywords(f: KeywordsCollectFn) { <KeywordSize as SpecifiedValueInfo>::collect_completion_keywords(f); } } /// CSS font keywords #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] #[allow(missing_docs)] pub enum KeywordSize { #[css(keyword = "xx-small")] XXSmall, XSmall, Small, Medium, Large, XLarge, #[css(keyword = "xx-large")] XXLarge, // This is not a real font keyword and will not parse // HTML font-size 7 corresponds to this value #[css(skip)] XXXLarge, } impl KeywordSize { /// Convert to an HTML <font size> value #[inline] pub fn html_size(self) -> u8 { self as u8 } } impl Default for KeywordSize { fn default() -> Self
} /// A generic value for the `font-style` property. /// /// https://drafts.csswg.org/css-fonts-4/#font-style-prop #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero)] pub enum FontStyle<Angle> { #[animation(error)] Normal, #[animation(error)] Italic, #[value_info(starts_with_keyword)] Oblique(Angle), }
{ KeywordSize::Medium }
identifier_body
font.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/. */ //! Generic types for font stuff. use app_units::Au; use byteorder::{BigEndian, ReadBytesExt}; use cssparser::Parser; use num_traits::One; use parser::{Parse, ParserContext}; use std::fmt::{self, Write}; use std::io::Cursor; use style_traits::{CssWriter, KeywordsCollectFn, ParseError}; use style_traits::{SpecifiedValueInfo, StyleParseErrorKind, ToCss}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// https://drafts.csswg.org/css-fonts-4/#feature-tag-value #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FeatureTagValue<Integer> { /// A four-character tag, packed into a u32 (one byte per character). pub tag: FontTag, /// The actual value. pub value: Integer, } impl<Integer> ToCss for FeatureTagValue<Integer> where Integer: One + ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.tag.to_css(dest)?; // Don't serialize the default value. if self.value!= Integer::one() { dest.write_char(' ')?; self.value.to_css(dest)?; } Ok(()) } } /// Variation setting for a single feature, see: /// /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def #[derive(Animate, Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct VariationValue<Number> { /// A four-character tag, packed into a u32 (one byte per character). #[animation(constant)] pub tag: FontTag, /// The actual value. pub value: Number, } impl<Number> ComputeSquaredDistance for VariationValue<Number> where Number: ComputeSquaredDistance, { #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { if self.tag!= other.tag { return Err(()); } self.value.compute_squared_distance(&other.value) } } /// A value both for font-variation-settings and font-feature-settings. #[css(comma)] #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct FontSettings<T>(#[css(if_empty = "normal", iterable)] pub Box<[T]>); impl<T> FontSettings<T> { /// Default value of font settings as `normal`. #[inline] pub fn normal() -> Self { FontSettings(vec![].into_boxed_slice()) } } impl<T: Parse> Parse for FontSettings<T> { /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if input.try(|i| i.expect_ident_matching("normal")).is_ok() { return Ok(Self::normal()); } Ok(FontSettings( input .parse_comma_separated(|i| T::parse(context, i))? .into_boxed_slice(), )) } } /// A font four-character tag, represented as a u32 for convenience. /// /// See: /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FontTag(pub u32); impl ToCss for FontTag { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { use byteorder::{BigEndian, ByteOrder}; use std::str; let mut raw = [0u8; 4]; BigEndian::write_u32(&mut raw, self.0); str::from_utf8(&raw).unwrap_or_default().to_css(dest) } } impl Parse for FontTag { fn parse<'i, 't>( _context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let location = input.current_source_location(); let tag = input.expect_string()?; // allowed strings of length 4 containing chars: <U+20, U+7E> if tag.len()!= 4 || tag.as_bytes().iter().any(|c| *c < b''|| *c > b'~')
let mut raw = Cursor::new(tag.as_bytes()); Ok(FontTag(raw.read_u32::<BigEndian>().unwrap())) } } #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToCss)] /// Additional information for keyword-derived font sizes. pub struct KeywordInfo<Length> { /// The keyword used pub kw: KeywordSize, /// A factor to be multiplied by the computed size of the keyword #[css(skip)] pub factor: f32, /// An additional Au offset to add to the kw*factor in the case of calcs #[css(skip)] pub offset: Length, } impl<L> KeywordInfo<L> where Au: Into<L>, { /// KeywordInfo value for font-size: medium pub fn medium() -> Self { KeywordSize::Medium.into() } } impl<L> From<KeywordSize> for KeywordInfo<L> where Au: Into<L>, { fn from(x: KeywordSize) -> Self { KeywordInfo { kw: x, factor: 1., offset: Au(0).into(), } } } impl<L> SpecifiedValueInfo for KeywordInfo<L> { fn collect_completion_keywords(f: KeywordsCollectFn) { <KeywordSize as SpecifiedValueInfo>::collect_completion_keywords(f); } } /// CSS font keywords #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] #[allow(missing_docs)] pub enum KeywordSize { #[css(keyword = "xx-small")] XXSmall, XSmall, Small, Medium, Large, XLarge, #[css(keyword = "xx-large")] XXLarge, // This is not a real font keyword and will not parse // HTML font-size 7 corresponds to this value #[css(skip)] XXXLarge, } impl KeywordSize { /// Convert to an HTML <font size> value #[inline] pub fn html_size(self) -> u8 { self as u8 } } impl Default for KeywordSize { fn default() -> Self { KeywordSize::Medium } } /// A generic value for the `font-style` property. /// /// https://drafts.csswg.org/css-fonts-4/#font-style-prop #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero)] pub enum FontStyle<Angle> { #[animation(error)] Normal, #[animation(error)] Italic, #[value_info(starts_with_keyword)] Oblique(Angle), }
{ return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); }
conditional_block
lazy-and-or.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn incr(x: &mut int) -> bool { *x += 1; assert!((false)); return false; } pub fn main() { let x = 1 == 2 || 3 == 3; assert!((x)); let mut y: int = 10; info2!("{:?}", x || incr(&mut y)); assert_eq!(y, 10); if true && x
else { assert!((false)); } }
{ assert!((true)); }
conditional_block
lazy-and-or.rs
// Copyright 2012 The Rust Project Developers. See the 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. fn incr(x: &mut int) -> bool { *x += 1; assert!((false)); return false; } pub fn main() { let x = 1 == 2 || 3 == 3; assert!((x)); let mut y: int = 10; info2!("{:?}", x || incr(&mut y)); assert_eq!(y, 10); if true && x { assert!((true)); } else { assert!((false)); } }
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
lazy-and-or.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn
(x: &mut int) -> bool { *x += 1; assert!((false)); return false; } pub fn main() { let x = 1 == 2 || 3 == 3; assert!((x)); let mut y: int = 10; info2!("{:?}", x || incr(&mut y)); assert_eq!(y, 10); if true && x { assert!((true)); } else { assert!((false)); } }
incr
identifier_name
lazy-and-or.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn incr(x: &mut int) -> bool
pub fn main() { let x = 1 == 2 || 3 == 3; assert!((x)); let mut y: int = 10; info2!("{:?}", x || incr(&mut y)); assert_eq!(y, 10); if true && x { assert!((true)); } else { assert!((false)); } }
{ *x += 1; assert!((false)); return false; }
identifier_body
schema.rs
use types::{ChecksumType, Column, ColumnValue}; use v1::row::{Row}; use v1::write::{schema_write}; use v1::read::schema_read; use v1::parse::parse_string; use std::io::{Error, ErrorKind, Read, Write}; use std::str; pub struct Metadata { pub checksum: ChecksumType, pub header_bytes: usize, // ordered list of columns pub columns: Vec<Column>, } impl Metadata { pub fn parse<R: Read>(reader: &mut R) -> Result<Self, Error>
pub fn write<W: Write>(&self, writer: &mut W, names: &[&str], values: &[ColumnValue]) { schema_write( &self.columns, writer, names, values, self.header_bytes, &self.checksum ); } pub fn read<R: Read>(&self, reader: &mut R) -> Row { loop { let r = schema_read( &self.columns, reader, self.header_bytes, &self.checksum ); if r.is_some() { return r.unwrap(); } println!("continuing with next row"); } } }
{ let mut s: String = String::new(); match reader.read_to_string(&mut s) { Ok(_) => { parse_string(&s).ok_or(Error::new(ErrorKind::Other, "parsing failed")) } Err(why) => Err(why), } }
identifier_body
schema.rs
use types::{ChecksumType, Column, ColumnValue}; use v1::row::{Row}; use v1::write::{schema_write}; use v1::read::schema_read; use v1::parse::parse_string; use std::io::{Error, ErrorKind, Read, Write}; use std::str; pub struct Metadata { pub checksum: ChecksumType, pub header_bytes: usize, // ordered list of columns pub columns: Vec<Column>, } impl Metadata { pub fn parse<R: Read>(reader: &mut R) -> Result<Self, Error> { let mut s: String = String::new(); match reader.read_to_string(&mut s) { Ok(_) =>
Err(why) => Err(why), } } pub fn write<W: Write>(&self, writer: &mut W, names: &[&str], values: &[ColumnValue]) { schema_write( &self.columns, writer, names, values, self.header_bytes, &self.checksum ); } pub fn read<R: Read>(&self, reader: &mut R) -> Row { loop { let r = schema_read( &self.columns, reader, self.header_bytes, &self.checksum ); if r.is_some() { return r.unwrap(); } println!("continuing with next row"); } } }
{ parse_string(&s).ok_or(Error::new(ErrorKind::Other, "parsing failed")) }
conditional_block
schema.rs
use types::{ChecksumType, Column, ColumnValue}; use v1::row::{Row}; use v1::write::{schema_write}; use v1::read::schema_read; use v1::parse::parse_string; use std::io::{Error, ErrorKind, Read, Write}; use std::str; pub struct
{ pub checksum: ChecksumType, pub header_bytes: usize, // ordered list of columns pub columns: Vec<Column>, } impl Metadata { pub fn parse<R: Read>(reader: &mut R) -> Result<Self, Error> { let mut s: String = String::new(); match reader.read_to_string(&mut s) { Ok(_) => { parse_string(&s).ok_or(Error::new(ErrorKind::Other, "parsing failed")) } Err(why) => Err(why), } } pub fn write<W: Write>(&self, writer: &mut W, names: &[&str], values: &[ColumnValue]) { schema_write( &self.columns, writer, names, values, self.header_bytes, &self.checksum ); } pub fn read<R: Read>(&self, reader: &mut R) -> Row { loop { let r = schema_read( &self.columns, reader, self.header_bytes, &self.checksum ); if r.is_some() { return r.unwrap(); } println!("continuing with next row"); } } }
Metadata
identifier_name
schema.rs
use types::{ChecksumType, Column, ColumnValue}; use v1::row::{Row}; use v1::write::{schema_write}; use v1::read::schema_read; use v1::parse::parse_string; use std::io::{Error, ErrorKind, Read, Write}; use std::str; pub struct Metadata { pub checksum: ChecksumType, pub header_bytes: usize, // ordered list of columns pub columns: Vec<Column>, } impl Metadata { pub fn parse<R: Read>(reader: &mut R) -> Result<Self, Error> { let mut s: String = String::new(); match reader.read_to_string(&mut s) { Ok(_) => { parse_string(&s).ok_or(Error::new(ErrorKind::Other, "parsing failed")) } Err(why) => Err(why), } }
values: &[ColumnValue]) { schema_write( &self.columns, writer, names, values, self.header_bytes, &self.checksum ); } pub fn read<R: Read>(&self, reader: &mut R) -> Row { loop { let r = schema_read( &self.columns, reader, self.header_bytes, &self.checksum ); if r.is_some() { return r.unwrap(); } println!("continuing with next row"); } } }
pub fn write<W: Write>(&self, writer: &mut W, names: &[&str],
random_line_split
history_traversal.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 script_thread::{CommonScriptMsg, MainThreadScriptMsg, ScriptChan}; use std::sync::mpsc::Sender; #[derive(JSTraceable)] pub struct HistoryTraversalTaskSource(pub Sender<MainThreadScriptMsg>); impl ScriptChan for HistoryTraversalTaskSource { fn
(&self, msg: CommonScriptMsg) -> Result<(), ()> { let HistoryTraversalTaskSource(ref chan) = *self; chan.send(MainThreadScriptMsg::Common(msg)).map_err(|_| ()) } fn clone(&self) -> Box<ScriptChan + Send> { let HistoryTraversalTaskSource(ref chan) = *self; box HistoryTraversalTaskSource((*chan).clone()) } }
send
identifier_name
history_traversal.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 script_thread::{CommonScriptMsg, MainThreadScriptMsg, ScriptChan}; use std::sync::mpsc::Sender; #[derive(JSTraceable)] pub struct HistoryTraversalTaskSource(pub Sender<MainThreadScriptMsg>);
impl ScriptChan for HistoryTraversalTaskSource { fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { let HistoryTraversalTaskSource(ref chan) = *self; chan.send(MainThreadScriptMsg::Common(msg)).map_err(|_| ()) } fn clone(&self) -> Box<ScriptChan + Send> { let HistoryTraversalTaskSource(ref chan) = *self; box HistoryTraversalTaskSource((*chan).clone()) } }
random_line_split
main.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.12 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #![feature(globs)] use std::io::*; use std::str;
let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println!("Listening on [{}]...", addr); for stream in acceptor.incoming() { match stream { Err(_) => (), // Spawn a task to handle the connection Ok(mut stream) => spawn(proc() { match stream.peer_name() { Err(_) => (), Ok(pn) => println!("Received connection from: [{}]", pn), } let mut buf = [0,..500]; let _ = stream.read(&mut buf); let request_str = str::from_utf8(&buf); println!("Received request :\n{}", request_str); let response = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"; let _ = stream.write(response.as_bytes()); println!("Connection terminates."); }), } } drop(acceptor); }
fn main() { let addr = "127.0.0.1:4414";
random_line_split
main.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.12 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #![feature(globs)] use std::io::*; use std::str; fn
() { let addr = "127.0.0.1:4414"; let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println!("Listening on [{}]...", addr); for stream in acceptor.incoming() { match stream { Err(_) => (), // Spawn a task to handle the connection Ok(mut stream) => spawn(proc() { match stream.peer_name() { Err(_) => (), Ok(pn) => println!("Received connection from: [{}]", pn), } let mut buf = [0,..500]; let _ = stream.read(&mut buf); let request_str = str::from_utf8(&buf); println!("Received request :\n{}", request_str); let response = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"; let _ = stream.write(response.as_bytes()); println!("Connection terminates."); }), } } drop(acceptor); }
main
identifier_name
main.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.12 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #![feature(globs)] use std::io::*; use std::str; fn main()
println!("Received request :\n{}", request_str); let response = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"; let _ = stream.write(response.as_bytes()); println!("Connection terminates."); }), } } drop(acceptor); }
{ let addr = "127.0.0.1:4414"; let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println!("Listening on [{}] ...", addr); for stream in acceptor.incoming() { match stream { Err(_) => (), // Spawn a task to handle the connection Ok(mut stream) => spawn(proc() { match stream.peer_name() { Err(_) => (), Ok(pn) => println!("Received connection from: [{}]", pn), } let mut buf = [0, ..500]; let _ = stream.read(&mut buf); let request_str = str::from_utf8(&buf);
identifier_body
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::str::DOMString; use dom::comment::Comment; use dom::document::Document; use dom::element::Element; use dom::node::{Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DOMRefCell<DOMString>, } impl CharacterData { pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData { CharacterData { node: Node::new_inherited(document), data: DOMRefCell::new(data), } } pub fn clone_with_data(&self, data: DOMString, document: &Document) -> Root<Node> { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { Root::upcast(Comment::new(data, &document)) } NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { let pi = self.downcast::<ProcessingInstruction>().unwrap(); Root::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) }, NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { Root::upcast(Text::new(data, &document)) }, _ => unreachable!(), } } #[inline] pub fn data(&self) -> Ref<DOMString> { self.data.borrow() } #[inline] pub fn append_data(&self, data: &str) { self.data.borrow_mut().push_str(data); self.content_changed(); } fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(&self, data: DOMString) { let old_length = self.Length(); let new_length = data.encode_utf16().count() as u32; *self.data.borrow_mut() = data; self.content_changed(); let node = self.upcast::<Node>(); node.ranges().replace_code_units(node, 0, old_length, new_length); } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(&self) -> u32 { self.data.borrow().encode_utf16().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let mut substring = String::new(); let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } remaining = s; } // Step 2. Err(()) => return Err(Error::IndexSize), } match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => substring = substring + remaining, // Steps 4. Ok((s, astral, _)) => { substring = substring + s; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } } }; Ok(DOMString::from(substring)) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata fn AppendData(&self, data: DOMString) { // FIXME(ajeffrey): Efficient append on DOMStrings? self.append_data(&*data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, DOMString::new()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let mut new_data; { let data = self.data.borrow(); let prefix; let replacement_before; let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((p, astral, r)) => { prefix = p; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" }; remaining = r; } // Step 2. Err(()) => return Err(Error::IndexSize), }; let replacement_after; let suffix; match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => { replacement_after = ""; suffix = ""; } Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" }; suffix = s; } }; // Step 4: Mutation observers. // Step 5 to 7. new_data = String::with_capacity( prefix.len() + replacement_before.len() + arg.len() + replacement_after.len() + suffix.len()); new_data.push_str(prefix); new_data.push_str(replacement_before); new_data.push_str(&arg); new_data.push_str(replacement_after); new_data.push_str(suffix); } *self.data.borrow_mut() = DOMString::from(new_data); self.content_changed(); // Steps 8-11. let node = self.upcast::<Node>(); node.ranges().replace_code_units( node, offset, count, arg.encode_utf16().count() as u32); Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult
// https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { let node = self.upcast::<Node>(); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout(&self) -> &str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> { #[inline] unsafe fn data_for_layout(&self) -> &str { &(*self.unsafe_get()).data.borrow_for_layout() } } /// Split the given string at the given position measured in UTF-16 code units from the start. /// /// * `Err(())` indicates that `offset` if after the end of the string /// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points. /// The two string slices are such that: /// `before == s.to_utf16()[..offset].to_utf8()` and /// `after == s.to_utf16()[offset..].to_utf8()` /// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle" /// of a single Unicode code point that would be represented in UTF-16 by a surrogate pair /// of two 16-bit code units. /// `ch` is that code point. /// The two string slices are such that: /// `before == s.to_utf16()[..offset - 1].to_utf8()` and /// `after == s.to_utf16()[offset + 1..].to_utf8()` /// /// # Panics /// /// Note that the third variant is only ever returned when the `-Z replace-surrogates` /// command-line option is specified. /// When it *would* be returned but the option is *not* specified, this function panics. fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> { let mut code_units = 0; for (i, c) in s.char_indices() { if code_units == offset { let (a, b) = s.split_at(i); return Ok((a, None, b)); } code_units += 1; if c > '\u{FFFF}' { if code_units == offset { if opts::get().replace_surrogates { debug_assert!(c.len_utf8() == 4); return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])) } panic!("\n\n\ Would split a surrogate pair in CharacterData API.\n\ If you see this in real content, please comment with the URL\n\ on https://github.com/servo/servo/issues/6873\n\ \n"); } code_units += 1; } } if code_units == offset { Ok((s, None, "")) } else { Err(()) } }
{ self.upcast::<Node>().before(nodes) }
identifier_body
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::str::DOMString; use dom::comment::Comment; use dom::document::Document; use dom::element::Element; use dom::node::{Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DOMRefCell<DOMString>, } impl CharacterData { pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData { CharacterData { node: Node::new_inherited(document), data: DOMRefCell::new(data), } } pub fn clone_with_data(&self, data: DOMString, document: &Document) -> Root<Node> { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { Root::upcast(Comment::new(data, &document)) } NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { let pi = self.downcast::<ProcessingInstruction>().unwrap(); Root::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) }, NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { Root::upcast(Text::new(data, &document)) }, _ => unreachable!(), } } #[inline] pub fn data(&self) -> Ref<DOMString> { self.data.borrow() } #[inline] pub fn append_data(&self, data: &str) { self.data.borrow_mut().push_str(data); self.content_changed(); } fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(&self, data: DOMString) { let old_length = self.Length(); let new_length = data.encode_utf16().count() as u32; *self.data.borrow_mut() = data; self.content_changed(); let node = self.upcast::<Node>(); node.ranges().replace_code_units(node, 0, old_length, new_length); } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(&self) -> u32 {
} // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let mut substring = String::new(); let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } remaining = s; } // Step 2. Err(()) => return Err(Error::IndexSize), } match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => substring = substring + remaining, // Steps 4. Ok((s, astral, _)) => { substring = substring + s; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } } }; Ok(DOMString::from(substring)) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata fn AppendData(&self, data: DOMString) { // FIXME(ajeffrey): Efficient append on DOMStrings? self.append_data(&*data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, DOMString::new()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let mut new_data; { let data = self.data.borrow(); let prefix; let replacement_before; let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((p, astral, r)) => { prefix = p; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" }; remaining = r; } // Step 2. Err(()) => return Err(Error::IndexSize), }; let replacement_after; let suffix; match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => { replacement_after = ""; suffix = ""; } Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" }; suffix = s; } }; // Step 4: Mutation observers. // Step 5 to 7. new_data = String::with_capacity( prefix.len() + replacement_before.len() + arg.len() + replacement_after.len() + suffix.len()); new_data.push_str(prefix); new_data.push_str(replacement_before); new_data.push_str(&arg); new_data.push_str(replacement_after); new_data.push_str(suffix); } *self.data.borrow_mut() = DOMString::from(new_data); self.content_changed(); // Steps 8-11. let node = self.upcast::<Node>(); node.ranges().replace_code_units( node, offset, count, arg.encode_utf16().count() as u32); Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { let node = self.upcast::<Node>(); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout(&self) -> &str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> { #[inline] unsafe fn data_for_layout(&self) -> &str { &(*self.unsafe_get()).data.borrow_for_layout() } } /// Split the given string at the given position measured in UTF-16 code units from the start. /// /// * `Err(())` indicates that `offset` if after the end of the string /// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points. /// The two string slices are such that: /// `before == s.to_utf16()[..offset].to_utf8()` and /// `after == s.to_utf16()[offset..].to_utf8()` /// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle" /// of a single Unicode code point that would be represented in UTF-16 by a surrogate pair /// of two 16-bit code units. /// `ch` is that code point. /// The two string slices are such that: /// `before == s.to_utf16()[..offset - 1].to_utf8()` and /// `after == s.to_utf16()[offset + 1..].to_utf8()` /// /// # Panics /// /// Note that the third variant is only ever returned when the `-Z replace-surrogates` /// command-line option is specified. /// When it *would* be returned but the option is *not* specified, this function panics. fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> { let mut code_units = 0; for (i, c) in s.char_indices() { if code_units == offset { let (a, b) = s.split_at(i); return Ok((a, None, b)); } code_units += 1; if c > '\u{FFFF}' { if code_units == offset { if opts::get().replace_surrogates { debug_assert!(c.len_utf8() == 4); return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])) } panic!("\n\n\ Would split a surrogate pair in CharacterData API.\n\ If you see this in real content, please comment with the URL\n\ on https://github.com/servo/servo/issues/6873\n\ \n"); } code_units += 1; } } if code_units == offset { Ok((s, None, "")) } else { Err(()) } }
self.data.borrow().encode_utf16().count() as u32
random_line_split
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::str::DOMString; use dom::comment::Comment; use dom::document::Document; use dom::element::Element; use dom::node::{Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DOMRefCell<DOMString>, } impl CharacterData { pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData { CharacterData { node: Node::new_inherited(document), data: DOMRefCell::new(data), } } pub fn
(&self, data: DOMString, document: &Document) -> Root<Node> { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { Root::upcast(Comment::new(data, &document)) } NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { let pi = self.downcast::<ProcessingInstruction>().unwrap(); Root::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) }, NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { Root::upcast(Text::new(data, &document)) }, _ => unreachable!(), } } #[inline] pub fn data(&self) -> Ref<DOMString> { self.data.borrow() } #[inline] pub fn append_data(&self, data: &str) { self.data.borrow_mut().push_str(data); self.content_changed(); } fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(&self, data: DOMString) { let old_length = self.Length(); let new_length = data.encode_utf16().count() as u32; *self.data.borrow_mut() = data; self.content_changed(); let node = self.upcast::<Node>(); node.ranges().replace_code_units(node, 0, old_length, new_length); } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(&self) -> u32 { self.data.borrow().encode_utf16().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let mut substring = String::new(); let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } remaining = s; } // Step 2. Err(()) => return Err(Error::IndexSize), } match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => substring = substring + remaining, // Steps 4. Ok((s, astral, _)) => { substring = substring + s; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } } }; Ok(DOMString::from(substring)) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata fn AppendData(&self, data: DOMString) { // FIXME(ajeffrey): Efficient append on DOMStrings? self.append_data(&*data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, DOMString::new()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let mut new_data; { let data = self.data.borrow(); let prefix; let replacement_before; let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((p, astral, r)) => { prefix = p; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" }; remaining = r; } // Step 2. Err(()) => return Err(Error::IndexSize), }; let replacement_after; let suffix; match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => { replacement_after = ""; suffix = ""; } Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" }; suffix = s; } }; // Step 4: Mutation observers. // Step 5 to 7. new_data = String::with_capacity( prefix.len() + replacement_before.len() + arg.len() + replacement_after.len() + suffix.len()); new_data.push_str(prefix); new_data.push_str(replacement_before); new_data.push_str(&arg); new_data.push_str(replacement_after); new_data.push_str(suffix); } *self.data.borrow_mut() = DOMString::from(new_data); self.content_changed(); // Steps 8-11. let node = self.upcast::<Node>(); node.ranges().replace_code_units( node, offset, count, arg.encode_utf16().count() as u32); Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { let node = self.upcast::<Node>(); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout(&self) -> &str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> { #[inline] unsafe fn data_for_layout(&self) -> &str { &(*self.unsafe_get()).data.borrow_for_layout() } } /// Split the given string at the given position measured in UTF-16 code units from the start. /// /// * `Err(())` indicates that `offset` if after the end of the string /// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points. /// The two string slices are such that: /// `before == s.to_utf16()[..offset].to_utf8()` and /// `after == s.to_utf16()[offset..].to_utf8()` /// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle" /// of a single Unicode code point that would be represented in UTF-16 by a surrogate pair /// of two 16-bit code units. /// `ch` is that code point. /// The two string slices are such that: /// `before == s.to_utf16()[..offset - 1].to_utf8()` and /// `after == s.to_utf16()[offset + 1..].to_utf8()` /// /// # Panics /// /// Note that the third variant is only ever returned when the `-Z replace-surrogates` /// command-line option is specified. /// When it *would* be returned but the option is *not* specified, this function panics. fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> { let mut code_units = 0; for (i, c) in s.char_indices() { if code_units == offset { let (a, b) = s.split_at(i); return Ok((a, None, b)); } code_units += 1; if c > '\u{FFFF}' { if code_units == offset { if opts::get().replace_surrogates { debug_assert!(c.len_utf8() == 4); return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])) } panic!("\n\n\ Would split a surrogate pair in CharacterData API.\n\ If you see this in real content, please comment with the URL\n\ on https://github.com/servo/servo/issues/6873\n\ \n"); } code_units += 1; } } if code_units == offset { Ok((s, None, "")) } else { Err(()) } }
clone_with_data
identifier_name
assert-eq-macro-success.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[derive(PartialEq, Debug)] struct Point { x : int } pub fn main() { assert_eq!(14,14);
assert_eq!(&Point{x:34},&Point{x:34}); }
assert_eq!("abc".to_string(),"abc".to_string()); assert_eq!(Box::new(Point{x:34}),Box::new(Point{x:34}));
random_line_split
assert-eq-macro-success.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[derive(PartialEq, Debug)] struct Point { x : int } pub fn main()
{ assert_eq!(14,14); assert_eq!("abc".to_string(),"abc".to_string()); assert_eq!(Box::new(Point{x:34}),Box::new(Point{x:34})); assert_eq!(&Point{x:34},&Point{x:34}); }
identifier_body
assert-eq-macro-success.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[derive(PartialEq, Debug)] struct Point { x : int } pub fn
() { assert_eq!(14,14); assert_eq!("abc".to_string(),"abc".to_string()); assert_eq!(Box::new(Point{x:34}),Box::new(Point{x:34})); assert_eq!(&Point{x:34},&Point{x:34}); }
main
identifier_name
lib.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing,
//! Rust runtime library for the Apache Thrift RPC system. //! //! This crate implements the components required to build a working //! Thrift server and client. It is divided into the following modules: //! //! 1. errors //! 2. protocol //! 3. transport //! 4. server //! 5. autogen //! //! The modules are layered as shown in the diagram below. The `autogen'd` //! layer is generated by the Thrift compiler's Rust plugin. It uses the //! types and functions defined in this crate to serialize and deserialize //! messages and implement RPC. Users interact with these types and services //! by writing their own code that uses the auto-generated clients and //! servers. //! //! ```text //! +-----------+ //! | user app | //! +-----------+ //! | autogen'd | (uses errors, autogen) //! +-----------+ //! | protocol | //! +-----------+ //! | transport | //! +-----------+ //! ``` //! //! # Tutorial //! //! For an example of how to setup a simple client and server using this crate //! see the [tutorial]. //! //! [tutorial]: https://github.com/apache/thrift/tree/master/tutorial/rs #![crate_type = "lib"] #![doc(test(attr(allow(unused_variables), deny(warnings))))] #![deny(bare_trait_objects)] // NOTE: this macro has to be defined before any modules. See: // https://danielkeep.github.io/quick-intro-to-macros.html#some-more-gotchas /// Assert that an expression returning a `Result` is a success. If it is, /// return the value contained in the result, i.e. `expr.unwrap()`. #[cfg(test)] macro_rules! assert_success { ($e: expr) => {{ let res = $e; assert!(res.is_ok()); res.unwrap() }}; } pub mod protocol; pub mod server; pub mod transport; mod errors; pub use crate::errors::*; mod autogen; pub use crate::autogen::*; /// Result type returned by all runtime library functions. /// /// As is convention this is a typedef of `std::result::Result` /// with `E` defined as the `thrift::Error` type. pub type Result<T> = std::result::Result<T, self::Error>; // Re-export ordered-float, since it is used by the generator // FIXME: check the guidance around type reexports pub use ordered_float::OrderedFloat;
// 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.
random_line_split
keystore.rs
#![allow(non_snake_case)] use serde_json::{self, Value}; use request::Handler; use error::ConsulResult; use std::error::Error; pub struct Keystore{ handler: Handler } impl Keystore { pub fn new(address: &str) -> Keystore { Keystore { handler: Handler::new(&format!("{}/v1/kv", address)) } } pub fn
(&self, key: String, value: String) -> ConsulResult<()> { self.handler.put(&key, value, Some("application/json"))?; Ok(()) } pub fn acquire_lock(&self, key: String, address: String, session_id: &String) -> ConsulResult<bool> { let uri = format!("{}?acquire={}", key, session_id); let result = self.handler.put(&uri, address, Some("application/json"))?; if result == "true" { Ok(true) } else { Ok(false) } } pub fn release_lock(&self, key: String, address: &str, session_id: &String) -> ConsulResult<bool> { let uri = format!("{}?release={}", key, session_id); let result = self.handler.put(&uri, address.to_owned(), Some("application/json"))?; if result == "true" { Ok(true) } else { Ok(false) } } pub fn get_key(&self, key: String) -> ConsulResult<Option<String>> { let result = self.handler.get(&key)?; let json_data: Value = serde_json::from_str(&result) .map_err(|e| e.description().to_owned())?; let v_json = json_data.as_array().unwrap(); Ok(super::get_string(&v_json[0], &["Value"])) } pub fn delete_key(&self, key: String) { self.handler.delete(&key).unwrap(); } }
set_key
identifier_name