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
state.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::async_client::JsonRpcResponse; #[derive(Debug, Clone, PartialEq, PartialOrd)] pub struct State { pub chain_id: u8, pub version: u64, pub timestamp_usecs: u64, } impl State { pub fn from_response(resp: &JsonRpcResponse) -> Self { Self { chain_id: resp.diem_chain_id, version: resp.diem_ledger_version, timestamp_usecs: resp.diem_ledger_timestampusec, } } } pub struct
{ last_known_state: std::sync::RwLock<Option<State>>, } impl Default for StateManager { fn default() -> Self { Self { last_known_state: std::sync::RwLock::new(None), } } } impl StateManager { pub fn new() -> Self { Self::default() } pub fn last_known_state(&self) -> Option<State> { let data = self.last_known_state.read().unwrap(); data.clone() } pub fn update_state(&self, resp_state: State) -> bool { let mut state_writer = self.last_known_state.write().unwrap(); if let Some(state) = &*state_writer { if &resp_state < state { return false; } } *state_writer = Some(resp_state); true } }
StateManager
identifier_name
decf.rs
//! formatter for %g %G decimal subs use super::super::format_field::FormatField; use super::super::formatter::{InPrefix, FormatPrimitive, Formatter}; use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common}; fn get_len_fprim(fprim: &FormatPrimitive) -> usize { let mut len = 0; if let Some(ref s) = fprim.prefix { len += s.len(); } if let Some(ref s) = fprim.pre_decimal { len += s.len(); } if let Some(ref s) = fprim.post_decimal { len += s.len(); } if let Some(ref s) = fprim.suffix { len += s.len(); } len } pub struct Decf { as_num: f64, } impl Decf { pub fn new() -> Decf { Decf { as_num: 0.0 } } } impl Formatter for Decf { fn get_primitive(&self, field: &FormatField, inprefix: &InPrefix, str_in: &str) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; // default to scif interp. so as to not truncate input vals // (that would be displayed in scif) based on relation to decimal place let analysis = FloatAnalysis::analyze(str_in, inprefix, Some(second_field as usize + 1), None, false); let mut f_sci = get_primitive_dec(inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, Some(*field.field_char == 'G')); // strip trailing zeroes match f_sci.post_decimal.clone() { Some(ref post_dec) => { let mut i = post_dec.len(); { let mut it = post_dec.chars(); while let Some(c) = it.next_back() { if c!= '0' { break; } i -= 1; } } if i!= post_dec.len() { f_sci.post_decimal = Some(String::from(&post_dec[0..i])); } } None => {} } let f_fl = get_primitive_dec(inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, None); Some(if get_len_fprim(&f_fl) >= get_len_fprim(&f_sci) { f_sci } else { f_fl }) } fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String
}
{ primitive_to_str_common(prim, &field) }
identifier_body
decf.rs
//! formatter for %g %G decimal subs use super::super::format_field::FormatField; use super::super::formatter::{InPrefix, FormatPrimitive, Formatter}; use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common}; fn get_len_fprim(fprim: &FormatPrimitive) -> usize { let mut len = 0; if let Some(ref s) = fprim.prefix { len += s.len(); } if let Some(ref s) = fprim.pre_decimal { len += s.len(); } if let Some(ref s) = fprim.post_decimal { len += s.len(); } if let Some(ref s) = fprim.suffix { len += s.len(); } len } pub struct Decf { as_num: f64, } impl Decf { pub fn
() -> Decf { Decf { as_num: 0.0 } } } impl Formatter for Decf { fn get_primitive(&self, field: &FormatField, inprefix: &InPrefix, str_in: &str) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; // default to scif interp. so as to not truncate input vals // (that would be displayed in scif) based on relation to decimal place let analysis = FloatAnalysis::analyze(str_in, inprefix, Some(second_field as usize + 1), None, false); let mut f_sci = get_primitive_dec(inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, Some(*field.field_char == 'G')); // strip trailing zeroes match f_sci.post_decimal.clone() { Some(ref post_dec) => { let mut i = post_dec.len(); { let mut it = post_dec.chars(); while let Some(c) = it.next_back() { if c!= '0' { break; } i -= 1; } } if i!= post_dec.len() { f_sci.post_decimal = Some(String::from(&post_dec[0..i])); } } None => {} } let f_fl = get_primitive_dec(inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, None); Some(if get_len_fprim(&f_fl) >= get_len_fprim(&f_sci) { f_sci } else { f_fl }) } fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String { primitive_to_str_common(prim, &field) } }
new
identifier_name
decf.rs
//! formatter for %g %G decimal subs use super::super::format_field::FormatField; use super::super::formatter::{InPrefix, FormatPrimitive, Formatter}; use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common}; fn get_len_fprim(fprim: &FormatPrimitive) -> usize { let mut len = 0; if let Some(ref s) = fprim.prefix { len += s.len(); } if let Some(ref s) = fprim.pre_decimal { len += s.len(); } if let Some(ref s) = fprim.post_decimal { len += s.len(); } if let Some(ref s) = fprim.suffix { len += s.len(); } len } pub struct Decf { as_num: f64, } impl Decf { pub fn new() -> Decf { Decf { as_num: 0.0 } } } impl Formatter for Decf { fn get_primitive(&self, field: &FormatField, inprefix: &InPrefix, str_in: &str) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; // default to scif interp. so as to not truncate input vals // (that would be displayed in scif) based on relation to decimal place let analysis = FloatAnalysis::analyze(str_in, inprefix, Some(second_field as usize + 1), None, false); let mut f_sci = get_primitive_dec(inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, Some(*field.field_char == 'G')); // strip trailing zeroes match f_sci.post_decimal.clone() { Some(ref post_dec) => { let mut i = post_dec.len(); { let mut it = post_dec.chars(); while let Some(c) = it.next_back() { if c!= '0' { break; } i -= 1; } } if i!= post_dec.len() { f_sci.post_decimal = Some(String::from(&post_dec[0..i])); } } None => {} } let f_fl = get_primitive_dec(inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, None); Some(if get_len_fprim(&f_fl) >= get_len_fprim(&f_sci) { f_sci } else
) } fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String { primitive_to_str_common(prim, &field) } }
{ f_fl }
conditional_block
decf.rs
//! formatter for %g %G decimal subs use super::super::format_field::FormatField; use super::super::formatter::{InPrefix, FormatPrimitive, Formatter}; use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common}; fn get_len_fprim(fprim: &FormatPrimitive) -> usize { let mut len = 0; if let Some(ref s) = fprim.prefix { len += s.len(); } if let Some(ref s) = fprim.pre_decimal { len += s.len(); } if let Some(ref s) = fprim.post_decimal { len += s.len(); } if let Some(ref s) = fprim.suffix { len += s.len(); } len } pub struct Decf { as_num: f64, } impl Decf { pub fn new() -> Decf { Decf { as_num: 0.0 } }
} impl Formatter for Decf { fn get_primitive(&self, field: &FormatField, inprefix: &InPrefix, str_in: &str) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; // default to scif interp. so as to not truncate input vals // (that would be displayed in scif) based on relation to decimal place let analysis = FloatAnalysis::analyze(str_in, inprefix, Some(second_field as usize + 1), None, false); let mut f_sci = get_primitive_dec(inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, Some(*field.field_char == 'G')); // strip trailing zeroes match f_sci.post_decimal.clone() { Some(ref post_dec) => { let mut i = post_dec.len(); { let mut it = post_dec.chars(); while let Some(c) = it.next_back() { if c!= '0' { break; } i -= 1; } } if i!= post_dec.len() { f_sci.post_decimal = Some(String::from(&post_dec[0..i])); } } None => {} } let f_fl = get_primitive_dec(inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, None); Some(if get_len_fprim(&f_fl) >= get_len_fprim(&f_sci) { f_sci } else { f_fl }) } fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String { primitive_to_str_common(prim, &field) } }
random_line_split
area_frame_allocator.rs
use memory::{Frame, FrameAllocator}; use multiboot2::{MemoryAreaIter, MemoryArea}; pub struct AreaFrameAllocator { next_free_frame: Frame, current_area: Option<&'static MemoryArea>, areas: MemoryAreaIter, kernel_start: Frame, kernel_end: Frame, multiboot_start: Frame, multiboot_end: Frame, } impl AreaFrameAllocator { pub fn new(kernel_start: usize, kernel_end: usize, multiboot_start: usize, multiboot_end: usize, memory_areas: MemoryAreaIter) -> AreaFrameAllocator { let mut allocator = AreaFrameAllocator { next_free_frame: Frame::containing_address(0), current_area: None, areas: memory_areas, kernel_start: Frame::containing_address(kernel_start), kernel_end: Frame::containing_address(kernel_end), multiboot_start: Frame::containing_address(multiboot_start), multiboot_end: Frame::containing_address(multiboot_end), }; allocator.jump_to_next_area(); allocator } fn jump_to_next_area(&mut self) { self.current_area = self.areas.clone().filter(|area| { let address = area.base_addr + area.length - 1; Frame::containing_address(address as usize) >= self.next_free_frame }).min_by_key(|area| area.base_addr); if let Some(area) = self.current_area { let start_frame = Frame::containing_address(area.base_addr as usize); if self.next_free_frame < start_frame { self.next_free_frame = start_frame; } } } } impl FrameAllocator for AreaFrameAllocator { fn allocate_frame(&mut self) -> Option<Frame> { if let Some(area) = self.current_area
// the frame was not valid. try to allocate again. self.allocate_frame() } else { None // no free frames left } } fn deallocate_frame(&mut self, frame: Frame) { // not implemented yet :( unimplemented!() } }
{ // if we have free frames left let frame = Frame { number: self.next_free_frame.number }; let last_frame_of_area = Frame::containing_address((area.base_addr + area.length - 1) as usize); if frame > last_frame_of_area { // we've used the current area up - jump to next area self.jump_to_next_area(); } else if frame >= self.kernel_start && frame <= self.kernel_end { // this frame is used by the kernel - jump to the frame after the kernel ends self.next_free_frame = Frame { number: self.kernel_end.number + 1}; } else if frame >= self.multiboot_start && frame <= self.multiboot_end { // this frame is used by multiboot - jump to the frame after the multiboot header self.next_free_frame = Frame { number: self.multiboot_end.number + 1}; } else { // this frame is actually free! yay! self.next_free_frame.number += 1; // bump the frame pointer by 1 return Some(frame); }
conditional_block
area_frame_allocator.rs
use memory::{Frame, FrameAllocator}; use multiboot2::{MemoryAreaIter, MemoryArea}; pub struct AreaFrameAllocator { next_free_frame: Frame, current_area: Option<&'static MemoryArea>, areas: MemoryAreaIter, kernel_start: Frame, kernel_end: Frame, multiboot_start: Frame, multiboot_end: Frame, } impl AreaFrameAllocator { pub fn new(kernel_start: usize, kernel_end: usize, multiboot_start: usize, multiboot_end: usize, memory_areas: MemoryAreaIter) -> AreaFrameAllocator { let mut allocator = AreaFrameAllocator { next_free_frame: Frame::containing_address(0), current_area: None, areas: memory_areas, kernel_start: Frame::containing_address(kernel_start), kernel_end: Frame::containing_address(kernel_end),
allocator } fn jump_to_next_area(&mut self) { self.current_area = self.areas.clone().filter(|area| { let address = area.base_addr + area.length - 1; Frame::containing_address(address as usize) >= self.next_free_frame }).min_by_key(|area| area.base_addr); if let Some(area) = self.current_area { let start_frame = Frame::containing_address(area.base_addr as usize); if self.next_free_frame < start_frame { self.next_free_frame = start_frame; } } } } impl FrameAllocator for AreaFrameAllocator { fn allocate_frame(&mut self) -> Option<Frame> { if let Some(area) = self.current_area { // if we have free frames left let frame = Frame { number: self.next_free_frame.number }; let last_frame_of_area = Frame::containing_address((area.base_addr + area.length - 1) as usize); if frame > last_frame_of_area { // we've used the current area up - jump to next area self.jump_to_next_area(); } else if frame >= self.kernel_start && frame <= self.kernel_end { // this frame is used by the kernel - jump to the frame after the kernel ends self.next_free_frame = Frame { number: self.kernel_end.number + 1}; } else if frame >= self.multiboot_start && frame <= self.multiboot_end { // this frame is used by multiboot - jump to the frame after the multiboot header self.next_free_frame = Frame { number: self.multiboot_end.number + 1}; } else { // this frame is actually free! yay! self.next_free_frame.number += 1; // bump the frame pointer by 1 return Some(frame); } // the frame was not valid. try to allocate again. self.allocate_frame() } else { None // no free frames left } } fn deallocate_frame(&mut self, frame: Frame) { // not implemented yet :( unimplemented!() } }
multiboot_start: Frame::containing_address(multiboot_start), multiboot_end: Frame::containing_address(multiboot_end), }; allocator.jump_to_next_area();
random_line_split
area_frame_allocator.rs
use memory::{Frame, FrameAllocator}; use multiboot2::{MemoryAreaIter, MemoryArea}; pub struct AreaFrameAllocator { next_free_frame: Frame, current_area: Option<&'static MemoryArea>, areas: MemoryAreaIter, kernel_start: Frame, kernel_end: Frame, multiboot_start: Frame, multiboot_end: Frame, } impl AreaFrameAllocator { pub fn new(kernel_start: usize, kernel_end: usize, multiboot_start: usize, multiboot_end: usize, memory_areas: MemoryAreaIter) -> AreaFrameAllocator { let mut allocator = AreaFrameAllocator { next_free_frame: Frame::containing_address(0), current_area: None, areas: memory_areas, kernel_start: Frame::containing_address(kernel_start), kernel_end: Frame::containing_address(kernel_end), multiboot_start: Frame::containing_address(multiboot_start), multiboot_end: Frame::containing_address(multiboot_end), }; allocator.jump_to_next_area(); allocator } fn jump_to_next_area(&mut self) { self.current_area = self.areas.clone().filter(|area| { let address = area.base_addr + area.length - 1; Frame::containing_address(address as usize) >= self.next_free_frame }).min_by_key(|area| area.base_addr); if let Some(area) = self.current_area { let start_frame = Frame::containing_address(area.base_addr as usize); if self.next_free_frame < start_frame { self.next_free_frame = start_frame; } } } } impl FrameAllocator for AreaFrameAllocator { fn allocate_frame(&mut self) -> Option<Frame> { if let Some(area) = self.current_area { // if we have free frames left let frame = Frame { number: self.next_free_frame.number }; let last_frame_of_area = Frame::containing_address((area.base_addr + area.length - 1) as usize); if frame > last_frame_of_area { // we've used the current area up - jump to next area self.jump_to_next_area(); } else if frame >= self.kernel_start && frame <= self.kernel_end { // this frame is used by the kernel - jump to the frame after the kernel ends self.next_free_frame = Frame { number: self.kernel_end.number + 1}; } else if frame >= self.multiboot_start && frame <= self.multiboot_end { // this frame is used by multiboot - jump to the frame after the multiboot header self.next_free_frame = Frame { number: self.multiboot_end.number + 1}; } else { // this frame is actually free! yay! self.next_free_frame.number += 1; // bump the frame pointer by 1 return Some(frame); } // the frame was not valid. try to allocate again. self.allocate_frame() } else { None // no free frames left } } fn deallocate_frame(&mut self, frame: Frame)
}
{ // not implemented yet :( unimplemented!() }
identifier_body
area_frame_allocator.rs
use memory::{Frame, FrameAllocator}; use multiboot2::{MemoryAreaIter, MemoryArea}; pub struct
{ next_free_frame: Frame, current_area: Option<&'static MemoryArea>, areas: MemoryAreaIter, kernel_start: Frame, kernel_end: Frame, multiboot_start: Frame, multiboot_end: Frame, } impl AreaFrameAllocator { pub fn new(kernel_start: usize, kernel_end: usize, multiboot_start: usize, multiboot_end: usize, memory_areas: MemoryAreaIter) -> AreaFrameAllocator { let mut allocator = AreaFrameAllocator { next_free_frame: Frame::containing_address(0), current_area: None, areas: memory_areas, kernel_start: Frame::containing_address(kernel_start), kernel_end: Frame::containing_address(kernel_end), multiboot_start: Frame::containing_address(multiboot_start), multiboot_end: Frame::containing_address(multiboot_end), }; allocator.jump_to_next_area(); allocator } fn jump_to_next_area(&mut self) { self.current_area = self.areas.clone().filter(|area| { let address = area.base_addr + area.length - 1; Frame::containing_address(address as usize) >= self.next_free_frame }).min_by_key(|area| area.base_addr); if let Some(area) = self.current_area { let start_frame = Frame::containing_address(area.base_addr as usize); if self.next_free_frame < start_frame { self.next_free_frame = start_frame; } } } } impl FrameAllocator for AreaFrameAllocator { fn allocate_frame(&mut self) -> Option<Frame> { if let Some(area) = self.current_area { // if we have free frames left let frame = Frame { number: self.next_free_frame.number }; let last_frame_of_area = Frame::containing_address((area.base_addr + area.length - 1) as usize); if frame > last_frame_of_area { // we've used the current area up - jump to next area self.jump_to_next_area(); } else if frame >= self.kernel_start && frame <= self.kernel_end { // this frame is used by the kernel - jump to the frame after the kernel ends self.next_free_frame = Frame { number: self.kernel_end.number + 1}; } else if frame >= self.multiboot_start && frame <= self.multiboot_end { // this frame is used by multiboot - jump to the frame after the multiboot header self.next_free_frame = Frame { number: self.multiboot_end.number + 1}; } else { // this frame is actually free! yay! self.next_free_frame.number += 1; // bump the frame pointer by 1 return Some(frame); } // the frame was not valid. try to allocate again. self.allocate_frame() } else { None // no free frames left } } fn deallocate_frame(&mut self, frame: Frame) { // not implemented yet :( unimplemented!() } }
AreaFrameAllocator
identifier_name
fmt.rs
use std::fmt; #[cfg(all(feature = "color", not(target_os = "windows")))] use ansi_term::Colour::{Red, Green, Yellow}; #[cfg(all(feature = "color", not(target_os = "windows")))] use ansi_term::ANSIString; #[allow(dead_code)] pub enum Format<T> { Error(T), Warning(T), Good(T), } #[cfg(all(feature = "color", not(target_os = "windows")))] impl<T: AsRef<str>> Format<T> { fn format(&self) -> ANSIString { match *self { Format::Error(ref e) => Red.bold().paint(e.as_ref()), Format::Warning(ref e) => Yellow.paint(e.as_ref()), Format::Good(ref e) => Green.paint(e.as_ref()), } } } #[cfg(all(feature = "color", not(target_os = "windows")))] impl<T: AsRef<str>> fmt::Display for Format<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } } #[cfg(any(not(feature = "color"), target_os = "windows"))] impl<T: fmt::Display> Format<T> { fn format(&self) -> &T { match *self { Format::Error(ref e) => e, Format::Warning(ref e) => e, Format::Good(ref e) => e, } } } #[cfg(any(not(feature = "color"), target_os = "windows"))] impl<T: fmt::Display> fmt::Display for Format<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } } pub fn format_number(n: u64, sep: Option<char>) -> String { debugln!("executing; format_number; n={}", n); let s = format!("{}", n); if let Some(sep) = sep
else { debugln!("There was not a separator"); s } }
{ debugln!("There was a separator {}", sep); let mut ins_sep = s.len() % 3; ins_sep = if ins_sep == 0 { 3 } else {ins_sep}; let mut ret = vec![]; for (i, c) in s.chars().enumerate() { debugln!("iter; c={}; ins_sep={}; ret={:?}", c, ins_sep, ret); if ins_sep == 0 && i != 0 { debugln!("Inserting the separator"); ret.push(sep); ins_sep = 3; } ret.push(c); ins_sep -= 1; } debugln!("returning; ret={}", ret.iter().cloned().collect::<String>()); ret.iter().cloned().collect() }
conditional_block
fmt.rs
use std::fmt; #[cfg(all(feature = "color", not(target_os = "windows")))] use ansi_term::Colour::{Red, Green, Yellow}; #[cfg(all(feature = "color", not(target_os = "windows")))] use ansi_term::ANSIString; #[allow(dead_code)] pub enum
<T> { Error(T), Warning(T), Good(T), } #[cfg(all(feature = "color", not(target_os = "windows")))] impl<T: AsRef<str>> Format<T> { fn format(&self) -> ANSIString { match *self { Format::Error(ref e) => Red.bold().paint(e.as_ref()), Format::Warning(ref e) => Yellow.paint(e.as_ref()), Format::Good(ref e) => Green.paint(e.as_ref()), } } } #[cfg(all(feature = "color", not(target_os = "windows")))] impl<T: AsRef<str>> fmt::Display for Format<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } } #[cfg(any(not(feature = "color"), target_os = "windows"))] impl<T: fmt::Display> Format<T> { fn format(&self) -> &T { match *self { Format::Error(ref e) => e, Format::Warning(ref e) => e, Format::Good(ref e) => e, } } } #[cfg(any(not(feature = "color"), target_os = "windows"))] impl<T: fmt::Display> fmt::Display for Format<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } } pub fn format_number(n: u64, sep: Option<char>) -> String { debugln!("executing; format_number; n={}", n); let s = format!("{}", n); if let Some(sep) = sep { debugln!("There was a separator {}", sep); let mut ins_sep = s.len() % 3; ins_sep = if ins_sep == 0 { 3 } else {ins_sep}; let mut ret = vec![]; for (i, c) in s.chars().enumerate() { debugln!("iter; c={}; ins_sep={}; ret={:?}", c, ins_sep, ret); if ins_sep == 0 && i!= 0 { debugln!("Inserting the separator"); ret.push(sep); ins_sep = 3; } ret.push(c); ins_sep -= 1; } debugln!("returning; ret={}", ret.iter().cloned().collect::<String>()); ret.iter().cloned().collect() } else { debugln!("There was not a separator"); s } }
Format
identifier_name
fmt.rs
use std::fmt; #[cfg(all(feature = "color", not(target_os = "windows")))] use ansi_term::Colour::{Red, Green, Yellow}; #[cfg(all(feature = "color", not(target_os = "windows")))] use ansi_term::ANSIString; #[allow(dead_code)] pub enum Format<T> { Error(T), Warning(T), Good(T), } #[cfg(all(feature = "color", not(target_os = "windows")))] impl<T: AsRef<str>> Format<T> { fn format(&self) -> ANSIString
} #[cfg(all(feature = "color", not(target_os = "windows")))] impl<T: AsRef<str>> fmt::Display for Format<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } } #[cfg(any(not(feature = "color"), target_os = "windows"))] impl<T: fmt::Display> Format<T> { fn format(&self) -> &T { match *self { Format::Error(ref e) => e, Format::Warning(ref e) => e, Format::Good(ref e) => e, } } } #[cfg(any(not(feature = "color"), target_os = "windows"))] impl<T: fmt::Display> fmt::Display for Format<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } } pub fn format_number(n: u64, sep: Option<char>) -> String { debugln!("executing; format_number; n={}", n); let s = format!("{}", n); if let Some(sep) = sep { debugln!("There was a separator {}", sep); let mut ins_sep = s.len() % 3; ins_sep = if ins_sep == 0 { 3 } else {ins_sep}; let mut ret = vec![]; for (i, c) in s.chars().enumerate() { debugln!("iter; c={}; ins_sep={}; ret={:?}", c, ins_sep, ret); if ins_sep == 0 && i!= 0 { debugln!("Inserting the separator"); ret.push(sep); ins_sep = 3; } ret.push(c); ins_sep -= 1; } debugln!("returning; ret={}", ret.iter().cloned().collect::<String>()); ret.iter().cloned().collect() } else { debugln!("There was not a separator"); s } }
{ match *self { Format::Error(ref e) => Red.bold().paint(e.as_ref()), Format::Warning(ref e) => Yellow.paint(e.as_ref()), Format::Good(ref e) => Green.paint(e.as_ref()), } }
identifier_body
fmt.rs
use std::fmt; #[cfg(all(feature = "color", not(target_os = "windows")))] use ansi_term::Colour::{Red, Green, Yellow}; #[cfg(all(feature = "color", not(target_os = "windows")))] use ansi_term::ANSIString; #[allow(dead_code)] pub enum Format<T> { Error(T), Warning(T), Good(T), } #[cfg(all(feature = "color", not(target_os = "windows")))] impl<T: AsRef<str>> Format<T> { fn format(&self) -> ANSIString { match *self { Format::Error(ref e) => Red.bold().paint(e.as_ref()), Format::Warning(ref e) => Yellow.paint(e.as_ref()), Format::Good(ref e) => Green.paint(e.as_ref()), } } } #[cfg(all(feature = "color", not(target_os = "windows")))] impl<T: AsRef<str>> fmt::Display for Format<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } } #[cfg(any(not(feature = "color"), target_os = "windows"))] impl<T: fmt::Display> Format<T> { fn format(&self) -> &T { match *self { Format::Error(ref e) => e, Format::Warning(ref e) => e, Format::Good(ref e) => e, } } } #[cfg(any(not(feature = "color"), target_os = "windows"))] impl<T: fmt::Display> fmt::Display for Format<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } } pub fn format_number(n: u64, sep: Option<char>) -> String { debugln!("executing; format_number; n={}", n); let s = format!("{}", n); if let Some(sep) = sep { debugln!("There was a separator {}", sep); let mut ins_sep = s.len() % 3;
debugln!("iter; c={}; ins_sep={}; ret={:?}", c, ins_sep, ret); if ins_sep == 0 && i!= 0 { debugln!("Inserting the separator"); ret.push(sep); ins_sep = 3; } ret.push(c); ins_sep -= 1; } debugln!("returning; ret={}", ret.iter().cloned().collect::<String>()); ret.iter().cloned().collect() } else { debugln!("There was not a separator"); s } }
ins_sep = if ins_sep == 0 { 3 } else {ins_sep}; let mut ret = vec![]; for (i, c) in s.chars().enumerate() {
random_line_split
lib.rs
// Copyright 2015 Hugo Duncan // // 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. #![deny(missing_docs)] #![feature(collections, core, io)] //! Austenite //! //! A library for building [Iron](https://github.com/iron/iron) //! handlers that implements HTTP header handling and content //! negotiation. //! //! ```ignore //! #[macro_use] extern crate austenite; //! use austenite::handle; //! use iron::{Iron, Listening, Request, Response}; //! //! struct GetOkContent; //! resource_handler!(GetOkContent); //! impl Resource for GetOkContent {
//! } //! } //! //! fn start_iron() -> Listening { //! Iron::new(Resource).listen((address,0u16)).unwrap(); //! } //! ``` #[macro_use] extern crate hyper; extern crate iron; extern crate mime; extern crate time; #[macro_use] extern crate log; pub use hyper_headers::*; pub use resource::{Resource, ResourceError, ResourceResult}; /// Content Negotiation pub mod content_neg; /// Headers pub mod hyper_headers; /// A Resource pub mod resource;
//! fn handle_ok(&self, req: &Request, resp: &mut Response) //! -> IronResult<Response> //! { //! resp.set_mut((status::Ok, "hello")); //! Ok(Response::new())
random_line_split
json.rs
#[derive(Debug, Deserialize)] /// A user object returned from the API pub struct User{ /// The username of the user pub username: String } #[derive(Debug, Deserialize)] /// An object containing the ID of something newly created pub struct Id<T> { /// The ID pub id: T } #[derive(Debug, Deserialize)] #[serde(rename_all = "lowercase")] /// A response that either is an error or a success pub enum HueResponse<T> { /// The result from the bridge if it didn't fail Success(T), /// The error that was returned from the bridge Error(Error) } use ::errors::HueError; impl<T> HueResponse<T> { pub fn into_result(self) -> Result<T, HueError> { match self { HueResponse::Success(s) => Ok(s), HueResponse::Error(e) => Err(e.into()), } } } #[derive(Debug, Clone, Serialize)] pub struct SceneRecall<'a> { pub scene: &'a str } #[derive(Debug, Deserialize)] /// An error object returned from the API pub struct Error { /// The URI the error happened on pub address: String, /// A short description of the error
#[serde(rename="type")] pub code: u16, }
pub description: String, /// Its errorcode
random_line_split
json.rs
#[derive(Debug, Deserialize)] /// A user object returned from the API pub struct User{ /// The username of the user pub username: String } #[derive(Debug, Deserialize)] /// An object containing the ID of something newly created pub struct Id<T> { /// The ID pub id: T } #[derive(Debug, Deserialize)] #[serde(rename_all = "lowercase")] /// A response that either is an error or a success pub enum HueResponse<T> { /// The result from the bridge if it didn't fail Success(T), /// The error that was returned from the bridge Error(Error) } use ::errors::HueError; impl<T> HueResponse<T> { pub fn into_result(self) -> Result<T, HueError> { match self { HueResponse::Success(s) => Ok(s), HueResponse::Error(e) => Err(e.into()), } } } #[derive(Debug, Clone, Serialize)] pub struct SceneRecall<'a> { pub scene: &'a str } #[derive(Debug, Deserialize)] /// An error object returned from the API pub struct
{ /// The URI the error happened on pub address: String, /// A short description of the error pub description: String, /// Its errorcode #[serde(rename="type")] pub code: u16, }
Error
identifier_name
static-impl.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. // xfail-fast pub trait plus { fn plus(&self) -> int; } mod a { use plus; impl plus for uint { fn plus(&self) -> int { *self as int + 20 } } } mod b { use plus; impl plus for ~str { fn plus(&self) -> int { 200 } } } trait uint_utils { fn str(&self) -> ~str; fn multi(&self, f: |uint|); } impl uint_utils for uint { fn
(&self) -> ~str { self.to_str() } fn multi(&self, f: |uint|) { let mut c = 0u; while c < *self { f(c); c += 1u; } } } trait vec_utils<T> { fn length_(&self, ) -> uint; fn iter_(&self, f: |&T|); fn map_<U>(&self, f: |&T| -> U) -> ~[U]; } impl<T> vec_utils<T> for ~[T] { fn length_(&self) -> uint { self.len() } fn iter_(&self, f: |&T|) { for x in self.iter() { f(x); } } fn map_<U>(&self, f: |&T| -> U) -> ~[U] { let mut r = ~[]; for elt in self.iter() { r.push(f(elt)); } r } } pub fn main() { assert_eq!(10u.plus(), 30); assert_eq!((~"hi").plus(), 200); assert_eq!((~[1]).length_().str(), ~"1"); assert_eq!((~[3, 4]).map_(|a| *a + 4 )[0], 7); assert_eq!((~[3, 4]).map_::<uint>(|a| *a as uint + 4u )[0], 7u); let mut x = 0u; 10u.multi(|_n| x += 2u ); assert_eq!(x, 20u); }
str
identifier_name
static-impl.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. // xfail-fast pub trait plus { fn plus(&self) -> int; } mod a { use plus; impl plus for uint { fn plus(&self) -> int
} } mod b { use plus; impl plus for ~str { fn plus(&self) -> int { 200 } } } trait uint_utils { fn str(&self) -> ~str; fn multi(&self, f: |uint|); } impl uint_utils for uint { fn str(&self) -> ~str { self.to_str() } fn multi(&self, f: |uint|) { let mut c = 0u; while c < *self { f(c); c += 1u; } } } trait vec_utils<T> { fn length_(&self, ) -> uint; fn iter_(&self, f: |&T|); fn map_<U>(&self, f: |&T| -> U) -> ~[U]; } impl<T> vec_utils<T> for ~[T] { fn length_(&self) -> uint { self.len() } fn iter_(&self, f: |&T|) { for x in self.iter() { f(x); } } fn map_<U>(&self, f: |&T| -> U) -> ~[U] { let mut r = ~[]; for elt in self.iter() { r.push(f(elt)); } r } } pub fn main() { assert_eq!(10u.plus(), 30); assert_eq!((~"hi").plus(), 200); assert_eq!((~[1]).length_().str(), ~"1"); assert_eq!((~[3, 4]).map_(|a| *a + 4 )[0], 7); assert_eq!((~[3, 4]).map_::<uint>(|a| *a as uint + 4u )[0], 7u); let mut x = 0u; 10u.multi(|_n| x += 2u ); assert_eq!(x, 20u); }
{ *self as int + 20 }
identifier_body
static-impl.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. // xfail-fast pub trait plus { fn plus(&self) -> int; } mod a { use plus; impl plus for uint { fn plus(&self) -> int { *self as int + 20 } } } mod b { use plus; impl plus for ~str { fn plus(&self) -> int { 200 } } } trait uint_utils { fn str(&self) -> ~str; fn multi(&self, f: |uint|); } impl uint_utils for uint { fn str(&self) -> ~str { self.to_str() } fn multi(&self, f: |uint|) { let mut c = 0u; while c < *self { f(c); c += 1u; } } } trait vec_utils<T> { fn length_(&self, ) -> uint; fn iter_(&self, f: |&T|); fn map_<U>(&self, f: |&T| -> U) -> ~[U]; } impl<T> vec_utils<T> for ~[T] { fn length_(&self) -> uint { self.len() } fn iter_(&self, f: |&T|) { for x in self.iter() { f(x); } } fn map_<U>(&self, f: |&T| -> U) -> ~[U] { let mut r = ~[]; for elt in self.iter() { r.push(f(elt)); }
assert_eq!(10u.plus(), 30); assert_eq!((~"hi").plus(), 200); assert_eq!((~[1]).length_().str(), ~"1"); assert_eq!((~[3, 4]).map_(|a| *a + 4 )[0], 7); assert_eq!((~[3, 4]).map_::<uint>(|a| *a as uint + 4u )[0], 7u); let mut x = 0u; 10u.multi(|_n| x += 2u ); assert_eq!(x, 20u); }
r } } pub fn main() {
random_line_split
render_mode.rs
use std::collections::BTreeMap; use error::{Error, ResultExt}; use types::{ CCode, CTree, Chord, ChordSpec, Field, KmapOrder, KmapPath, ModeInfo, ModeName, ToC, }; use util::usize_to_u8; pub struct ModeBuilder<'a> { pub mode_name: &'a ModeName, pub info: &'a ModeInfo, pub kmap_struct_names: &'a BTreeMap<KmapPath, CCode>, pub mod_chords: Vec<Chord<KmapOrder>>, pub anagram_mask: Chord<KmapOrder>, pub chord_spec: ChordSpec, } c_struct!( struct ModeStruct { is_gaming: bool, num_kmaps: u8, kmaps: CCode, mod_chords: CCode, anagram_mask: CCode, } ); //////////////////////////////////////////////////////////////////////////////// impl<'a> ModeBuilder<'a> { pub fn render(&self) -> Result<(CTree, CCode), Error> { let mut g = Vec::new(); let (tree, kmap_array_name, num_kmaps) = self.render_kmap_array()?; g.push(tree); let (tree, mod_array_name) = self.render_modifier_array()?; g.push(tree); let (tree, anagram_mask_name) = self.render_anagram_mask()?; g.push(tree); let mode_struct = ModeStruct { num_kmaps: usize_to_u8(num_kmaps) .context("too many kmaps in mode")?, kmaps: kmap_array_name, mod_chords: mod_array_name, anagram_mask: anagram_mask_name, is_gaming: self.info.gaming, }; let mode_struct_name = format!("{}_struct", self.mode_name).to_c(); g.push(mode_struct.render(mode_struct_name.clone())); Ok((CTree::Group(g), mode_struct_name)) } fn render_kmap_array(&self) -> Result<(CTree, CCode, usize), Error> { let mut g = Vec::new(); let array_name = format!("{}_kmaps_array", self.mode_name).to_c(); let contents: Vec<_> = self .info .keymaps .iter() .map(|info| { self.kmap_struct_names .get(&info.file) .expect("no struct name was found for kmap") .to_owned() }) .collect(); g.push(CTree::Array { name: array_name.clone(), values: CCode::map_prepend("&", &contents), c_type: "KmapStruct*".to_c(), is_extern: false, }); Ok((CTree::Group(g), array_name, contents.len())) } fn render_anagram_mask(&self) -> Result<(CTree, CCode), Error> { let array_name_out = format!("{}_anagram_mask", self.mode_name).to_c(); let tree = CTree::ConstVar { name: array_name_out.clone(), value: self .chord_spec .to_firmware(&self.anagram_mask)? .to_c_constructor(), c_type: Chord::c_type_name(), is_extern: false, }; Ok((tree, array_name_out)) } fn
(&self) -> Result<(CTree, CCode), Error> { self.render_chord_array_helper(&self.mod_chords, &"mod_chord".to_c()) } fn render_chord_array_helper( &self, chords: &[Chord<KmapOrder>], label: &CCode, ) -> Result<(CTree, CCode), Error> { // TODO share code with stuff in kmap_builder? get rid of this helper? let array_name_out = format!("{}_{}", self.mode_name, label).to_c(); let tree = CTree::Array { name: array_name_out.clone(), values: chords .iter() .map(|c| Ok(self.chord_spec.to_firmware(c)?.to_c_constructor())) .collect::<Result<Vec<CCode>, Error>>()?, c_type: Chord::c_type_name(), is_extern: false, }; Ok((tree, array_name_out)) } }
render_modifier_array
identifier_name
render_mode.rs
use std::collections::BTreeMap; use error::{Error, ResultExt}; use types::{ CCode, CTree, Chord, ChordSpec, Field, KmapOrder, KmapPath, ModeInfo, ModeName, ToC, }; use util::usize_to_u8; pub struct ModeBuilder<'a> { pub mode_name: &'a ModeName, pub info: &'a ModeInfo, pub kmap_struct_names: &'a BTreeMap<KmapPath, CCode>, pub mod_chords: Vec<Chord<KmapOrder>>, pub anagram_mask: Chord<KmapOrder>, pub chord_spec: ChordSpec, } c_struct!( struct ModeStruct { is_gaming: bool, num_kmaps: u8, kmaps: CCode, mod_chords: CCode, anagram_mask: CCode, } ); //////////////////////////////////////////////////////////////////////////////// impl<'a> ModeBuilder<'a> { pub fn render(&self) -> Result<(CTree, CCode), Error> { let mut g = Vec::new(); let (tree, kmap_array_name, num_kmaps) = self.render_kmap_array()?; g.push(tree); let (tree, mod_array_name) = self.render_modifier_array()?; g.push(tree); let (tree, anagram_mask_name) = self.render_anagram_mask()?; g.push(tree); let mode_struct = ModeStruct { num_kmaps: usize_to_u8(num_kmaps) .context("too many kmaps in mode")?, kmaps: kmap_array_name, mod_chords: mod_array_name, anagram_mask: anagram_mask_name, is_gaming: self.info.gaming, }; let mode_struct_name = format!("{}_struct", self.mode_name).to_c(); g.push(mode_struct.render(mode_struct_name.clone())); Ok((CTree::Group(g), mode_struct_name)) } fn render_kmap_array(&self) -> Result<(CTree, CCode, usize), Error> { let mut g = Vec::new(); let array_name = format!("{}_kmaps_array", self.mode_name).to_c(); let contents: Vec<_> = self .info .keymaps .iter() .map(|info| { self.kmap_struct_names .get(&info.file) .expect("no struct name was found for kmap") .to_owned() }) .collect(); g.push(CTree::Array { name: array_name.clone(), values: CCode::map_prepend("&", &contents), c_type: "KmapStruct*".to_c(), is_extern: false, }); Ok((CTree::Group(g), array_name, contents.len())) } fn render_anagram_mask(&self) -> Result<(CTree, CCode), Error> { let array_name_out = format!("{}_anagram_mask", self.mode_name).to_c(); let tree = CTree::ConstVar { name: array_name_out.clone(), value: self .chord_spec .to_firmware(&self.anagram_mask)? .to_c_constructor(), c_type: Chord::c_type_name(), is_extern: false, }; Ok((tree, array_name_out)) }
fn render_modifier_array(&self) -> Result<(CTree, CCode), Error> { self.render_chord_array_helper(&self.mod_chords, &"mod_chord".to_c()) } fn render_chord_array_helper( &self, chords: &[Chord<KmapOrder>], label: &CCode, ) -> Result<(CTree, CCode), Error> { // TODO share code with stuff in kmap_builder? get rid of this helper? let array_name_out = format!("{}_{}", self.mode_name, label).to_c(); let tree = CTree::Array { name: array_name_out.clone(), values: chords .iter() .map(|c| Ok(self.chord_spec.to_firmware(c)?.to_c_constructor())) .collect::<Result<Vec<CCode>, Error>>()?, c_type: Chord::c_type_name(), is_extern: false, }; Ok((tree, array_name_out)) } }
random_line_split
render_mode.rs
use std::collections::BTreeMap; use error::{Error, ResultExt}; use types::{ CCode, CTree, Chord, ChordSpec, Field, KmapOrder, KmapPath, ModeInfo, ModeName, ToC, }; use util::usize_to_u8; pub struct ModeBuilder<'a> { pub mode_name: &'a ModeName, pub info: &'a ModeInfo, pub kmap_struct_names: &'a BTreeMap<KmapPath, CCode>, pub mod_chords: Vec<Chord<KmapOrder>>, pub anagram_mask: Chord<KmapOrder>, pub chord_spec: ChordSpec, } c_struct!( struct ModeStruct { is_gaming: bool, num_kmaps: u8, kmaps: CCode, mod_chords: CCode, anagram_mask: CCode, } ); //////////////////////////////////////////////////////////////////////////////// impl<'a> ModeBuilder<'a> { pub fn render(&self) -> Result<(CTree, CCode), Error> { let mut g = Vec::new(); let (tree, kmap_array_name, num_kmaps) = self.render_kmap_array()?; g.push(tree); let (tree, mod_array_name) = self.render_modifier_array()?; g.push(tree); let (tree, anagram_mask_name) = self.render_anagram_mask()?; g.push(tree); let mode_struct = ModeStruct { num_kmaps: usize_to_u8(num_kmaps) .context("too many kmaps in mode")?, kmaps: kmap_array_name, mod_chords: mod_array_name, anagram_mask: anagram_mask_name, is_gaming: self.info.gaming, }; let mode_struct_name = format!("{}_struct", self.mode_name).to_c(); g.push(mode_struct.render(mode_struct_name.clone())); Ok((CTree::Group(g), mode_struct_name)) } fn render_kmap_array(&self) -> Result<(CTree, CCode, usize), Error>
c_type: "KmapStruct*".to_c(), is_extern: false, }); Ok((CTree::Group(g), array_name, contents.len())) } fn render_anagram_mask(&self) -> Result<(CTree, CCode), Error> { let array_name_out = format!("{}_anagram_mask", self.mode_name).to_c(); let tree = CTree::ConstVar { name: array_name_out.clone(), value: self .chord_spec .to_firmware(&self.anagram_mask)? .to_c_constructor(), c_type: Chord::c_type_name(), is_extern: false, }; Ok((tree, array_name_out)) } fn render_modifier_array(&self) -> Result<(CTree, CCode), Error> { self.render_chord_array_helper(&self.mod_chords, &"mod_chord".to_c()) } fn render_chord_array_helper( &self, chords: &[Chord<KmapOrder>], label: &CCode, ) -> Result<(CTree, CCode), Error> { // TODO share code with stuff in kmap_builder? get rid of this helper? let array_name_out = format!("{}_{}", self.mode_name, label).to_c(); let tree = CTree::Array { name: array_name_out.clone(), values: chords .iter() .map(|c| Ok(self.chord_spec.to_firmware(c)?.to_c_constructor())) .collect::<Result<Vec<CCode>, Error>>()?, c_type: Chord::c_type_name(), is_extern: false, }; Ok((tree, array_name_out)) } }
{ let mut g = Vec::new(); let array_name = format!("{}_kmaps_array", self.mode_name).to_c(); let contents: Vec<_> = self .info .keymaps .iter() .map(|info| { self.kmap_struct_names .get(&info.file) .expect("no struct name was found for kmap") .to_owned() }) .collect(); g.push(CTree::Array { name: array_name.clone(), values: CCode::map_prepend("&", &contents),
identifier_body
simple.rs
use std::collections::HashMap; use unshare::{Command, Fd}; use crate::config::command::{CommandInfo, WriteMode}; use crate::launcher::{Context, socket}; use crate::launcher::options::{ArgError, parse_docopts}; use crate::launcher::volumes::prepare_volumes; use crate::process_util::{run_and_wait, convert_status}; use super::build::{build_container}; use super::network; use super::wrap::Wrapper; const DEFAULT_DOCOPT: &'static str = "\ Common options: -h, --help This help "; pub type Version = String; pub struct Args { cmdname: String, args: Vec<String>, environ: HashMap<String, String>, } pub fn
(cinfo: &CommandInfo, _context: &Context, cmd: String, args: Vec<String>) -> Result<Args, ArgError> { if let Some(_) = cinfo.network { return Err(ArgError::Error(format!( "Network is not supported for!Command use!Supervise"))); } if let Some(ref opttext) = cinfo.options { let (env, _) = parse_docopts(&cinfo.description, opttext, DEFAULT_DOCOPT, &cmd, args)?; Ok(Args { cmdname: cmd, environ: env, args: Vec::new(), }) } else { Ok(Args { cmdname: cmd, environ: HashMap::new(), args: args, }) } } pub fn prepare_containers(cinfo: &CommandInfo, _: &Args, context: &Context) -> Result<Version, String> { let ver = build_container(context, &cinfo.container, context.build_mode, false)?; let cont = context.config.containers.get(&cinfo.container) .ok_or_else(|| format!("Container {:?} not found", cinfo.container))?; prepare_volumes(cont.volumes.values(), context)?; prepare_volumes(cinfo.volumes.values(), context)?; return Ok(ver); } pub fn run(cinfo: &CommandInfo, args: Args, version: Version, context: &Context) -> Result<i32, String> { if cinfo.isolate_network || context.isolate_network { try_msg!(network::isolate_network(), "Cannot setup isolated network: {err}"); } let mut cmd: Command = Wrapper::new(Some(&version), &context.settings); cmd.workdir(&context.workdir); for (k, v) in &args.environ { cmd.env(k, v); } cmd.arg(&args.cmdname); cmd.args(&args.args); if let Some(ref sock_str) = cinfo.pass_tcp_socket { let sock = socket::parse_and_bind(sock_str) .map_err(|e| format!("Error listening {:?}: {}", sock_str, e))?; cmd.file_descriptor(3, Fd::from_file(sock)); } if cinfo.network.is_none() { // TODO(tailhook) is it still a thing? cmd.map_users_for( &context.config.get_container(&cinfo.container).unwrap(), &context.settings)?; cmd.gid(0); cmd.groups(Vec::new()); } let res = run_and_wait(&mut cmd).map(convert_status); if cinfo.write_mode!= WriteMode::read_only { let mut cmd: Command = Wrapper::new(None, &context.settings); cmd.workdir(&context.workdir); cmd.max_uidmap(); cmd.gid(0); cmd.groups(Vec::new()); cmd.arg("_clean").arg("--transient"); match cmd.status() { Ok(s) if s.success() => {} Ok(s) => warn!("The `vagga _clean --transient` {}", s), Err(e) => warn!("Failed to run `vagga _clean --transient`: {}", e), } } if res == Ok(0) { if let Some(ref epilog) = cinfo.epilog { print!("{}", epilog); } } return res; }
parse_args
identifier_name
simple.rs
use std::collections::HashMap; use unshare::{Command, Fd}; use crate::config::command::{CommandInfo, WriteMode}; use crate::launcher::{Context, socket}; use crate::launcher::options::{ArgError, parse_docopts}; use crate::launcher::volumes::prepare_volumes; use crate::process_util::{run_and_wait, convert_status}; use super::build::{build_container}; use super::network; use super::wrap::Wrapper; const DEFAULT_DOCOPT: &'static str = "\ Common options: -h, --help This help "; pub type Version = String; pub struct Args {
environ: HashMap<String, String>, } pub fn parse_args(cinfo: &CommandInfo, _context: &Context, cmd: String, args: Vec<String>) -> Result<Args, ArgError> { if let Some(_) = cinfo.network { return Err(ArgError::Error(format!( "Network is not supported for!Command use!Supervise"))); } if let Some(ref opttext) = cinfo.options { let (env, _) = parse_docopts(&cinfo.description, opttext, DEFAULT_DOCOPT, &cmd, args)?; Ok(Args { cmdname: cmd, environ: env, args: Vec::new(), }) } else { Ok(Args { cmdname: cmd, environ: HashMap::new(), args: args, }) } } pub fn prepare_containers(cinfo: &CommandInfo, _: &Args, context: &Context) -> Result<Version, String> { let ver = build_container(context, &cinfo.container, context.build_mode, false)?; let cont = context.config.containers.get(&cinfo.container) .ok_or_else(|| format!("Container {:?} not found", cinfo.container))?; prepare_volumes(cont.volumes.values(), context)?; prepare_volumes(cinfo.volumes.values(), context)?; return Ok(ver); } pub fn run(cinfo: &CommandInfo, args: Args, version: Version, context: &Context) -> Result<i32, String> { if cinfo.isolate_network || context.isolate_network { try_msg!(network::isolate_network(), "Cannot setup isolated network: {err}"); } let mut cmd: Command = Wrapper::new(Some(&version), &context.settings); cmd.workdir(&context.workdir); for (k, v) in &args.environ { cmd.env(k, v); } cmd.arg(&args.cmdname); cmd.args(&args.args); if let Some(ref sock_str) = cinfo.pass_tcp_socket { let sock = socket::parse_and_bind(sock_str) .map_err(|e| format!("Error listening {:?}: {}", sock_str, e))?; cmd.file_descriptor(3, Fd::from_file(sock)); } if cinfo.network.is_none() { // TODO(tailhook) is it still a thing? cmd.map_users_for( &context.config.get_container(&cinfo.container).unwrap(), &context.settings)?; cmd.gid(0); cmd.groups(Vec::new()); } let res = run_and_wait(&mut cmd).map(convert_status); if cinfo.write_mode!= WriteMode::read_only { let mut cmd: Command = Wrapper::new(None, &context.settings); cmd.workdir(&context.workdir); cmd.max_uidmap(); cmd.gid(0); cmd.groups(Vec::new()); cmd.arg("_clean").arg("--transient"); match cmd.status() { Ok(s) if s.success() => {} Ok(s) => warn!("The `vagga _clean --transient` {}", s), Err(e) => warn!("Failed to run `vagga _clean --transient`: {}", e), } } if res == Ok(0) { if let Some(ref epilog) = cinfo.epilog { print!("{}", epilog); } } return res; }
cmdname: String, args: Vec<String>,
random_line_split
simple.rs
use std::collections::HashMap; use unshare::{Command, Fd}; use crate::config::command::{CommandInfo, WriteMode}; use crate::launcher::{Context, socket}; use crate::launcher::options::{ArgError, parse_docopts}; use crate::launcher::volumes::prepare_volumes; use crate::process_util::{run_and_wait, convert_status}; use super::build::{build_container}; use super::network; use super::wrap::Wrapper; const DEFAULT_DOCOPT: &'static str = "\ Common options: -h, --help This help "; pub type Version = String; pub struct Args { cmdname: String, args: Vec<String>, environ: HashMap<String, String>, } pub fn parse_args(cinfo: &CommandInfo, _context: &Context, cmd: String, args: Vec<String>) -> Result<Args, ArgError>
} } pub fn prepare_containers(cinfo: &CommandInfo, _: &Args, context: &Context) -> Result<Version, String> { let ver = build_container(context, &cinfo.container, context.build_mode, false)?; let cont = context.config.containers.get(&cinfo.container) .ok_or_else(|| format!("Container {:?} not found", cinfo.container))?; prepare_volumes(cont.volumes.values(), context)?; prepare_volumes(cinfo.volumes.values(), context)?; return Ok(ver); } pub fn run(cinfo: &CommandInfo, args: Args, version: Version, context: &Context) -> Result<i32, String> { if cinfo.isolate_network || context.isolate_network { try_msg!(network::isolate_network(), "Cannot setup isolated network: {err}"); } let mut cmd: Command = Wrapper::new(Some(&version), &context.settings); cmd.workdir(&context.workdir); for (k, v) in &args.environ { cmd.env(k, v); } cmd.arg(&args.cmdname); cmd.args(&args.args); if let Some(ref sock_str) = cinfo.pass_tcp_socket { let sock = socket::parse_and_bind(sock_str) .map_err(|e| format!("Error listening {:?}: {}", sock_str, e))?; cmd.file_descriptor(3, Fd::from_file(sock)); } if cinfo.network.is_none() { // TODO(tailhook) is it still a thing? cmd.map_users_for( &context.config.get_container(&cinfo.container).unwrap(), &context.settings)?; cmd.gid(0); cmd.groups(Vec::new()); } let res = run_and_wait(&mut cmd).map(convert_status); if cinfo.write_mode!= WriteMode::read_only { let mut cmd: Command = Wrapper::new(None, &context.settings); cmd.workdir(&context.workdir); cmd.max_uidmap(); cmd.gid(0); cmd.groups(Vec::new()); cmd.arg("_clean").arg("--transient"); match cmd.status() { Ok(s) if s.success() => {} Ok(s) => warn!("The `vagga _clean --transient` {}", s), Err(e) => warn!("Failed to run `vagga _clean --transient`: {}", e), } } if res == Ok(0) { if let Some(ref epilog) = cinfo.epilog { print!("{}", epilog); } } return res; }
{ if let Some(_) = cinfo.network { return Err(ArgError::Error(format!( "Network is not supported for !Command use !Supervise"))); } if let Some(ref opttext) = cinfo.options { let (env, _) = parse_docopts(&cinfo.description, opttext, DEFAULT_DOCOPT, &cmd, args)?; Ok(Args { cmdname: cmd, environ: env, args: Vec::new(), }) } else { Ok(Args { cmdname: cmd, environ: HashMap::new(), args: args, })
identifier_body
simple.rs
use std::collections::HashMap; use unshare::{Command, Fd}; use crate::config::command::{CommandInfo, WriteMode}; use crate::launcher::{Context, socket}; use crate::launcher::options::{ArgError, parse_docopts}; use crate::launcher::volumes::prepare_volumes; use crate::process_util::{run_and_wait, convert_status}; use super::build::{build_container}; use super::network; use super::wrap::Wrapper; const DEFAULT_DOCOPT: &'static str = "\ Common options: -h, --help This help "; pub type Version = String; pub struct Args { cmdname: String, args: Vec<String>, environ: HashMap<String, String>, } pub fn parse_args(cinfo: &CommandInfo, _context: &Context, cmd: String, args: Vec<String>) -> Result<Args, ArgError> { if let Some(_) = cinfo.network { return Err(ArgError::Error(format!( "Network is not supported for!Command use!Supervise"))); } if let Some(ref opttext) = cinfo.options { let (env, _) = parse_docopts(&cinfo.description, opttext, DEFAULT_DOCOPT, &cmd, args)?; Ok(Args { cmdname: cmd, environ: env, args: Vec::new(), }) } else { Ok(Args { cmdname: cmd, environ: HashMap::new(), args: args, }) } } pub fn prepare_containers(cinfo: &CommandInfo, _: &Args, context: &Context) -> Result<Version, String> { let ver = build_container(context, &cinfo.container, context.build_mode, false)?; let cont = context.config.containers.get(&cinfo.container) .ok_or_else(|| format!("Container {:?} not found", cinfo.container))?; prepare_volumes(cont.volumes.values(), context)?; prepare_volumes(cinfo.volumes.values(), context)?; return Ok(ver); } pub fn run(cinfo: &CommandInfo, args: Args, version: Version, context: &Context) -> Result<i32, String> { if cinfo.isolate_network || context.isolate_network { try_msg!(network::isolate_network(), "Cannot setup isolated network: {err}"); } let mut cmd: Command = Wrapper::new(Some(&version), &context.settings); cmd.workdir(&context.workdir); for (k, v) in &args.environ { cmd.env(k, v); } cmd.arg(&args.cmdname); cmd.args(&args.args); if let Some(ref sock_str) = cinfo.pass_tcp_socket { let sock = socket::parse_and_bind(sock_str) .map_err(|e| format!("Error listening {:?}: {}", sock_str, e))?; cmd.file_descriptor(3, Fd::from_file(sock)); } if cinfo.network.is_none() { // TODO(tailhook) is it still a thing? cmd.map_users_for( &context.config.get_container(&cinfo.container).unwrap(), &context.settings)?; cmd.gid(0); cmd.groups(Vec::new()); } let res = run_and_wait(&mut cmd).map(convert_status); if cinfo.write_mode!= WriteMode::read_only { let mut cmd: Command = Wrapper::new(None, &context.settings); cmd.workdir(&context.workdir); cmd.max_uidmap(); cmd.gid(0); cmd.groups(Vec::new()); cmd.arg("_clean").arg("--transient"); match cmd.status() { Ok(s) if s.success() => {} Ok(s) => warn!("The `vagga _clean --transient` {}", s), Err(e) => warn!("Failed to run `vagga _clean --transient`: {}", e), } } if res == Ok(0) { if let Some(ref epilog) = cinfo.epilog
} return res; }
{ print!("{}", epilog); }
conditional_block
background.rs
use std::rc::Rc; use glium::{Program, Display, VertexBuffer, Surface}; use glium::texture::Texture2d; use glium::framebuffer::SimpleFrameBuffer; use glium::index::NoIndices; use glium::index::PrimitiveType::TriangleStrip; use ffmpeg::frame; use renderer::{Render, Support}; use renderer::background::{Video, Visualizer}; use game; #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 2], texture: [f32; 2], } implement_vertex!(Vertex, position, texture); pub struct Background<'a> { display: &'a Display, video: Video<'a>, visualizer: Visualizer<'a>, program: Program, vertices: VertexBuffer<Vertex>, texture: Rc<Texture2d>, } impl<'a> Background<'a>{ pub fn new<'b>(display: &'b Display) -> Background<'b> { Background { display: display, video: Video::new(display), visualizer: Visualizer::new(display), program: program!(display, 100 => { vertex: " #version 100 precision lowp float; attribute vec2 position; attribute vec2 texture; varying vec2 v_texture; void main() { gl_Position = vec4(position, 0.0, 1.0); v_texture = texture; } ", fragment: " #version 100 precision lowp float; uniform sampler2D tex; varying vec2 v_texture; void main() { gl_FragColor = texture2D(tex, v_texture); } ", }, ).unwrap(), vertices: VertexBuffer::new(display, &[ Vertex { position: [-1.0, 1.0], texture: [0.0, 1.0] }, Vertex { position: [ 1.0, 1.0], texture: [1.0, 1.0] }, Vertex { position: [-1.0, -1.0], texture: [0.0, 0.0] }, Vertex { position: [ 1.0, -1.0], texture: [1.0, 0.0] }, ]).unwrap(), texture: Rc::new(Texture2d::empty(display, 1, 1).unwrap()), } } pub fn resize(&mut self, width: u32, height: u32) { self.texture = Rc::new(Texture2d::empty(self.display, width, height).unwrap()); } pub fn render<S: Surface>(&mut self, target: &mut S, support: &Support, state: &game::State, frame: Option<&frame::Video>) { // render video or visualizer to the internal texture { let mut surface = SimpleFrameBuffer::new(self.display, &*self.texture).unwrap(); if let Some(frame) = frame { self.video.render(&mut surface, support, frame); } else { self.visualizer.render(&mut surface, support, state); } } // draw the internal texture to video let uniforms = uniform! { tex: &*self.texture, }; target.draw(&self.vertices, &NoIndices(TriangleStrip), &self.program, &uniforms, &Default::default()).unwrap(); } pub fn texture(&self) -> Rc<Texture2d>
}
{ self.texture.clone() }
identifier_body
background.rs
use std::rc::Rc; use glium::{Program, Display, VertexBuffer, Surface}; use glium::texture::Texture2d; use glium::framebuffer::SimpleFrameBuffer; use glium::index::NoIndices; use glium::index::PrimitiveType::TriangleStrip; use ffmpeg::frame; use renderer::{Render, Support}; use renderer::background::{Video, Visualizer}; use game; #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 2], texture: [f32; 2], } implement_vertex!(Vertex, position, texture); pub struct Background<'a> { display: &'a Display, video: Video<'a>, visualizer: Visualizer<'a>, program: Program, vertices: VertexBuffer<Vertex>, texture: Rc<Texture2d>, } impl<'a> Background<'a>{ pub fn
<'b>(display: &'b Display) -> Background<'b> { Background { display: display, video: Video::new(display), visualizer: Visualizer::new(display), program: program!(display, 100 => { vertex: " #version 100 precision lowp float; attribute vec2 position; attribute vec2 texture; varying vec2 v_texture; void main() { gl_Position = vec4(position, 0.0, 1.0); v_texture = texture; } ", fragment: " #version 100 precision lowp float; uniform sampler2D tex; varying vec2 v_texture; void main() { gl_FragColor = texture2D(tex, v_texture); } ", }, ).unwrap(), vertices: VertexBuffer::new(display, &[ Vertex { position: [-1.0, 1.0], texture: [0.0, 1.0] }, Vertex { position: [ 1.0, 1.0], texture: [1.0, 1.0] }, Vertex { position: [-1.0, -1.0], texture: [0.0, 0.0] }, Vertex { position: [ 1.0, -1.0], texture: [1.0, 0.0] }, ]).unwrap(), texture: Rc::new(Texture2d::empty(display, 1, 1).unwrap()), } } pub fn resize(&mut self, width: u32, height: u32) { self.texture = Rc::new(Texture2d::empty(self.display, width, height).unwrap()); } pub fn render<S: Surface>(&mut self, target: &mut S, support: &Support, state: &game::State, frame: Option<&frame::Video>) { // render video or visualizer to the internal texture { let mut surface = SimpleFrameBuffer::new(self.display, &*self.texture).unwrap(); if let Some(frame) = frame { self.video.render(&mut surface, support, frame); } else { self.visualizer.render(&mut surface, support, state); } } // draw the internal texture to video let uniforms = uniform! { tex: &*self.texture, }; target.draw(&self.vertices, &NoIndices(TriangleStrip), &self.program, &uniforms, &Default::default()).unwrap(); } pub fn texture(&self) -> Rc<Texture2d> { self.texture.clone() } }
new
identifier_name
background.rs
use std::rc::Rc; use glium::{Program, Display, VertexBuffer, Surface}; use glium::texture::Texture2d; use glium::framebuffer::SimpleFrameBuffer; use glium::index::NoIndices; use glium::index::PrimitiveType::TriangleStrip; use ffmpeg::frame; use renderer::{Render, Support}; use renderer::background::{Video, Visualizer}; use game; #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 2], texture: [f32; 2], } implement_vertex!(Vertex, position, texture); pub struct Background<'a> { display: &'a Display, video: Video<'a>, visualizer: Visualizer<'a>, program: Program, vertices: VertexBuffer<Vertex>, texture: Rc<Texture2d>, } impl<'a> Background<'a>{ pub fn new<'b>(display: &'b Display) -> Background<'b> { Background { display: display, video: Video::new(display), visualizer: Visualizer::new(display), program: program!(display, 100 => { vertex: " #version 100 precision lowp float; attribute vec2 position; attribute vec2 texture; varying vec2 v_texture; void main() { gl_Position = vec4(position, 0.0, 1.0); v_texture = texture; } ", fragment: " #version 100 precision lowp float; uniform sampler2D tex; varying vec2 v_texture; void main() { gl_FragColor = texture2D(tex, v_texture); } ", }, ).unwrap(), vertices: VertexBuffer::new(display, &[ Vertex { position: [-1.0, 1.0], texture: [0.0, 1.0] }, Vertex { position: [ 1.0, 1.0], texture: [1.0, 1.0] }, Vertex { position: [-1.0, -1.0], texture: [0.0, 0.0] }, Vertex { position: [ 1.0, -1.0], texture: [1.0, 0.0] }, ]).unwrap(), texture: Rc::new(Texture2d::empty(display, 1, 1).unwrap()), } } pub fn resize(&mut self, width: u32, height: u32) { self.texture = Rc::new(Texture2d::empty(self.display, width, height).unwrap()); } pub fn render<S: Surface>(&mut self, target: &mut S, support: &Support, state: &game::State, frame: Option<&frame::Video>) { // render video or visualizer to the internal texture { let mut surface = SimpleFrameBuffer::new(self.display, &*self.texture).unwrap(); if let Some(frame) = frame { self.video.render(&mut surface, support, frame); } else
} // draw the internal texture to video let uniforms = uniform! { tex: &*self.texture, }; target.draw(&self.vertices, &NoIndices(TriangleStrip), &self.program, &uniforms, &Default::default()).unwrap(); } pub fn texture(&self) -> Rc<Texture2d> { self.texture.clone() } }
{ self.visualizer.render(&mut surface, support, state); }
conditional_block
background.rs
use std::rc::Rc; use glium::{Program, Display, VertexBuffer, Surface}; use glium::texture::Texture2d; use glium::framebuffer::SimpleFrameBuffer; use glium::index::NoIndices; use glium::index::PrimitiveType::TriangleStrip; use ffmpeg::frame; use renderer::{Render, Support}; use renderer::background::{Video, Visualizer}; use game; #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 2], texture: [f32; 2], } implement_vertex!(Vertex, position, texture); pub struct Background<'a> { display: &'a Display, video: Video<'a>, visualizer: Visualizer<'a>, program: Program, vertices: VertexBuffer<Vertex>, texture: Rc<Texture2d>, } impl<'a> Background<'a>{ pub fn new<'b>(display: &'b Display) -> Background<'b> { Background { display: display, video: Video::new(display), visualizer: Visualizer::new(display), program: program!(display, 100 => { vertex: " #version 100 precision lowp float; attribute vec2 position; attribute vec2 texture; varying vec2 v_texture; void main() { gl_Position = vec4(position, 0.0, 1.0); v_texture = texture; } ", fragment: " #version 100 precision lowp float; uniform sampler2D tex; varying vec2 v_texture; void main() { gl_FragColor = texture2D(tex, v_texture); } ", }, ).unwrap(), vertices: VertexBuffer::new(display, &[ Vertex { position: [-1.0, 1.0], texture: [0.0, 1.0] }, Vertex { position: [ 1.0, 1.0], texture: [1.0, 1.0] }, Vertex { position: [-1.0, -1.0], texture: [0.0, 0.0] }, Vertex { position: [ 1.0, -1.0], texture: [1.0, 0.0] }, ]).unwrap(), texture: Rc::new(Texture2d::empty(display, 1, 1).unwrap()), } } pub fn resize(&mut self, width: u32, height: u32) { self.texture = Rc::new(Texture2d::empty(self.display, width, height).unwrap()); } pub fn render<S: Surface>(&mut self, target: &mut S, support: &Support, state: &game::State, frame: Option<&frame::Video>) { // render video or visualizer to the internal texture { let mut surface = SimpleFrameBuffer::new(self.display, &*self.texture).unwrap(); if let Some(frame) = frame { self.video.render(&mut surface, support, frame); } else { self.visualizer.render(&mut surface, support, state); } } // draw the internal texture to video let uniforms = uniform! { tex: &*self.texture, }; target.draw(&self.vertices, &NoIndices(TriangleStrip), &self.program, &uniforms, &Default::default()).unwrap(); } pub fn texture(&self) -> Rc<Texture2d> {
}
self.texture.clone() }
random_line_split
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// This module provides linkage between rustc::middle::graph and /// libgraphviz traits. /// For clarity, rename the graphviz crate locally to dot. use dot = graphviz; use syntax::ast; use syntax::ast_map; use middle::cfg; pub type Node<'a> = (cfg::CFGIndex, &'a cfg::CFGNode); pub type Edge<'a> = &'a cfg::CFGEdge; pub struct LabelledCFG<'a>{ pub ast_map: &'a ast_map::Map, pub cfg: &'a cfg::CFG, pub name: String, } fn replace_newline_with_backslash_l(s: String) -> String { // Replacing newlines with \\l causes each line to be left-aligned, // improving presentation of (long) pretty-printed expressions. if s.as_slice().contains("\n") { let mut s = s.replace("\n", "\\l"); // Apparently left-alignment applies to the line that precedes // \l, not the line that follows; so, add \l at end of string // if not already present, ensuring last line gets left-aligned // as well. let mut last_two: Vec<_> = s.as_slice().chars().rev().take(2).collect(); last_two.reverse(); if last_two.as_slice()!= ['\\', 'l'] { s = s.append("\\l"); } s.to_string() } else { s } } impl<'a> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> { fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(self.name.as_slice()) } fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> { dot::Id::new(format!("N{:u}", i.node_id())) } fn node_label(&'a self, &(i, n): &Node<'a>) -> dot::LabelText<'a> { if i == self.cfg.entry { dot::LabelStr("entry".into_maybe_owned()) } else if i == self.cfg.exit { dot::LabelStr("exit".into_maybe_owned()) } else if n.data.id == ast::DUMMY_NODE_ID { dot::LabelStr("(dummy_node)".into_maybe_owned()) } else { let s = self.ast_map.node_to_string(n.data.id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); dot::EscStr(s.into_maybe_owned()) } } fn edge_label(&self, e: &Edge<'a>) -> dot::LabelText<'a> { let mut label = String::new(); let mut put_one = false; for (i, &node_id) in e.data.exiting_scopes.iter().enumerate() { if put_one { label = label.append(",\\l"); } else { put_one = true; } let s = self.ast_map.node_to_string(node_id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); label = label.append(format!("exiting scope_{} {}", i, s.as_slice()).as_slice()); } dot::EscStr(label.into_maybe_owned()) } } impl<'a> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for &'a cfg::CFG { fn
(&self) -> dot::Nodes<'a, Node<'a>> { let mut v = Vec::new(); self.graph.each_node(|i, nd| { v.push((i, nd)); true }); dot::maybe_owned_vec::Growable(v) } fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.graph.all_edges().iter().collect() } fn source(&self, edge: &Edge<'a>) -> Node<'a> { let i = edge.source(); (i, self.graph.node(i)) } fn target(&self, edge: &Edge<'a>) -> Node<'a> { let i = edge.target(); (i, self.graph.node(i)) } } impl<'a> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> { fn nodes(&self) -> dot::Nodes<'a, Node<'a>> { self.cfg.nodes() } fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.cfg.edges() } fn source(&self, edge: &Edge<'a>) -> Node<'a> { self.cfg.source(edge) } fn target(&self, edge: &Edge<'a>) -> Node<'a> { self.cfg.target(edge) } }
nodes
identifier_name
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// This module provides linkage between rustc::middle::graph and /// libgraphviz traits. /// For clarity, rename the graphviz crate locally to dot. use dot = graphviz; use syntax::ast; use syntax::ast_map; use middle::cfg; pub type Node<'a> = (cfg::CFGIndex, &'a cfg::CFGNode); pub type Edge<'a> = &'a cfg::CFGEdge; pub struct LabelledCFG<'a>{ pub ast_map: &'a ast_map::Map, pub cfg: &'a cfg::CFG, pub name: String, } fn replace_newline_with_backslash_l(s: String) -> String { // Replacing newlines with \\l causes each line to be left-aligned, // improving presentation of (long) pretty-printed expressions. if s.as_slice().contains("\n") { let mut s = s.replace("\n", "\\l"); // Apparently left-alignment applies to the line that precedes // \l, not the line that follows; so, add \l at end of string // if not already present, ensuring last line gets left-aligned // as well. let mut last_two: Vec<_> = s.as_slice().chars().rev().take(2).collect(); last_two.reverse(); if last_two.as_slice()!= ['\\', 'l'] { s = s.append("\\l"); } s.to_string() } else { s } } impl<'a> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> { fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(self.name.as_slice()) } fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> { dot::Id::new(format!("N{:u}", i.node_id())) } fn node_label(&'a self, &(i, n): &Node<'a>) -> dot::LabelText<'a> { if i == self.cfg.entry { dot::LabelStr("entry".into_maybe_owned()) } else if i == self.cfg.exit { dot::LabelStr("exit".into_maybe_owned()) } else if n.data.id == ast::DUMMY_NODE_ID { dot::LabelStr("(dummy_node)".into_maybe_owned()) } else { let s = self.ast_map.node_to_string(n.data.id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); dot::EscStr(s.into_maybe_owned()) } } fn edge_label(&self, e: &Edge<'a>) -> dot::LabelText<'a> { let mut label = String::new(); let mut put_one = false; for (i, &node_id) in e.data.exiting_scopes.iter().enumerate() { if put_one { label = label.append(",\\l"); } else { put_one = true; } let s = self.ast_map.node_to_string(node_id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); label = label.append(format!("exiting scope_{} {}", i, s.as_slice()).as_slice()); } dot::EscStr(label.into_maybe_owned()) } } impl<'a> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for &'a cfg::CFG { fn nodes(&self) -> dot::Nodes<'a, Node<'a>> { let mut v = Vec::new(); self.graph.each_node(|i, nd| { v.push((i, nd)); true }); dot::maybe_owned_vec::Growable(v) } fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.graph.all_edges().iter().collect() } fn source(&self, edge: &Edge<'a>) -> Node<'a> { let i = edge.source(); (i, self.graph.node(i)) } fn target(&self, edge: &Edge<'a>) -> Node<'a> { let i = edge.target(); (i, self.graph.node(i)) } } impl<'a> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> { fn nodes(&self) -> dot::Nodes<'a, Node<'a>> { self.cfg.nodes() } fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.cfg.edges() } fn source(&self, edge: &Edge<'a>) -> Node<'a>
fn target(&self, edge: &Edge<'a>) -> Node<'a> { self.cfg.target(edge) } }
{ self.cfg.source(edge) }
identifier_body
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// This module provides linkage between rustc::middle::graph and /// libgraphviz traits. /// For clarity, rename the graphviz crate locally to dot. use dot = graphviz; use syntax::ast; use syntax::ast_map; use middle::cfg; pub type Node<'a> = (cfg::CFGIndex, &'a cfg::CFGNode); pub type Edge<'a> = &'a cfg::CFGEdge; pub struct LabelledCFG<'a>{ pub ast_map: &'a ast_map::Map, pub cfg: &'a cfg::CFG, pub name: String, } fn replace_newline_with_backslash_l(s: String) -> String { // Replacing newlines with \\l causes each line to be left-aligned, // improving presentation of (long) pretty-printed expressions. if s.as_slice().contains("\n") { let mut s = s.replace("\n", "\\l"); // Apparently left-alignment applies to the line that precedes // \l, not the line that follows; so, add \l at end of string // if not already present, ensuring last line gets left-aligned // as well. let mut last_two: Vec<_> = s.as_slice().chars().rev().take(2).collect(); last_two.reverse(); if last_two.as_slice()!= ['\\', 'l']
s.to_string() } else { s } } impl<'a> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> { fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(self.name.as_slice()) } fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> { dot::Id::new(format!("N{:u}", i.node_id())) } fn node_label(&'a self, &(i, n): &Node<'a>) -> dot::LabelText<'a> { if i == self.cfg.entry { dot::LabelStr("entry".into_maybe_owned()) } else if i == self.cfg.exit { dot::LabelStr("exit".into_maybe_owned()) } else if n.data.id == ast::DUMMY_NODE_ID { dot::LabelStr("(dummy_node)".into_maybe_owned()) } else { let s = self.ast_map.node_to_string(n.data.id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); dot::EscStr(s.into_maybe_owned()) } } fn edge_label(&self, e: &Edge<'a>) -> dot::LabelText<'a> { let mut label = String::new(); let mut put_one = false; for (i, &node_id) in e.data.exiting_scopes.iter().enumerate() { if put_one { label = label.append(",\\l"); } else { put_one = true; } let s = self.ast_map.node_to_string(node_id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); label = label.append(format!("exiting scope_{} {}", i, s.as_slice()).as_slice()); } dot::EscStr(label.into_maybe_owned()) } } impl<'a> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for &'a cfg::CFG { fn nodes(&self) -> dot::Nodes<'a, Node<'a>> { let mut v = Vec::new(); self.graph.each_node(|i, nd| { v.push((i, nd)); true }); dot::maybe_owned_vec::Growable(v) } fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.graph.all_edges().iter().collect() } fn source(&self, edge: &Edge<'a>) -> Node<'a> { let i = edge.source(); (i, self.graph.node(i)) } fn target(&self, edge: &Edge<'a>) -> Node<'a> { let i = edge.target(); (i, self.graph.node(i)) } } impl<'a> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> { fn nodes(&self) -> dot::Nodes<'a, Node<'a>> { self.cfg.nodes() } fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.cfg.edges() } fn source(&self, edge: &Edge<'a>) -> Node<'a> { self.cfg.source(edge) } fn target(&self, edge: &Edge<'a>) -> Node<'a> { self.cfg.target(edge) } }
{ s = s.append("\\l"); }
conditional_block
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// This module provides linkage between rustc::middle::graph and /// libgraphviz traits. /// For clarity, rename the graphviz crate locally to dot. use dot = graphviz; use syntax::ast; use syntax::ast_map; use middle::cfg; pub type Node<'a> = (cfg::CFGIndex, &'a cfg::CFGNode); pub type Edge<'a> = &'a cfg::CFGEdge; pub struct LabelledCFG<'a>{ pub ast_map: &'a ast_map::Map, pub cfg: &'a cfg::CFG, pub name: String, } fn replace_newline_with_backslash_l(s: String) -> String { // Replacing newlines with \\l causes each line to be left-aligned, // improving presentation of (long) pretty-printed expressions. if s.as_slice().contains("\n") { let mut s = s.replace("\n", "\\l"); // Apparently left-alignment applies to the line that precedes // \l, not the line that follows; so, add \l at end of string // if not already present, ensuring last line gets left-aligned // as well. let mut last_two: Vec<_> = s.as_slice().chars().rev().take(2).collect(); last_two.reverse(); if last_two.as_slice()!= ['\\', 'l'] { s = s.append("\\l"); } s.to_string() } else { s } } impl<'a> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> { fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(self.name.as_slice()) } fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> { dot::Id::new(format!("N{:u}", i.node_id())) } fn node_label(&'a self, &(i, n): &Node<'a>) -> dot::LabelText<'a> { if i == self.cfg.entry { dot::LabelStr("entry".into_maybe_owned()) } else if i == self.cfg.exit { dot::LabelStr("exit".into_maybe_owned()) } else if n.data.id == ast::DUMMY_NODE_ID { dot::LabelStr("(dummy_node)".into_maybe_owned()) } else { let s = self.ast_map.node_to_string(n.data.id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); dot::EscStr(s.into_maybe_owned()) } } fn edge_label(&self, e: &Edge<'a>) -> dot::LabelText<'a> { let mut label = String::new(); let mut put_one = false; for (i, &node_id) in e.data.exiting_scopes.iter().enumerate() { if put_one { label = label.append(",\\l"); } else { put_one = true; } let s = self.ast_map.node_to_string(node_id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); label = label.append(format!("exiting scope_{} {}", i, s.as_slice()).as_slice()); } dot::EscStr(label.into_maybe_owned()) } } impl<'a> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for &'a cfg::CFG { fn nodes(&self) -> dot::Nodes<'a, Node<'a>> { let mut v = Vec::new(); self.graph.each_node(|i, nd| { v.push((i, nd)); true }); dot::maybe_owned_vec::Growable(v) } fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.graph.all_edges().iter().collect() } fn source(&self, edge: &Edge<'a>) -> Node<'a> { let i = edge.source(); (i, self.graph.node(i)) } fn target(&self, edge: &Edge<'a>) -> Node<'a> { let i = edge.target(); (i, self.graph.node(i))
} impl<'a> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> { fn nodes(&self) -> dot::Nodes<'a, Node<'a>> { self.cfg.nodes() } fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.cfg.edges() } fn source(&self, edge: &Edge<'a>) -> Node<'a> { self.cfg.source(edge) } fn target(&self, edge: &Edge<'a>) -> Node<'a> { self.cfg.target(edge) } }
}
random_line_split
refptr.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 std::marker::PhantomData; use std::mem::{forget, transmute}; use std::ptr; use std::sync::Arc; /// Helper trait for conversions between FFI Strong/Borrowed types and Arcs /// /// Should be implemented by types which are passed over FFI as Arcs /// via Strong and Borrowed pub unsafe trait HasArcFFI where Self: Sized { /// Gecko's name for the type /// This is equivalent to ArcInner<Self> type FFIType: Sized; /// Given a non-null borrowed FFI reference, this produces a temporary /// Arc which is borrowed by the given closure and used. /// Panics on null. fn with<F, Output>(raw: Borrowed<Self::FFIType>, cb: F) -> Output where F: FnOnce(&Arc<Self>) -> Output { Self::maybe_with(raw, |opt| cb(opt.unwrap())) } /// Given a maybe-null borrowed FFI reference, this produces a temporary /// Option<Arc> (None if null) which is borrowed by the given closure and used fn maybe_with<F, Output>(maybe_raw: Borrowed<Self::FFIType>, cb: F) -> Output where F: FnOnce(Option<&Arc<Self>>) -> Output { cb(Self::borrowed_as(&maybe_raw)) } /// Given a non-null strong FFI reference, converts it into an Arc. /// Panics on null. fn into(ptr: Strong<Self::FFIType>) -> Arc<Self> { assert!(!ptr.is_null()); unsafe { transmute(ptr) } } fn borrowed_as<'a>(ptr: &'a Borrowed<'a, Self::FFIType>) -> Option<&'a Arc<Self>> { unsafe { if ptr.is_null() { None } else { Some(transmute::<&Borrowed<_>, &Arc<_>>(ptr)) } } } /// Converts an Arc into a strong FFI reference. fn from_arc(owned: Arc<Self>) -> Strong<Self::FFIType> { unsafe { transmute(owned) } } /// Artificially increments the refcount of a borrowed Arc over FFI. unsafe fn addref(ptr: Borrowed<Self::FFIType>) { Self::with(ptr, |arc| forget(arc.clone())); } /// Given a (possibly null) borrowed FFI reference, decrements the refcount. /// Unsafe since it doesn't consume the backing Arc. Run it only when you /// know that a strong reference to the backing Arc is disappearing /// (usually on the C++ side) without running the Arc destructor. unsafe fn release(ptr: Borrowed<Self::FFIType>) { if let Some(arc) = Self::borrowed_as(&ptr) { let _: Arc<_> = ptr::read(arc as *const Arc<_>); } } /// Produces a borrowed FFI reference by borrowing an Arc. fn to_borrowed<'a>(arc: &'a Arc<Self>) -> Borrowed<'a, Self::FFIType> { let borrowedptr = arc as *const Arc<Self> as *const Borrowed<'a, Self::FFIType>; unsafe { ptr::read(borrowedptr) } } /// Produces a null strong FFI reference fn
() -> Strong<Self::FFIType> { unsafe { transmute(ptr::null::<Self::FFIType>()) } } } #[repr(C)] /// Gecko-FFI-safe borrowed Arc (&T where T is an ArcInner). /// This can be null. pub struct Borrowed<'a, T: 'a> { ptr: *const T, _marker: PhantomData<&'a T>, } // manual impls because derive doesn't realize that `T: Clone` isn't necessary impl<'a, T> Copy for Borrowed<'a, T> {} impl<'a, T> Clone for Borrowed<'a, T> { fn clone(&self) -> Self { *self } } impl<'a, T> Borrowed<'a, T> { pub fn is_null(&self) -> bool { self.ptr == ptr::null() } } #[repr(C)] /// Gecko-FFI-safe Arc (T is an ArcInner). /// This can be null. pub struct Strong<T> { ptr: *const T, _marker: PhantomData<T>, } impl<T> Strong<T> { pub fn is_null(&self) -> bool { self.ptr == ptr::null() } }
null_strong
identifier_name
refptr.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 std::marker::PhantomData; use std::mem::{forget, transmute}; use std::ptr; use std::sync::Arc; /// Helper trait for conversions between FFI Strong/Borrowed types and Arcs /// /// Should be implemented by types which are passed over FFI as Arcs /// via Strong and Borrowed pub unsafe trait HasArcFFI where Self: Sized { /// Gecko's name for the type /// This is equivalent to ArcInner<Self> type FFIType: Sized; /// Given a non-null borrowed FFI reference, this produces a temporary /// Arc which is borrowed by the given closure and used. /// Panics on null. fn with<F, Output>(raw: Borrowed<Self::FFIType>, cb: F) -> Output where F: FnOnce(&Arc<Self>) -> Output { Self::maybe_with(raw, |opt| cb(opt.unwrap())) } /// Given a maybe-null borrowed FFI reference, this produces a temporary /// Option<Arc> (None if null) which is borrowed by the given closure and used fn maybe_with<F, Output>(maybe_raw: Borrowed<Self::FFIType>, cb: F) -> Output where F: FnOnce(Option<&Arc<Self>>) -> Output { cb(Self::borrowed_as(&maybe_raw)) } /// Given a non-null strong FFI reference, converts it into an Arc. /// Panics on null. fn into(ptr: Strong<Self::FFIType>) -> Arc<Self> { assert!(!ptr.is_null()); unsafe { transmute(ptr) } } fn borrowed_as<'a>(ptr: &'a Borrowed<'a, Self::FFIType>) -> Option<&'a Arc<Self>> { unsafe { if ptr.is_null() { None } else { Some(transmute::<&Borrowed<_>, &Arc<_>>(ptr)) } } } /// Converts an Arc into a strong FFI reference. fn from_arc(owned: Arc<Self>) -> Strong<Self::FFIType> { unsafe { transmute(owned) } } /// Artificially increments the refcount of a borrowed Arc over FFI. unsafe fn addref(ptr: Borrowed<Self::FFIType>) { Self::with(ptr, |arc| forget(arc.clone())); } /// Given a (possibly null) borrowed FFI reference, decrements the refcount. /// Unsafe since it doesn't consume the backing Arc. Run it only when you /// know that a strong reference to the backing Arc is disappearing /// (usually on the C++ side) without running the Arc destructor. unsafe fn release(ptr: Borrowed<Self::FFIType>) { if let Some(arc) = Self::borrowed_as(&ptr) { let _: Arc<_> = ptr::read(arc as *const Arc<_>); } } /// Produces a borrowed FFI reference by borrowing an Arc. fn to_borrowed<'a>(arc: &'a Arc<Self>) -> Borrowed<'a, Self::FFIType> { let borrowedptr = arc as *const Arc<Self> as *const Borrowed<'a, Self::FFIType>; unsafe { ptr::read(borrowedptr) } } /// Produces a null strong FFI reference fn null_strong() -> Strong<Self::FFIType> { unsafe { transmute(ptr::null::<Self::FFIType>()) } } } #[repr(C)] /// Gecko-FFI-safe borrowed Arc (&T where T is an ArcInner). /// This can be null. pub struct Borrowed<'a, T: 'a> { ptr: *const T, _marker: PhantomData<&'a T>, } // manual impls because derive doesn't realize that `T: Clone` isn't necessary impl<'a, T> Copy for Borrowed<'a, T> {} impl<'a, T> Clone for Borrowed<'a, T> { fn clone(&self) -> Self { *self } } impl<'a, T> Borrowed<'a, T> { pub fn is_null(&self) -> bool { self.ptr == ptr::null() } } #[repr(C)] /// Gecko-FFI-safe Arc (T is an ArcInner). /// This can be null. pub struct Strong<T> { ptr: *const T, _marker: PhantomData<T>, } impl<T> Strong<T> { pub fn is_null(&self) -> bool
}
{ self.ptr == ptr::null() }
identifier_body
refptr.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 std::marker::PhantomData; use std::mem::{forget, transmute}; use std::ptr; use std::sync::Arc; /// Helper trait for conversions between FFI Strong/Borrowed types and Arcs /// /// Should be implemented by types which are passed over FFI as Arcs /// via Strong and Borrowed pub unsafe trait HasArcFFI where Self: Sized { /// Gecko's name for the type /// This is equivalent to ArcInner<Self> type FFIType: Sized; /// Given a non-null borrowed FFI reference, this produces a temporary /// Arc which is borrowed by the given closure and used. /// Panics on null. fn with<F, Output>(raw: Borrowed<Self::FFIType>, cb: F) -> Output where F: FnOnce(&Arc<Self>) -> Output { Self::maybe_with(raw, |opt| cb(opt.unwrap())) } /// Given a maybe-null borrowed FFI reference, this produces a temporary /// Option<Arc> (None if null) which is borrowed by the given closure and used fn maybe_with<F, Output>(maybe_raw: Borrowed<Self::FFIType>, cb: F) -> Output where F: FnOnce(Option<&Arc<Self>>) -> Output { cb(Self::borrowed_as(&maybe_raw)) } /// Given a non-null strong FFI reference, converts it into an Arc. /// Panics on null. fn into(ptr: Strong<Self::FFIType>) -> Arc<Self> { assert!(!ptr.is_null()); unsafe { transmute(ptr) } } fn borrowed_as<'a>(ptr: &'a Borrowed<'a, Self::FFIType>) -> Option<&'a Arc<Self>> { unsafe { if ptr.is_null() { None } else
} } /// Converts an Arc into a strong FFI reference. fn from_arc(owned: Arc<Self>) -> Strong<Self::FFIType> { unsafe { transmute(owned) } } /// Artificially increments the refcount of a borrowed Arc over FFI. unsafe fn addref(ptr: Borrowed<Self::FFIType>) { Self::with(ptr, |arc| forget(arc.clone())); } /// Given a (possibly null) borrowed FFI reference, decrements the refcount. /// Unsafe since it doesn't consume the backing Arc. Run it only when you /// know that a strong reference to the backing Arc is disappearing /// (usually on the C++ side) without running the Arc destructor. unsafe fn release(ptr: Borrowed<Self::FFIType>) { if let Some(arc) = Self::borrowed_as(&ptr) { let _: Arc<_> = ptr::read(arc as *const Arc<_>); } } /// Produces a borrowed FFI reference by borrowing an Arc. fn to_borrowed<'a>(arc: &'a Arc<Self>) -> Borrowed<'a, Self::FFIType> { let borrowedptr = arc as *const Arc<Self> as *const Borrowed<'a, Self::FFIType>; unsafe { ptr::read(borrowedptr) } } /// Produces a null strong FFI reference fn null_strong() -> Strong<Self::FFIType> { unsafe { transmute(ptr::null::<Self::FFIType>()) } } } #[repr(C)] /// Gecko-FFI-safe borrowed Arc (&T where T is an ArcInner). /// This can be null. pub struct Borrowed<'a, T: 'a> { ptr: *const T, _marker: PhantomData<&'a T>, } // manual impls because derive doesn't realize that `T: Clone` isn't necessary impl<'a, T> Copy for Borrowed<'a, T> {} impl<'a, T> Clone for Borrowed<'a, T> { fn clone(&self) -> Self { *self } } impl<'a, T> Borrowed<'a, T> { pub fn is_null(&self) -> bool { self.ptr == ptr::null() } } #[repr(C)] /// Gecko-FFI-safe Arc (T is an ArcInner). /// This can be null. pub struct Strong<T> { ptr: *const T, _marker: PhantomData<T>, } impl<T> Strong<T> { pub fn is_null(&self) -> bool { self.ptr == ptr::null() } }
{ Some(transmute::<&Borrowed<_>, &Arc<_>>(ptr)) }
conditional_block
refptr.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 std::marker::PhantomData; use std::mem::{forget, transmute}; use std::ptr; use std::sync::Arc; /// Helper trait for conversions between FFI Strong/Borrowed types and Arcs /// /// Should be implemented by types which are passed over FFI as Arcs /// via Strong and Borrowed pub unsafe trait HasArcFFI where Self: Sized { /// Gecko's name for the type /// This is equivalent to ArcInner<Self> type FFIType: Sized; /// Given a non-null borrowed FFI reference, this produces a temporary /// Arc which is borrowed by the given closure and used. /// Panics on null. fn with<F, Output>(raw: Borrowed<Self::FFIType>, cb: F) -> Output where F: FnOnce(&Arc<Self>) -> Output { Self::maybe_with(raw, |opt| cb(opt.unwrap())) } /// Given a maybe-null borrowed FFI reference, this produces a temporary /// Option<Arc> (None if null) which is borrowed by the given closure and used fn maybe_with<F, Output>(maybe_raw: Borrowed<Self::FFIType>, cb: F) -> Output where F: FnOnce(Option<&Arc<Self>>) -> Output { cb(Self::borrowed_as(&maybe_raw)) } /// Given a non-null strong FFI reference, converts it into an Arc. /// Panics on null. fn into(ptr: Strong<Self::FFIType>) -> Arc<Self> { assert!(!ptr.is_null()); unsafe { transmute(ptr) } } fn borrowed_as<'a>(ptr: &'a Borrowed<'a, Self::FFIType>) -> Option<&'a Arc<Self>> { unsafe { if ptr.is_null() { None } else { Some(transmute::<&Borrowed<_>, &Arc<_>>(ptr)) } } } /// Converts an Arc into a strong FFI reference. fn from_arc(owned: Arc<Self>) -> Strong<Self::FFIType> { unsafe { transmute(owned) } } /// Artificially increments the refcount of a borrowed Arc over FFI. unsafe fn addref(ptr: Borrowed<Self::FFIType>) { Self::with(ptr, |arc| forget(arc.clone())); } /// Given a (possibly null) borrowed FFI reference, decrements the refcount. /// Unsafe since it doesn't consume the backing Arc. Run it only when you /// know that a strong reference to the backing Arc is disappearing /// (usually on the C++ side) without running the Arc destructor. unsafe fn release(ptr: Borrowed<Self::FFIType>) { if let Some(arc) = Self::borrowed_as(&ptr) { let _: Arc<_> = ptr::read(arc as *const Arc<_>); } } /// Produces a borrowed FFI reference by borrowing an Arc. fn to_borrowed<'a>(arc: &'a Arc<Self>) -> Borrowed<'a, Self::FFIType> { let borrowedptr = arc as *const Arc<Self> as *const Borrowed<'a, Self::FFIType>; unsafe { ptr::read(borrowedptr) } } /// Produces a null strong FFI reference fn null_strong() -> Strong<Self::FFIType> { unsafe { transmute(ptr::null::<Self::FFIType>()) } } } #[repr(C)] /// Gecko-FFI-safe borrowed Arc (&T where T is an ArcInner). /// This can be null. pub struct Borrowed<'a, T: 'a> { ptr: *const T, _marker: PhantomData<&'a T>, } // manual impls because derive doesn't realize that `T: Clone` isn't necessary impl<'a, T> Copy for Borrowed<'a, T> {} impl<'a, T> Clone for Borrowed<'a, T> { fn clone(&self) -> Self { *self } } impl<'a, T> Borrowed<'a, T> { pub fn is_null(&self) -> bool { self.ptr == ptr::null() } } #[repr(C)] /// Gecko-FFI-safe Arc (T is an ArcInner). /// This can be null. pub struct Strong<T> { ptr: *const T, _marker: PhantomData<T>, }
} }
impl<T> Strong<T> { pub fn is_null(&self) -> bool { self.ptr == ptr::null()
random_line_split
disk.rs
// Take a look at the license at the top of the repository in the LICENSE file. use crate::sys::{ffi, utils}; use crate::utils::to_cpath; use crate::{Disk, DiskType}; use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull, CFRelease}; use core_foundation_sys::dictionary::{CFDictionaryGetValueIfPresent, CFDictionaryRef}; use core_foundation_sys::number::{kCFBooleanTrue, CFBooleanRef}; use core_foundation_sys::string as cfs; use libc::{c_char, c_int, c_void, statfs}; use std::ffi::{OsStr, OsString}; use std::mem; use std::os::unix::ffi::OsStrExt; use std::path::PathBuf; use std::ptr; fn to_path(mount_path: &[c_char]) -> Option<PathBuf> { let mut tmp = Vec::with_capacity(mount_path.len()); for &c in mount_path { if c == 0 { break; } tmp.push(c as u8); } if tmp.is_empty() { None } else { let path = OsStr::from_bytes(&tmp); Some(PathBuf::from(path)) } } pub(crate) fn get_disks(session: ffi::DASessionRef) -> Vec<Disk> { if session.is_null() { return Vec::new(); } unsafe { let count = libc::getfsstat(ptr::null_mut(), 0, libc::MNT_NOWAIT); if count < 1 { return Vec::new(); } let bufsize = count * mem::size_of::<libc::statfs>() as c_int; let mut disks = Vec::with_capacity(count as _); let count = libc::getfsstat(disks.as_mut_ptr(), bufsize, libc::MNT_NOWAIT); if count < 1 { return Vec::new(); } disks.set_len(count as _); disks .into_iter() .filter_map(|c_disk| { let mount_point = to_path(&c_disk.f_mntonname)?; let disk = ffi::DADiskCreateFromBSDName( kCFAllocatorDefault as _, session, c_disk.f_mntfromname.as_ptr(), ); let dict = ffi::DADiskCopyDescription(disk); if dict.is_null() { return None; } // Keeping this around in case one might want the list of the available // keys in "dict". // core_foundation_sys::base::CFShow(dict as _); let name = match get_str_value(dict, b"DAMediaName\0").map(OsString::from) { Some(n) => n, None => return None, }; let removable = get_bool_value(dict, b"DAMediaRemovable\0").unwrap_or(false); let ejectable = get_bool_value(dict, b"DAMediaEjectable\0").unwrap_or(false); // This is very hackish but still better than nothing... let type_ = if let Some(model) = get_str_value(dict, b"DADeviceModel\0") { if model.contains("SSD") { DiskType::SSD } else { // We just assume by default that this is a HDD DiskType::HDD } } else { DiskType::Unknown(-1) }; CFRelease(dict as _); new_disk(name, mount_point, type_, removable || ejectable) }) .collect::<Vec<_>>() } } unsafe fn get_dict_value<T, F: FnOnce(*const c_void) -> Option<T>>( dict: CFDictionaryRef, key: &[u8], callback: F, ) -> Option<T> { let key = ffi::CFStringCreateWithCStringNoCopy( ptr::null_mut(), key.as_ptr() as *const c_char, cfs::kCFStringEncodingUTF8, kCFAllocatorNull as _, ); let mut value = std::ptr::null(); let ret = if CFDictionaryGetValueIfPresent(dict, key as _, &mut value)!= 0 { callback(value) } else { None }; CFRelease(key as _); ret } unsafe fn get_str_value(dict: CFDictionaryRef, key: &[u8]) -> Option<String> { get_dict_value(dict, key, |v| { let v = v as cfs::CFStringRef; let len = cfs::CFStringGetLength(v); utils::cstr_to_rust_with_size( cfs::CFStringGetCStringPtr(v, cfs::kCFStringEncodingUTF8), Some(len as _), ) }) } unsafe fn get_bool_value(dict: CFDictionaryRef, key: &[u8]) -> Option<bool> { get_dict_value(dict, key, |v| Some(v as CFBooleanRef == kCFBooleanTrue)) } fn new_disk( name: OsString, mount_point: PathBuf, type_: DiskType, is_removable: bool, ) -> Option<Disk> { let mount_point_cpath = to_cpath(&mount_point); let mut total_space = 0; let mut available_space = 0; let mut file_system = None; unsafe { let mut stat: statfs = mem::zeroed(); if statfs(mount_point_cpath.as_ptr() as *const i8, &mut stat) == 0 { total_space = u64::from(stat.f_bsize) * stat.f_blocks; available_space = u64::from(stat.f_bsize) * stat.f_bavail; let mut vec = Vec::with_capacity(stat.f_fstypename.len()); for x in &stat.f_fstypename { if *x == 0
vec.push(*x as u8); } file_system = Some(vec); } if total_space == 0 { return None; } Some(Disk { type_, name, file_system: file_system.unwrap_or_else(|| b"<Unknown>".to_vec()), mount_point, total_space, available_space, is_removable, }) } }
{ break; }
conditional_block
disk.rs
// Take a look at the license at the top of the repository in the LICENSE file. use crate::sys::{ffi, utils}; use crate::utils::to_cpath; use crate::{Disk, DiskType}; use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull, CFRelease}; use core_foundation_sys::dictionary::{CFDictionaryGetValueIfPresent, CFDictionaryRef}; use core_foundation_sys::number::{kCFBooleanTrue, CFBooleanRef}; use core_foundation_sys::string as cfs; use libc::{c_char, c_int, c_void, statfs}; use std::ffi::{OsStr, OsString}; use std::mem; use std::os::unix::ffi::OsStrExt; use std::path::PathBuf; use std::ptr; fn to_path(mount_path: &[c_char]) -> Option<PathBuf> { let mut tmp = Vec::with_capacity(mount_path.len()); for &c in mount_path { if c == 0 { break; } tmp.push(c as u8); } if tmp.is_empty() { None } else { let path = OsStr::from_bytes(&tmp); Some(PathBuf::from(path)) } } pub(crate) fn get_disks(session: ffi::DASessionRef) -> Vec<Disk> { if session.is_null() { return Vec::new(); } unsafe { let count = libc::getfsstat(ptr::null_mut(), 0, libc::MNT_NOWAIT); if count < 1 { return Vec::new(); } let bufsize = count * mem::size_of::<libc::statfs>() as c_int; let mut disks = Vec::with_capacity(count as _); let count = libc::getfsstat(disks.as_mut_ptr(), bufsize, libc::MNT_NOWAIT); if count < 1 { return Vec::new(); } disks.set_len(count as _); disks .into_iter() .filter_map(|c_disk| { let mount_point = to_path(&c_disk.f_mntonname)?; let disk = ffi::DADiskCreateFromBSDName( kCFAllocatorDefault as _, session, c_disk.f_mntfromname.as_ptr(), ); let dict = ffi::DADiskCopyDescription(disk); if dict.is_null() { return None; } // Keeping this around in case one might want the list of the available // keys in "dict". // core_foundation_sys::base::CFShow(dict as _); let name = match get_str_value(dict, b"DAMediaName\0").map(OsString::from) { Some(n) => n, None => return None, }; let removable = get_bool_value(dict, b"DAMediaRemovable\0").unwrap_or(false); let ejectable = get_bool_value(dict, b"DAMediaEjectable\0").unwrap_or(false); // This is very hackish but still better than nothing... let type_ = if let Some(model) = get_str_value(dict, b"DADeviceModel\0") { if model.contains("SSD") { DiskType::SSD } else { // We just assume by default that this is a HDD DiskType::HDD } } else { DiskType::Unknown(-1) }; CFRelease(dict as _); new_disk(name, mount_point, type_, removable || ejectable) }) .collect::<Vec<_>>() } } unsafe fn get_dict_value<T, F: FnOnce(*const c_void) -> Option<T>>( dict: CFDictionaryRef, key: &[u8], callback: F, ) -> Option<T> { let key = ffi::CFStringCreateWithCStringNoCopy( ptr::null_mut(), key.as_ptr() as *const c_char, cfs::kCFStringEncodingUTF8, kCFAllocatorNull as _, ); let mut value = std::ptr::null(); let ret = if CFDictionaryGetValueIfPresent(dict, key as _, &mut value)!= 0 { callback(value) } else { None }; CFRelease(key as _); ret } unsafe fn get_str_value(dict: CFDictionaryRef, key: &[u8]) -> Option<String> { get_dict_value(dict, key, |v| { let v = v as cfs::CFStringRef; let len = cfs::CFStringGetLength(v); utils::cstr_to_rust_with_size( cfs::CFStringGetCStringPtr(v, cfs::kCFStringEncodingUTF8), Some(len as _), ) }) } unsafe fn
(dict: CFDictionaryRef, key: &[u8]) -> Option<bool> { get_dict_value(dict, key, |v| Some(v as CFBooleanRef == kCFBooleanTrue)) } fn new_disk( name: OsString, mount_point: PathBuf, type_: DiskType, is_removable: bool, ) -> Option<Disk> { let mount_point_cpath = to_cpath(&mount_point); let mut total_space = 0; let mut available_space = 0; let mut file_system = None; unsafe { let mut stat: statfs = mem::zeroed(); if statfs(mount_point_cpath.as_ptr() as *const i8, &mut stat) == 0 { total_space = u64::from(stat.f_bsize) * stat.f_blocks; available_space = u64::from(stat.f_bsize) * stat.f_bavail; let mut vec = Vec::with_capacity(stat.f_fstypename.len()); for x in &stat.f_fstypename { if *x == 0 { break; } vec.push(*x as u8); } file_system = Some(vec); } if total_space == 0 { return None; } Some(Disk { type_, name, file_system: file_system.unwrap_or_else(|| b"<Unknown>".to_vec()), mount_point, total_space, available_space, is_removable, }) } }
get_bool_value
identifier_name
disk.rs
// Take a look at the license at the top of the repository in the LICENSE file. use crate::sys::{ffi, utils}; use crate::utils::to_cpath; use crate::{Disk, DiskType}; use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull, CFRelease}; use core_foundation_sys::dictionary::{CFDictionaryGetValueIfPresent, CFDictionaryRef}; use core_foundation_sys::number::{kCFBooleanTrue, CFBooleanRef}; use core_foundation_sys::string as cfs; use libc::{c_char, c_int, c_void, statfs}; use std::ffi::{OsStr, OsString}; use std::mem; use std::os::unix::ffi::OsStrExt; use std::path::PathBuf; use std::ptr; fn to_path(mount_path: &[c_char]) -> Option<PathBuf> { let mut tmp = Vec::with_capacity(mount_path.len()); for &c in mount_path { if c == 0 { break; } tmp.push(c as u8); } if tmp.is_empty() { None } else { let path = OsStr::from_bytes(&tmp); Some(PathBuf::from(path)) } } pub(crate) fn get_disks(session: ffi::DASessionRef) -> Vec<Disk> { if session.is_null() { return Vec::new(); } unsafe { let count = libc::getfsstat(ptr::null_mut(), 0, libc::MNT_NOWAIT); if count < 1 { return Vec::new(); } let bufsize = count * mem::size_of::<libc::statfs>() as c_int; let mut disks = Vec::with_capacity(count as _); let count = libc::getfsstat(disks.as_mut_ptr(), bufsize, libc::MNT_NOWAIT); if count < 1 { return Vec::new(); } disks.set_len(count as _); disks .into_iter() .filter_map(|c_disk| { let mount_point = to_path(&c_disk.f_mntonname)?; let disk = ffi::DADiskCreateFromBSDName( kCFAllocatorDefault as _, session, c_disk.f_mntfromname.as_ptr(), ); let dict = ffi::DADiskCopyDescription(disk); if dict.is_null() { return None; } // Keeping this around in case one might want the list of the available // keys in "dict". // core_foundation_sys::base::CFShow(dict as _); let name = match get_str_value(dict, b"DAMediaName\0").map(OsString::from) { Some(n) => n, None => return None, }; let removable = get_bool_value(dict, b"DAMediaRemovable\0").unwrap_or(false); let ejectable = get_bool_value(dict, b"DAMediaEjectable\0").unwrap_or(false); // This is very hackish but still better than nothing... let type_ = if let Some(model) = get_str_value(dict, b"DADeviceModel\0") { if model.contains("SSD") { DiskType::SSD } else { // We just assume by default that this is a HDD DiskType::HDD } } else { DiskType::Unknown(-1) }; CFRelease(dict as _); new_disk(name, mount_point, type_, removable || ejectable) }) .collect::<Vec<_>>() } } unsafe fn get_dict_value<T, F: FnOnce(*const c_void) -> Option<T>>( dict: CFDictionaryRef, key: &[u8], callback: F, ) -> Option<T> { let key = ffi::CFStringCreateWithCStringNoCopy( ptr::null_mut(), key.as_ptr() as *const c_char, cfs::kCFStringEncodingUTF8, kCFAllocatorNull as _, ); let mut value = std::ptr::null(); let ret = if CFDictionaryGetValueIfPresent(dict, key as _, &mut value)!= 0 { callback(value) } else { None }; CFRelease(key as _); ret } unsafe fn get_str_value(dict: CFDictionaryRef, key: &[u8]) -> Option<String>
unsafe fn get_bool_value(dict: CFDictionaryRef, key: &[u8]) -> Option<bool> { get_dict_value(dict, key, |v| Some(v as CFBooleanRef == kCFBooleanTrue)) } fn new_disk( name: OsString, mount_point: PathBuf, type_: DiskType, is_removable: bool, ) -> Option<Disk> { let mount_point_cpath = to_cpath(&mount_point); let mut total_space = 0; let mut available_space = 0; let mut file_system = None; unsafe { let mut stat: statfs = mem::zeroed(); if statfs(mount_point_cpath.as_ptr() as *const i8, &mut stat) == 0 { total_space = u64::from(stat.f_bsize) * stat.f_blocks; available_space = u64::from(stat.f_bsize) * stat.f_bavail; let mut vec = Vec::with_capacity(stat.f_fstypename.len()); for x in &stat.f_fstypename { if *x == 0 { break; } vec.push(*x as u8); } file_system = Some(vec); } if total_space == 0 { return None; } Some(Disk { type_, name, file_system: file_system.unwrap_or_else(|| b"<Unknown>".to_vec()), mount_point, total_space, available_space, is_removable, }) } }
{ get_dict_value(dict, key, |v| { let v = v as cfs::CFStringRef; let len = cfs::CFStringGetLength(v); utils::cstr_to_rust_with_size( cfs::CFStringGetCStringPtr(v, cfs::kCFStringEncodingUTF8), Some(len as _), ) }) }
identifier_body
disk.rs
// Take a look at the license at the top of the repository in the LICENSE file. use crate::sys::{ffi, utils}; use crate::utils::to_cpath; use crate::{Disk, DiskType}; use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull, CFRelease}; use core_foundation_sys::dictionary::{CFDictionaryGetValueIfPresent, CFDictionaryRef}; use core_foundation_sys::number::{kCFBooleanTrue, CFBooleanRef}; use core_foundation_sys::string as cfs; use libc::{c_char, c_int, c_void, statfs}; use std::ffi::{OsStr, OsString}; use std::mem; use std::os::unix::ffi::OsStrExt; use std::path::PathBuf; use std::ptr; fn to_path(mount_path: &[c_char]) -> Option<PathBuf> { let mut tmp = Vec::with_capacity(mount_path.len()); for &c in mount_path { if c == 0 { break; } tmp.push(c as u8); } if tmp.is_empty() { None } else { let path = OsStr::from_bytes(&tmp); Some(PathBuf::from(path)) } } pub(crate) fn get_disks(session: ffi::DASessionRef) -> Vec<Disk> { if session.is_null() { return Vec::new(); } unsafe { let count = libc::getfsstat(ptr::null_mut(), 0, libc::MNT_NOWAIT); if count < 1 { return Vec::new(); } let bufsize = count * mem::size_of::<libc::statfs>() as c_int; let mut disks = Vec::with_capacity(count as _); let count = libc::getfsstat(disks.as_mut_ptr(), bufsize, libc::MNT_NOWAIT); if count < 1 { return Vec::new(); } disks.set_len(count as _); disks .into_iter() .filter_map(|c_disk| { let mount_point = to_path(&c_disk.f_mntonname)?; let disk = ffi::DADiskCreateFromBSDName( kCFAllocatorDefault as _, session, c_disk.f_mntfromname.as_ptr(), ); let dict = ffi::DADiskCopyDescription(disk); if dict.is_null() { return None; } // Keeping this around in case one might want the list of the available // keys in "dict". // core_foundation_sys::base::CFShow(dict as _); let name = match get_str_value(dict, b"DAMediaName\0").map(OsString::from) { Some(n) => n, None => return None, }; let removable = get_bool_value(dict, b"DAMediaRemovable\0").unwrap_or(false); let ejectable = get_bool_value(dict, b"DAMediaEjectable\0").unwrap_or(false); // This is very hackish but still better than nothing... let type_ = if let Some(model) = get_str_value(dict, b"DADeviceModel\0") { if model.contains("SSD") { DiskType::SSD
DiskType::Unknown(-1) }; CFRelease(dict as _); new_disk(name, mount_point, type_, removable || ejectable) }) .collect::<Vec<_>>() } } unsafe fn get_dict_value<T, F: FnOnce(*const c_void) -> Option<T>>( dict: CFDictionaryRef, key: &[u8], callback: F, ) -> Option<T> { let key = ffi::CFStringCreateWithCStringNoCopy( ptr::null_mut(), key.as_ptr() as *const c_char, cfs::kCFStringEncodingUTF8, kCFAllocatorNull as _, ); let mut value = std::ptr::null(); let ret = if CFDictionaryGetValueIfPresent(dict, key as _, &mut value)!= 0 { callback(value) } else { None }; CFRelease(key as _); ret } unsafe fn get_str_value(dict: CFDictionaryRef, key: &[u8]) -> Option<String> { get_dict_value(dict, key, |v| { let v = v as cfs::CFStringRef; let len = cfs::CFStringGetLength(v); utils::cstr_to_rust_with_size( cfs::CFStringGetCStringPtr(v, cfs::kCFStringEncodingUTF8), Some(len as _), ) }) } unsafe fn get_bool_value(dict: CFDictionaryRef, key: &[u8]) -> Option<bool> { get_dict_value(dict, key, |v| Some(v as CFBooleanRef == kCFBooleanTrue)) } fn new_disk( name: OsString, mount_point: PathBuf, type_: DiskType, is_removable: bool, ) -> Option<Disk> { let mount_point_cpath = to_cpath(&mount_point); let mut total_space = 0; let mut available_space = 0; let mut file_system = None; unsafe { let mut stat: statfs = mem::zeroed(); if statfs(mount_point_cpath.as_ptr() as *const i8, &mut stat) == 0 { total_space = u64::from(stat.f_bsize) * stat.f_blocks; available_space = u64::from(stat.f_bsize) * stat.f_bavail; let mut vec = Vec::with_capacity(stat.f_fstypename.len()); for x in &stat.f_fstypename { if *x == 0 { break; } vec.push(*x as u8); } file_system = Some(vec); } if total_space == 0 { return None; } Some(Disk { type_, name, file_system: file_system.unwrap_or_else(|| b"<Unknown>".to_vec()), mount_point, total_space, available_space, is_removable, }) } }
} else { // We just assume by default that this is a HDD DiskType::HDD } } else {
random_line_split
lib.rs
extern crate base64; extern crate bincode; extern crate bytes; extern crate byteorder; extern crate chan; extern crate chrono; extern crate crossbeam; extern crate crypto; #[cfg(feature = "rvi")] extern crate dbus; extern crate hex; extern crate hmac; extern crate hyper; extern crate itoa; #[macro_use] extern crate lazy_static; extern crate libc; #[macro_use] extern crate log; #[macro_use] extern crate maplit; extern crate net2; extern crate openssl; extern crate pem; extern crate ring; extern crate serde; #[macro_use] extern crate serde_derive;
extern crate sha2; extern crate tar; extern crate time; extern crate toml; #[cfg(feature = "websocket")] extern crate tungstenite; #[cfg(feature = "socket")] extern crate unix_socket; extern crate untrusted; extern crate url; extern crate uuid; pub mod atomic; pub mod authenticate; pub mod broadcast; pub mod datatype; pub mod gateway; pub mod http; pub mod images; pub mod interpreter; pub mod pacman; #[cfg(feature = "rvi")] pub mod rvi; pub mod sota; pub mod uptane;
extern crate serde_json as json;
random_line_split
lib.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/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[privatize]` : Forces all fields in a struct/enum to be private //! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate //! - `#[must_root]` : Prevents data of the marked type from being used on the stack. //! See the lints module for more details //! - `#[dom_struct]` : Implies `#[privatize]`,`#[derive(JSTraceable)]`, and `#[must_root]`. //! Use this for structs that correspond to a DOM type #![feature(plugin_registrar, quote, plugin, box_syntax, rustc_private)] #[macro_use] extern crate syntax; #[macro_use] extern crate rustc; extern crate tenacious; use rustc::lint::LintPassObject; use rustc::plugin::Registry; use syntax::ext::base::*; use syntax::parse::token::intern; // Public for documentation to show up /// Handles the auto-deriving for `#[derive(JSTraceable)]` pub mod jstraceable; /// Handles the auto-deriving for `#[derive(HeapSizeOf)]` pub mod heap_size; /// Autogenerates implementations of Reflectable on DOM structs pub mod reflector; pub mod lints; /// Utilities for writing plugins pub mod utils; pub mod casing; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry)
{ reg.register_syntax_extension(intern("dom_struct"), MultiModifier(box jstraceable::expand_dom_struct)); reg.register_syntax_extension(intern("derive_JSTraceable"), MultiDecorator(box jstraceable::expand_jstraceable)); reg.register_syntax_extension(intern("_generate_reflector"), MultiDecorator(box reflector::expand_reflector)); reg.register_syntax_extension(intern("derive_HeapSizeOf"), MultiDecorator(box heap_size::expand_heap_size)); reg.register_macro("to_lower", casing::expand_lower); reg.register_macro("to_upper", casing::expand_upper); reg.register_lint_pass(box lints::transmute_type::TransmutePass as LintPassObject); reg.register_lint_pass(box lints::unrooted_must_root::UnrootedPass as LintPassObject); reg.register_lint_pass(box lints::privatize::PrivatizePass as LintPassObject); reg.register_lint_pass(box lints::inheritance_integrity::InheritancePass as LintPassObject); reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject); reg.register_lint_pass(box lints::ban::BanPass as LintPassObject); reg.register_lint_pass(box tenacious::TenaciousPass as LintPassObject); }
identifier_body
lib.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/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[privatize]` : Forces all fields in a struct/enum to be private //! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate //! - `#[must_root]` : Prevents data of the marked type from being used on the stack. //! See the lints module for more details //! - `#[dom_struct]` : Implies `#[privatize]`,`#[derive(JSTraceable)]`, and `#[must_root]`. //! Use this for structs that correspond to a DOM type #![feature(plugin_registrar, quote, plugin, box_syntax, rustc_private)] #[macro_use] extern crate syntax; #[macro_use] extern crate rustc; extern crate tenacious; use rustc::lint::LintPassObject; use rustc::plugin::Registry; use syntax::ext::base::*; use syntax::parse::token::intern; // Public for documentation to show up /// Handles the auto-deriving for `#[derive(JSTraceable)]` pub mod jstraceable; /// Handles the auto-deriving for `#[derive(HeapSizeOf)]` pub mod heap_size; /// Autogenerates implementations of Reflectable on DOM structs pub mod reflector; pub mod lints; /// Utilities for writing plugins pub mod utils; pub mod casing; #[plugin_registrar] pub fn
(reg: &mut Registry) { reg.register_syntax_extension(intern("dom_struct"), MultiModifier(box jstraceable::expand_dom_struct)); reg.register_syntax_extension(intern("derive_JSTraceable"), MultiDecorator(box jstraceable::expand_jstraceable)); reg.register_syntax_extension(intern("_generate_reflector"), MultiDecorator(box reflector::expand_reflector)); reg.register_syntax_extension(intern("derive_HeapSizeOf"), MultiDecorator(box heap_size::expand_heap_size)); reg.register_macro("to_lower", casing::expand_lower); reg.register_macro("to_upper", casing::expand_upper); reg.register_lint_pass(box lints::transmute_type::TransmutePass as LintPassObject); reg.register_lint_pass(box lints::unrooted_must_root::UnrootedPass as LintPassObject); reg.register_lint_pass(box lints::privatize::PrivatizePass as LintPassObject); reg.register_lint_pass(box lints::inheritance_integrity::InheritancePass as LintPassObject); reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject); reg.register_lint_pass(box lints::ban::BanPass as LintPassObject); reg.register_lint_pass(box tenacious::TenaciousPass as LintPassObject); }
plugin_registrar
identifier_name
lib.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/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[privatize]` : Forces all fields in a struct/enum to be private //! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate //! - `#[must_root]` : Prevents data of the marked type from being used on the stack. //! See the lints module for more details //! - `#[dom_struct]` : Implies `#[privatize]`,`#[derive(JSTraceable)]`, and `#[must_root]`. //! Use this for structs that correspond to a DOM type #![feature(plugin_registrar, quote, plugin, box_syntax, rustc_private)] #[macro_use] extern crate syntax; #[macro_use] extern crate rustc; extern crate tenacious; use rustc::lint::LintPassObject; use rustc::plugin::Registry; use syntax::ext::base::*; use syntax::parse::token::intern; // Public for documentation to show up /// Handles the auto-deriving for `#[derive(JSTraceable)]` pub mod jstraceable; /// Handles the auto-deriving for `#[derive(HeapSizeOf)]` pub mod heap_size; /// Autogenerates implementations of Reflectable on DOM structs pub mod reflector; pub mod lints; /// Utilities for writing plugins pub mod utils; pub mod casing; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_syntax_extension(intern("dom_struct"), MultiModifier(box jstraceable::expand_dom_struct)); reg.register_syntax_extension(intern("derive_JSTraceable"), MultiDecorator(box jstraceable::expand_jstraceable)); reg.register_syntax_extension(intern("_generate_reflector"), MultiDecorator(box reflector::expand_reflector)); reg.register_syntax_extension(intern("derive_HeapSizeOf"), MultiDecorator(box heap_size::expand_heap_size)); reg.register_macro("to_lower", casing::expand_lower); reg.register_macro("to_upper", casing::expand_upper); reg.register_lint_pass(box lints::transmute_type::TransmutePass as LintPassObject); reg.register_lint_pass(box lints::unrooted_must_root::UnrootedPass as LintPassObject); reg.register_lint_pass(box lints::privatize::PrivatizePass as LintPassObject); reg.register_lint_pass(box lints::inheritance_integrity::InheritancePass as LintPassObject);
reg.register_lint_pass(box lints::ban::BanPass as LintPassObject); reg.register_lint_pass(box tenacious::TenaciousPass as LintPassObject); }
reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject);
random_line_split
lifetime.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. /*! * This module implements the check that the lifetime of a borrow * does not exceed the lifetime of the value being borrowed. */ use middle::borrowck::*; use euv = middle::expr_use_visitor; use mc = middle::mem_categorization; use middle::ty; use util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime(bccx: &BorrowckCtxt, item_scope_id: ast::NodeId, span: Span, cause: euv::LoanCause, cmt: mc::cmt, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope_id: item_scope_id, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a> { bccx: &'a BorrowckCtxt<'a>, // the node id of the function body for the enclosing item item_scope_id: ast::NodeId, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt } impl<'a> GuaranteeLifetimeContext<'a> { fn check(&self, cmt: &mc::cmt, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the "guarantor". debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_copied_upvar(..) | // L-Local mc::cat_local(..) | // L-Local mc::cat_arg(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base) | mc::cat_deref(ref base, _, mc::OwnedPtr) | // L-Deref-Send mc::cat_interior(ref base, _) | // L-Field mc::cat_deref(ref base, _, mc::GcPtr) => { self.check(base, discr_scope) } mc::cat_discr(ref base, new_discr_scope) => { // Subtle: in a match, we must ensure that each binding // variable remains valid for the duration of the arm in // which it appears, presuming that this arm is taken. // But it is inconvenient in trans to root something just // for one arm. Therefore, we insert a cat_discr(), // basically a special kind of category that says "if this // value must be dynamically rooted, root it for the scope // `match_id`". // // As an example, consider this scenario: // // let mut x = @Some(3); // match *x { Some(y) {...} None {...} } // // Technically, the value `x` need only be rooted // in the `some` arm. However, we evaluate `x` in trans // before we know what arm will be taken, so we just // always root it for the duration of the match. // // As a second example, consider *this* scenario: // // let x = @@Some(3); // match x { @@Some(y) {...} @@None {...} } // // Here again, `x` need only be rooted in the `some` arm. // In this case, the value which needs to be rooted is // found only when checking which pattern matches: but // this check is done before entering the arm. Therefore, // even in this case we just choose to keep the value // rooted for the entire match. This means the value will be // rooted even if the none arm is taken. Oh well. // // At first, I tried to optimize the second case to only // root in one arm, but the result was suboptimal: first, // it interfered with the construction of phi nodes in the // arm, as we were adding code to root values before the // phi nodes were added. This could have been addressed // with a second basic block. However, the naive approach // also yielded suboptimal results for patterns like: // // let x = @@...; // match x { @@some_variant(y) | @@some_other_variant(y) => // // The reason is that we would root the value once for // each pattern and not once per arm. This is also easily // fixed, but it's yet more code for what is really quite // the corner case. // // Nonetheless, if you decide to optimize this case in the // future, you need only adjust where the cat_discr() // node appears to draw the line between what will be rooted // in the *arm* vs the *match*. self.check(base, Some(new_discr_scope)) } } } fn check_scope(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `valid_scope` if!self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. // See the SCOPE(LV) function in doc.rs match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) | mc::cat_copied_upvar(_) =>
mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) | mc::cat_arg(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt) | mc::cat_deref(ref cmt, _, mc::OwnedPtr) | mc::cat_deref(ref cmt, _, mc::GcPtr) | mc::cat_interior(ref cmt, _) | mc::cat_discr(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
{ ty::ReScope(self.item_scope_id) }
conditional_block
lifetime.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. /*! * This module implements the check that the lifetime of a borrow * does not exceed the lifetime of the value being borrowed. */ use middle::borrowck::*; use euv = middle::expr_use_visitor; use mc = middle::mem_categorization; use middle::ty; use util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime(bccx: &BorrowckCtxt, item_scope_id: ast::NodeId, span: Span, cause: euv::LoanCause, cmt: mc::cmt, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope_id: item_scope_id, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct
<'a> { bccx: &'a BorrowckCtxt<'a>, // the node id of the function body for the enclosing item item_scope_id: ast::NodeId, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt } impl<'a> GuaranteeLifetimeContext<'a> { fn check(&self, cmt: &mc::cmt, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the "guarantor". debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_copied_upvar(..) | // L-Local mc::cat_local(..) | // L-Local mc::cat_arg(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base) | mc::cat_deref(ref base, _, mc::OwnedPtr) | // L-Deref-Send mc::cat_interior(ref base, _) | // L-Field mc::cat_deref(ref base, _, mc::GcPtr) => { self.check(base, discr_scope) } mc::cat_discr(ref base, new_discr_scope) => { // Subtle: in a match, we must ensure that each binding // variable remains valid for the duration of the arm in // which it appears, presuming that this arm is taken. // But it is inconvenient in trans to root something just // for one arm. Therefore, we insert a cat_discr(), // basically a special kind of category that says "if this // value must be dynamically rooted, root it for the scope // `match_id`". // // As an example, consider this scenario: // // let mut x = @Some(3); // match *x { Some(y) {...} None {...} } // // Technically, the value `x` need only be rooted // in the `some` arm. However, we evaluate `x` in trans // before we know what arm will be taken, so we just // always root it for the duration of the match. // // As a second example, consider *this* scenario: // // let x = @@Some(3); // match x { @@Some(y) {...} @@None {...} } // // Here again, `x` need only be rooted in the `some` arm. // In this case, the value which needs to be rooted is // found only when checking which pattern matches: but // this check is done before entering the arm. Therefore, // even in this case we just choose to keep the value // rooted for the entire match. This means the value will be // rooted even if the none arm is taken. Oh well. // // At first, I tried to optimize the second case to only // root in one arm, but the result was suboptimal: first, // it interfered with the construction of phi nodes in the // arm, as we were adding code to root values before the // phi nodes were added. This could have been addressed // with a second basic block. However, the naive approach // also yielded suboptimal results for patterns like: // // let x = @@...; // match x { @@some_variant(y) | @@some_other_variant(y) => // // The reason is that we would root the value once for // each pattern and not once per arm. This is also easily // fixed, but it's yet more code for what is really quite // the corner case. // // Nonetheless, if you decide to optimize this case in the // future, you need only adjust where the cat_discr() // node appears to draw the line between what will be rooted // in the *arm* vs the *match*. self.check(base, Some(new_discr_scope)) } } } fn check_scope(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `valid_scope` if!self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. // See the SCOPE(LV) function in doc.rs match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) | mc::cat_copied_upvar(_) => { ty::ReScope(self.item_scope_id) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) | mc::cat_arg(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt) | mc::cat_deref(ref cmt, _, mc::OwnedPtr) | mc::cat_deref(ref cmt, _, mc::GcPtr) | mc::cat_interior(ref cmt, _) | mc::cat_discr(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
GuaranteeLifetimeContext
identifier_name
lifetime.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. /*! * This module implements the check that the lifetime of a borrow * does not exceed the lifetime of the value being borrowed. */ use middle::borrowck::*; use euv = middle::expr_use_visitor; use mc = middle::mem_categorization; use middle::ty; use util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime(bccx: &BorrowckCtxt, item_scope_id: ast::NodeId, span: Span, cause: euv::LoanCause, cmt: mc::cmt, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()>
/////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a> { bccx: &'a BorrowckCtxt<'a>, // the node id of the function body for the enclosing item item_scope_id: ast::NodeId, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt } impl<'a> GuaranteeLifetimeContext<'a> { fn check(&self, cmt: &mc::cmt, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the "guarantor". debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_copied_upvar(..) | // L-Local mc::cat_local(..) | // L-Local mc::cat_arg(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base) | mc::cat_deref(ref base, _, mc::OwnedPtr) | // L-Deref-Send mc::cat_interior(ref base, _) | // L-Field mc::cat_deref(ref base, _, mc::GcPtr) => { self.check(base, discr_scope) } mc::cat_discr(ref base, new_discr_scope) => { // Subtle: in a match, we must ensure that each binding // variable remains valid for the duration of the arm in // which it appears, presuming that this arm is taken. // But it is inconvenient in trans to root something just // for one arm. Therefore, we insert a cat_discr(), // basically a special kind of category that says "if this // value must be dynamically rooted, root it for the scope // `match_id`". // // As an example, consider this scenario: // // let mut x = @Some(3); // match *x { Some(y) {...} None {...} } // // Technically, the value `x` need only be rooted // in the `some` arm. However, we evaluate `x` in trans // before we know what arm will be taken, so we just // always root it for the duration of the match. // // As a second example, consider *this* scenario: // // let x = @@Some(3); // match x { @@Some(y) {...} @@None {...} } // // Here again, `x` need only be rooted in the `some` arm. // In this case, the value which needs to be rooted is // found only when checking which pattern matches: but // this check is done before entering the arm. Therefore, // even in this case we just choose to keep the value // rooted for the entire match. This means the value will be // rooted even if the none arm is taken. Oh well. // // At first, I tried to optimize the second case to only // root in one arm, but the result was suboptimal: first, // it interfered with the construction of phi nodes in the // arm, as we were adding code to root values before the // phi nodes were added. This could have been addressed // with a second basic block. However, the naive approach // also yielded suboptimal results for patterns like: // // let x = @@...; // match x { @@some_variant(y) | @@some_other_variant(y) => // // The reason is that we would root the value once for // each pattern and not once per arm. This is also easily // fixed, but it's yet more code for what is really quite // the corner case. // // Nonetheless, if you decide to optimize this case in the // future, you need only adjust where the cat_discr() // node appears to draw the line between what will be rooted // in the *arm* vs the *match*. self.check(base, Some(new_discr_scope)) } } } fn check_scope(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `valid_scope` if!self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. // See the SCOPE(LV) function in doc.rs match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) | mc::cat_copied_upvar(_) => { ty::ReScope(self.item_scope_id) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) | mc::cat_arg(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt) | mc::cat_deref(ref cmt, _, mc::OwnedPtr) | mc::cat_deref(ref cmt, _, mc::GcPtr) | mc::cat_interior(ref cmt, _) | mc::cat_discr(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
{ debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope_id: item_scope_id, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) }
identifier_body
lifetime.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. /*! * This module implements the check that the lifetime of a borrow * does not exceed the lifetime of the value being borrowed. */ use middle::borrowck::*; use euv = middle::expr_use_visitor; use mc = middle::mem_categorization; use middle::ty; use util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime(bccx: &BorrowckCtxt, item_scope_id: ast::NodeId, span: Span, cause: euv::LoanCause, cmt: mc::cmt, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope_id: item_scope_id, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a> { bccx: &'a BorrowckCtxt<'a>, // the node id of the function body for the enclosing item item_scope_id: ast::NodeId, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt } impl<'a> GuaranteeLifetimeContext<'a> { fn check(&self, cmt: &mc::cmt, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the "guarantor". debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_copied_upvar(..) | // L-Local mc::cat_local(..) | // L-Local mc::cat_arg(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base) | mc::cat_deref(ref base, _, mc::OwnedPtr) | // L-Deref-Send mc::cat_interior(ref base, _) | // L-Field mc::cat_deref(ref base, _, mc::GcPtr) => { self.check(base, discr_scope) } mc::cat_discr(ref base, new_discr_scope) => { // Subtle: in a match, we must ensure that each binding // variable remains valid for the duration of the arm in // which it appears, presuming that this arm is taken. // But it is inconvenient in trans to root something just // for one arm. Therefore, we insert a cat_discr(),
// basically a special kind of category that says "if this // value must be dynamically rooted, root it for the scope // `match_id`". // // As an example, consider this scenario: // // let mut x = @Some(3); // match *x { Some(y) {...} None {...} } // // Technically, the value `x` need only be rooted // in the `some` arm. However, we evaluate `x` in trans // before we know what arm will be taken, so we just // always root it for the duration of the match. // // As a second example, consider *this* scenario: // // let x = @@Some(3); // match x { @@Some(y) {...} @@None {...} } // // Here again, `x` need only be rooted in the `some` arm. // In this case, the value which needs to be rooted is // found only when checking which pattern matches: but // this check is done before entering the arm. Therefore, // even in this case we just choose to keep the value // rooted for the entire match. This means the value will be // rooted even if the none arm is taken. Oh well. // // At first, I tried to optimize the second case to only // root in one arm, but the result was suboptimal: first, // it interfered with the construction of phi nodes in the // arm, as we were adding code to root values before the // phi nodes were added. This could have been addressed // with a second basic block. However, the naive approach // also yielded suboptimal results for patterns like: // // let x = @@...; // match x { @@some_variant(y) | @@some_other_variant(y) => // // The reason is that we would root the value once for // each pattern and not once per arm. This is also easily // fixed, but it's yet more code for what is really quite // the corner case. // // Nonetheless, if you decide to optimize this case in the // future, you need only adjust where the cat_discr() // node appears to draw the line between what will be rooted // in the *arm* vs the *match*. self.check(base, Some(new_discr_scope)) } } } fn check_scope(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `valid_scope` if!self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. // See the SCOPE(LV) function in doc.rs match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) | mc::cat_copied_upvar(_) => { ty::ReScope(self.item_scope_id) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) | mc::cat_arg(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt) | mc::cat_deref(ref cmt, _, mc::OwnedPtr) | mc::cat_deref(ref cmt, _, mc::GcPtr) | mc::cat_interior(ref cmt, _) | mc::cat_discr(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
random_line_split
borrowck-anon-fields-variant.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Tests that we are able to distinguish when loans borrow different // anonymous fields of an enum variant vs the same anonymous field. enum Foo { X, Y(uint, uint) } fn distinct_variant()
fn same_variant() { let mut y = Foo::Y(1, 2); let a = match y { Foo::Y(ref mut a, _) => a, Foo::X => panic!() }; let b = match y { Foo::Y(ref mut b, _) => b, //~ ERROR cannot borrow Foo::X => panic!() }; *a += 1; *b += 1; } fn main() { }
{ let mut y = Foo::Y(1, 2); let a = match y { Foo::Y(ref mut a, _) => a, Foo::X => panic!() }; let b = match y { Foo::Y(_, ref mut b) => b, Foo::X => panic!() }; *a += 1; *b += 1; }
identifier_body
borrowck-anon-fields-variant.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Tests that we are able to distinguish when loans borrow different // anonymous fields of an enum variant vs the same anonymous field. enum
{ X, Y(uint, uint) } fn distinct_variant() { let mut y = Foo::Y(1, 2); let a = match y { Foo::Y(ref mut a, _) => a, Foo::X => panic!() }; let b = match y { Foo::Y(_, ref mut b) => b, Foo::X => panic!() }; *a += 1; *b += 1; } fn same_variant() { let mut y = Foo::Y(1, 2); let a = match y { Foo::Y(ref mut a, _) => a, Foo::X => panic!() }; let b = match y { Foo::Y(ref mut b, _) => b, //~ ERROR cannot borrow Foo::X => panic!() }; *a += 1; *b += 1; } fn main() { }
Foo
identifier_name
borrowck-anon-fields-variant.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Tests that we are able to distinguish when loans borrow different // anonymous fields of an enum variant vs the same anonymous field. enum Foo { X, Y(uint, uint)
} fn distinct_variant() { let mut y = Foo::Y(1, 2); let a = match y { Foo::Y(ref mut a, _) => a, Foo::X => panic!() }; let b = match y { Foo::Y(_, ref mut b) => b, Foo::X => panic!() }; *a += 1; *b += 1; } fn same_variant() { let mut y = Foo::Y(1, 2); let a = match y { Foo::Y(ref mut a, _) => a, Foo::X => panic!() }; let b = match y { Foo::Y(ref mut b, _) => b, //~ ERROR cannot borrow Foo::X => panic!() }; *a += 1; *b += 1; } fn main() { }
random_line_split
mod.rs
//! Loaders for osci memory images. pub mod rawloader; pub mod hexloader; use std::{error, fmt, io, num, result}; use std::string::String; #[derive(Debug)] /// Error type for all loaders. /// /// `LoadError` is just a union-type over a couple of built-in errors with the `From` trait implemented for each of them. This makes implementing loaders more convenient due to the `try!` macro and the `?` operator. /// /// The `None` is mostly available to be used with `std::result::Result.ok_or()`. pub enum LoadError { None, IoErr(io::Error), ParseIntErr(num::ParseIntError), FormatErr(fmt::Error), Message(String), } impl LoadError { pub fn new() -> LoadError { LoadError::None } pub fn
(msg: String) -> LoadError { LoadError::Message(msg) } } impl fmt::Display for LoadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Loading failed") } } impl error::Error for LoadError { fn description(&self) -> &str { match self { &LoadError::None => &"Loading failed", &LoadError::Message(ref str) => str, &LoadError::IoErr(ref err) => err.description(), &LoadError::ParseIntErr(ref err) => err.description(), &LoadError::FormatErr(ref err) => err.description(), } } fn cause(&self) -> Option<&error::Error> { match self { &LoadError::IoErr(ref err) => Some(err), &LoadError::ParseIntErr(ref err) => Some(err), &LoadError::FormatErr(ref err) => Some(err), _ => None, } } } impl From<io::Error> for LoadError { fn from(err: io::Error) -> Self { LoadError::IoErr(err) } } impl From<num::ParseIntError> for LoadError { fn from(err: num::ParseIntError) -> Self { LoadError::ParseIntErr(err) } } impl From<fmt::Error> for LoadError { fn from(err: fmt::Error) -> Self { LoadError::FormatErr(err) } } pub type Result<T> = result::Result<T, LoadError>;
from_message
identifier_name
mod.rs
//! Loaders for osci memory images. pub mod rawloader; pub mod hexloader; use std::{error, fmt, io, num, result}; use std::string::String; #[derive(Debug)] /// Error type for all loaders. /// /// `LoadError` is just a union-type over a couple of built-in errors with the `From` trait implemented for each of them. This makes implementing loaders more convenient due to the `try!` macro and the `?` operator. /// /// The `None` is mostly available to be used with `std::result::Result.ok_or()`. pub enum LoadError { None,
} impl LoadError { pub fn new() -> LoadError { LoadError::None } pub fn from_message(msg: String) -> LoadError { LoadError::Message(msg) } } impl fmt::Display for LoadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Loading failed") } } impl error::Error for LoadError { fn description(&self) -> &str { match self { &LoadError::None => &"Loading failed", &LoadError::Message(ref str) => str, &LoadError::IoErr(ref err) => err.description(), &LoadError::ParseIntErr(ref err) => err.description(), &LoadError::FormatErr(ref err) => err.description(), } } fn cause(&self) -> Option<&error::Error> { match self { &LoadError::IoErr(ref err) => Some(err), &LoadError::ParseIntErr(ref err) => Some(err), &LoadError::FormatErr(ref err) => Some(err), _ => None, } } } impl From<io::Error> for LoadError { fn from(err: io::Error) -> Self { LoadError::IoErr(err) } } impl From<num::ParseIntError> for LoadError { fn from(err: num::ParseIntError) -> Self { LoadError::ParseIntErr(err) } } impl From<fmt::Error> for LoadError { fn from(err: fmt::Error) -> Self { LoadError::FormatErr(err) } } pub type Result<T> = result::Result<T, LoadError>;
IoErr(io::Error), ParseIntErr(num::ParseIntError), FormatErr(fmt::Error), Message(String),
random_line_split
mod.rs
//! Loaders for osci memory images. pub mod rawloader; pub mod hexloader; use std::{error, fmt, io, num, result}; use std::string::String; #[derive(Debug)] /// Error type for all loaders. /// /// `LoadError` is just a union-type over a couple of built-in errors with the `From` trait implemented for each of them. This makes implementing loaders more convenient due to the `try!` macro and the `?` operator. /// /// The `None` is mostly available to be used with `std::result::Result.ok_or()`. pub enum LoadError { None, IoErr(io::Error), ParseIntErr(num::ParseIntError), FormatErr(fmt::Error), Message(String), } impl LoadError { pub fn new() -> LoadError { LoadError::None } pub fn from_message(msg: String) -> LoadError
} impl fmt::Display for LoadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Loading failed") } } impl error::Error for LoadError { fn description(&self) -> &str { match self { &LoadError::None => &"Loading failed", &LoadError::Message(ref str) => str, &LoadError::IoErr(ref err) => err.description(), &LoadError::ParseIntErr(ref err) => err.description(), &LoadError::FormatErr(ref err) => err.description(), } } fn cause(&self) -> Option<&error::Error> { match self { &LoadError::IoErr(ref err) => Some(err), &LoadError::ParseIntErr(ref err) => Some(err), &LoadError::FormatErr(ref err) => Some(err), _ => None, } } } impl From<io::Error> for LoadError { fn from(err: io::Error) -> Self { LoadError::IoErr(err) } } impl From<num::ParseIntError> for LoadError { fn from(err: num::ParseIntError) -> Self { LoadError::ParseIntErr(err) } } impl From<fmt::Error> for LoadError { fn from(err: fmt::Error) -> Self { LoadError::FormatErr(err) } } pub type Result<T> = result::Result<T, LoadError>;
{ LoadError::Message(msg) }
identifier_body
grid.rs
pub struct Grid { pub grid: [[bool;1000];1000] } impl Grid { /// Turns on all lights from x,y through x,y in the grid. pub fn turn_on(&mut self, start: [usize;2], stop: [usize;2]) { for x in start[0]..stop[0]+1 { for y in start[1]..stop[1]+1 { self.grid[x][y] = true; } } } /// Turns off all lights from x,y through x,y in the grid. pub fn turn_off(&mut self, start: [usize;2], stop: [usize;2]) { for x in start[0]..stop[0]+1 { for y in start[1]..stop[1]+1 { self.grid[x][y] = false; } } } /// Toggles lights from x,y through x,y in the grid so that lights that were on are off, and /// lights that were off are now on. pub fn
(&mut self, start: [usize;2], stop: [usize;2]) { for x in start[0]..stop[0]+1 { for y in start[1]..stop[1]+1 { self.grid[x][y] =!self.grid[x][y]; } } } /// Counts the total number of lights turned on in the grid. pub fn turned_on_count(&self) -> usize { self.grid.iter().map(|column| column.iter().filter(|&x| *x == true).count()) .fold(0, |total, next| total + next) } }
toggle
identifier_name
grid.rs
pub struct Grid { pub grid: [[bool;1000];1000] } impl Grid { /// Turns on all lights from x,y through x,y in the grid. pub fn turn_on(&mut self, start: [usize;2], stop: [usize;2]) { for x in start[0]..stop[0]+1 { for y in start[1]..stop[1]+1 { self.grid[x][y] = true; } } } /// Turns off all lights from x,y through x,y in the grid. pub fn turn_off(&mut self, start: [usize;2], stop: [usize;2]) { for x in start[0]..stop[0]+1 { for y in start[1]..stop[1]+1 { self.grid[x][y] = false; } } } /// Toggles lights from x,y through x,y in the grid so that lights that were on are off, and /// lights that were off are now on. pub fn toggle(&mut self, start: [usize;2], stop: [usize;2])
/// Counts the total number of lights turned on in the grid. pub fn turned_on_count(&self) -> usize { self.grid.iter().map(|column| column.iter().filter(|&x| *x == true).count()) .fold(0, |total, next| total + next) } }
{ for x in start[0]..stop[0]+1 { for y in start[1]..stop[1]+1 { self.grid[x][y] = !self.grid[x][y]; } } }
identifier_body
grid.rs
pub struct Grid { pub grid: [[bool;1000];1000] } impl Grid { /// Turns on all lights from x,y through x,y in the grid.
pub fn turn_on(&mut self, start: [usize;2], stop: [usize;2]) { for x in start[0]..stop[0]+1 { for y in start[1]..stop[1]+1 { self.grid[x][y] = true; } } } /// Turns off all lights from x,y through x,y in the grid. pub fn turn_off(&mut self, start: [usize;2], stop: [usize;2]) { for x in start[0]..stop[0]+1 { for y in start[1]..stop[1]+1 { self.grid[x][y] = false; } } } /// Toggles lights from x,y through x,y in the grid so that lights that were on are off, and /// lights that were off are now on. pub fn toggle(&mut self, start: [usize;2], stop: [usize;2]) { for x in start[0]..stop[0]+1 { for y in start[1]..stop[1]+1 { self.grid[x][y] =!self.grid[x][y]; } } } /// Counts the total number of lights turned on in the grid. pub fn turned_on_count(&self) -> usize { self.grid.iter().map(|column| column.iter().filter(|&x| *x == true).count()) .fold(0, |total, next| total + next) } }
random_line_split
build.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. extern crate vergen; extern crate rustc_version; use std::env; use std::fs::File; use std::io::Write; use std::path::Path; use vergen::*; fn
() { vergen(OutputFns::all()).unwrap(); let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("rustc_version.rs"); let mut f = File::create(&dest_path).unwrap(); f.write_all( format!( " /// Returns compiler version. pub fn rustc_version() -> &'static str {{ \"{}\" }} ", rustc_version::version() ) .as_bytes(), ) .unwrap(); }
main
identifier_name
build.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>.
extern crate rustc_version; use std::env; use std::fs::File; use std::io::Write; use std::path::Path; use vergen::*; fn main() { vergen(OutputFns::all()).unwrap(); let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("rustc_version.rs"); let mut f = File::create(&dest_path).unwrap(); f.write_all( format!( " /// Returns compiler version. pub fn rustc_version() -> &'static str {{ \"{}\" }} ", rustc_version::version() ) .as_bytes(), ) .unwrap(); }
extern crate vergen;
random_line_split
build.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. extern crate vergen; extern crate rustc_version; use std::env; use std::fs::File; use std::io::Write; use std::path::Path; use vergen::*; fn main()
{ vergen(OutputFns::all()).unwrap(); let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("rustc_version.rs"); let mut f = File::create(&dest_path).unwrap(); f.write_all( format!( " /// Returns compiler version. pub fn rustc_version() -> &'static str {{ \"{}\" }} ", rustc_version::version() ) .as_bytes(), ) .unwrap(); }
identifier_body
set_mana.rs
use rune_vm::Rune; use rustc_serialize::json; use game_state::GameState; use minion_card::UID; use hlua; #[derive(RustcDecodable, RustcEncodable, Clone, Debug)] pub struct SetMana { controller_uid: UID, mana: u8, } implement_for_lua!(SetMana, |mut _metatable| {}); impl SetMana { pub fn new(controller_uid: UID, mana: u8) -> SetMana { SetMana { controller_uid: controller_uid, mana: mana, } } pub fn to_rune(&self) -> Box<Rune>
} impl Rune for SetMana { fn execute_rune(&self, game_state: &mut GameState) { game_state.get_mut_controller_by_uid(self.controller_uid).unwrap().set_mana(self.mana); } fn can_see(&self, _controller: UID, _game_state: &GameState) -> bool { return true; } fn to_json(&self) -> String { json::encode(self).unwrap().replace("{", "{\"runeType\":\"SetMana\",") } fn into_box(&self) -> Box<Rune> { Box::new(self.clone()) } }
{ Box::new(self.clone()) }
identifier_body
set_mana.rs
use rune_vm::Rune; use rustc_serialize::json; use game_state::GameState; use minion_card::UID; use hlua; #[derive(RustcDecodable, RustcEncodable, Clone, Debug)] pub struct SetMana { controller_uid: UID, mana: u8, } implement_for_lua!(SetMana, |mut _metatable| {}); impl SetMana { pub fn new(controller_uid: UID, mana: u8) -> SetMana { SetMana {
mana: mana, } } pub fn to_rune(&self) -> Box<Rune> { Box::new(self.clone()) } } impl Rune for SetMana { fn execute_rune(&self, game_state: &mut GameState) { game_state.get_mut_controller_by_uid(self.controller_uid).unwrap().set_mana(self.mana); } fn can_see(&self, _controller: UID, _game_state: &GameState) -> bool { return true; } fn to_json(&self) -> String { json::encode(self).unwrap().replace("{", "{\"runeType\":\"SetMana\",") } fn into_box(&self) -> Box<Rune> { Box::new(self.clone()) } }
controller_uid: controller_uid,
random_line_split
set_mana.rs
use rune_vm::Rune; use rustc_serialize::json; use game_state::GameState; use minion_card::UID; use hlua; #[derive(RustcDecodable, RustcEncodable, Clone, Debug)] pub struct SetMana { controller_uid: UID, mana: u8, } implement_for_lua!(SetMana, |mut _metatable| {}); impl SetMana { pub fn new(controller_uid: UID, mana: u8) -> SetMana { SetMana { controller_uid: controller_uid, mana: mana, } } pub fn to_rune(&self) -> Box<Rune> { Box::new(self.clone()) } } impl Rune for SetMana { fn execute_rune(&self, game_state: &mut GameState) { game_state.get_mut_controller_by_uid(self.controller_uid).unwrap().set_mana(self.mana); } fn can_see(&self, _controller: UID, _game_state: &GameState) -> bool { return true; } fn
(&self) -> String { json::encode(self).unwrap().replace("{", "{\"runeType\":\"SetMana\",") } fn into_box(&self) -> Box<Rune> { Box::new(self.clone()) } }
to_json
identifier_name
audioclient.rs
// Copyright © 2015-2017 winapi-rs developers // 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms //! this ALWAYS GENERATED file contains the definitions for the interfaces use shared::basetsd::{UINT32, UINT64}; use shared::guiddef::{LPCGUID, REFIID}; use shared::minwindef::{BYTE, DWORD, LPVOID}; use shared::mmreg::WAVEFORMATEX; use shared::winerror::{FACILITY_AUDCLNT, SEVERITY_ERROR, SEVERITY_SUCCESS}; use shared::wtypesbase::SCODE; use um::audiosessiontypes::AUDCLNT_SHAREMODE; use um::strmif::REFERENCE_TIME; use um::unknwnbase::{IUnknown, IUnknownVtbl}; use um::winnt::{HANDLE, HRESULT}; //1627 pub const AUDCLNT_E_NOT_INITIALIZED: HRESULT = AUDCLNT_ERR!(0x001); pub const AUDCLNT_E_ALREADY_INITIALIZED: HRESULT = AUDCLNT_ERR!(0x002); pub const AUDCLNT_E_WRONG_ENDPOINT_TYPE: HRESULT = AUDCLNT_ERR!(0x003); pub const AUDCLNT_E_DEVICE_INVALIDATED: HRESULT = AUDCLNT_ERR!(0x004); pub const AUDCLNT_E_NOT_STOPPED: HRESULT = AUDCLNT_ERR!(0x005); pub const AUDCLNT_E_BUFFER_TOO_LARGE: HRESULT = AUDCLNT_ERR!(0x006); pub const AUDCLNT_E_OUT_OF_ORDER: HRESULT = AUDCLNT_ERR!(0x007); pub const AUDCLNT_E_UNSUPPORTED_FORMAT: HRESULT = AUDCLNT_ERR!(0x008); pub const AUDCLNT_E_INVALID_SIZE: HRESULT = AUDCLNT_ERR!(0x009); pub const AUDCLNT_E_DEVICE_IN_USE: HRESULT = AUDCLNT_ERR!(0x00a); pub const AUDCLNT_E_BUFFER_OPERATION_PENDING: HRESULT = AUDCLNT_ERR!(0x00b); pub const AUDCLNT_E_THREAD_NOT_REGISTERED: HRESULT = AUDCLNT_ERR!(0x00c); pub const AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: HRESULT = AUDCLNT_ERR!(0x00e); pub const AUDCLNT_E_ENDPOINT_CREATE_FAILED: HRESULT = AUDCLNT_ERR!(0x00f); pub const AUDCLNT_E_SERVICE_NOT_RUNNING: HRESULT = AUDCLNT_ERR!(0x010); pub const AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: HRESULT = AUDCLNT_ERR!(0x011); pub const AUDCLNT_E_EXCLUSIVE_MODE_ONLY: HRESULT = AUDCLNT_ERR!(0x012); pub const AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: HRESULT = AUDCLNT_ERR!(0x013); pub const AUDCLNT_E_EVENTHANDLE_NOT_SET: HRESULT = AUDCLNT_ERR!(0x014); pub const AUDCLNT_E_INCORRECT_BUFFER_SIZE: HRESULT = AUDCLNT_ERR!(0x015); pub const AUDCLNT_E_BUFFER_SIZE_ERROR: HRESULT = AUDCLNT_ERR!(0x016); pub const AUDCLNT_E_CPUUSAGE_EXCEEDED: HRESULT = AUDCLNT_ERR!(0x017); pub const AUDCLNT_E_BUFFER_ERROR: HRESULT = AUDCLNT_ERR!(0x018); pub const AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED: HRESULT = AUDCLNT_ERR!(0x019); pub const AUDCLNT_E_INVALID_DEVICE_PERIOD: HRESULT = AUDCLNT_ERR!(0x020); pub const AUDCLNT_E_INVALID_STREAM_FLAG: HRESULT = AUDCLNT_ERR!(0x021); pub const AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE: HRESULT = AUDCLNT_ERR!(0x022); pub const AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES: HRESULT = AUDCLNT_ERR!(0x023); pub const AUDCLNT_E_OFFLOAD_MODE_ONLY: HRESULT = AUDCLNT_ERR!(0x024); pub const AUDCLNT_E_NONOFFLOAD_MODE_ONLY: HRESULT = AUDCLNT_ERR!(0x025); pub const AUDCLNT_E_RESOURCES_INVALIDATED: HRESULT = AUDCLNT_ERR!(0x026); pub const AUDCLNT_E_RAW_MODE_UNSUPPORTED: HRESULT = AUDCLNT_ERR!(0x027); pub const AUDCLNT_S_BUFFER_EMPTY: SCODE = AUDCLNT_SUCCESS!(0x001); pub const AUDCLNT_S_THREAD_ALREADY_REGISTERED: SCODE = AUDCLNT_SUCCESS!(0x002); pub const AUDCLNT_S_POSITION_STALLED: SCODE = AUDCLNT_SUCCESS!(0x003); DEFINE_GUID!{IID_IAudioClient, 0x1CB9AD4C, 0xDBFA, 0x4c32, 0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2} DEFINE_GUID!{IID_IAudioRenderClient, 0xF294ACFC, 0x3146, 0x4483, 0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2} DEFINE_GUID!{IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17} RIDL!{#[uuid(0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2)] interface IAudioClient(IAudioClientVtbl): IUnknown(IUnknownVtbl) { fn Initialize( ShareMode: AUDCLNT_SHAREMODE, StreamFlags: DWORD, hnsBufferDuration: REFERENCE_TIME, hnsPeriodicity: REFERENCE_TIME, pFormat: *const WAVEFORMATEX, AudioSessionGuid: LPCGUID, ) -> HRESULT, fn GetBufferSize( pNumBufferFrames: *mut UINT32, ) -> HRESULT, fn GetStreamLatency( phnsLatency: *mut REFERENCE_TIME, ) -> HRESULT, fn GetCurrentPadding( pNumPaddingFrames: *mut UINT32, ) -> HRESULT, fn IsFormatSupported( ShareMode: AUDCLNT_SHAREMODE, pFormat: *const WAVEFORMATEX, ppClosestMatch: *mut *mut WAVEFORMATEX, ) -> HRESULT, fn GetMixFormat( ppDeviceFormat: *mut *mut WAVEFORMATEX, ) -> HRESULT, fn GetDevicePeriod( phnsDefaultDevicePeriod: *mut REFERENCE_TIME, phnsMinimumDevicePeriod: *mut REFERENCE_TIME, ) -> HRESULT, fn Start() -> HRESULT, fn Stop() -> HRESULT, fn Reset() -> HRESULT, fn SetEventHandle( eventHandle: HANDLE, ) -> HRESULT, fn GetService( riid: REFIID, ppv: *mut LPVOID, ) -> HRESULT, }} RIDL!{#[uuid(0xf294acfc, 0x3146, 0x4483, 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2)] interface IAudioRenderClient(IAudioRenderClientVtbl): IUnknown(IUnknownVtbl) { fn GetBuffer( NumFramesRequested: UINT32, ppData: *mut *mut BYTE, ) -> HRESULT, fn ReleaseBuffer( NumFramesWritten: UINT32, dwFlags: DWORD, ) -> HRESULT, }} RIDL!{#[uuid(0xc8adbd64, 0xe71e, 0x48a0, 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17)]
pdwFlags: *mut DWORD, pu64DevicePosition: *mut UINT64, pu64QPCPosition: *mut UINT64, ) -> HRESULT, fn ReleaseBuffer( NumFramesRead: UINT32, ) -> HRESULT, fn GetNextPacketSize( pNumFramesInNextPacket: *mut UINT32, ) -> HRESULT, }}
interface IAudioCaptureClient(IAudioCaptureClientVtbl): IUnknown(IUnknownVtbl) { fn GetBuffer( ppData: *mut *mut BYTE, pNumFramesToRead: *mut UINT32,
random_line_split
int_rect.rs
use math::IntVector; use sdl2::rect::Rect as SdlRect; #[derive(Debug, Copy, PartialEq, Clone)] pub struct IntRect { pub xy: IntVector, pub width: u32, pub height: u32, } impl IntRect { fn new(x: i32, y: i32, width: u32, height: u32) -> IntRect { IntRect { xy: IntVector::new(x, y), width: width, height: height, } } pub fn x(&self) -> i32 { self.xy.x } pub fn y(&self) -> i32 { self.xy.y } pub fn width(&self) -> u32 { self.width } pub fn height(&self) -> u32 { self.height } } impl From<SdlRect> for IntRect { fn from(sdl_rect: SdlRect) -> IntRect { IntRect::new(sdl_rect.x(), sdl_rect.y(), sdl_rect.width(), sdl_rect.height()) } } impl From<IntRect> for SdlRect { fn from(int_rect: IntRect) -> SdlRect { SdlRect::new(int_rect.x(), int_rect.y(), int_rect.width(), int_rect.height()) }
}
random_line_split
int_rect.rs
use math::IntVector; use sdl2::rect::Rect as SdlRect; #[derive(Debug, Copy, PartialEq, Clone)] pub struct IntRect { pub xy: IntVector, pub width: u32, pub height: u32, } impl IntRect { fn new(x: i32, y: i32, width: u32, height: u32) -> IntRect { IntRect { xy: IntVector::new(x, y), width: width, height: height, } } pub fn x(&self) -> i32 { self.xy.x } pub fn y(&self) -> i32
pub fn width(&self) -> u32 { self.width } pub fn height(&self) -> u32 { self.height } } impl From<SdlRect> for IntRect { fn from(sdl_rect: SdlRect) -> IntRect { IntRect::new(sdl_rect.x(), sdl_rect.y(), sdl_rect.width(), sdl_rect.height()) } } impl From<IntRect> for SdlRect { fn from(int_rect: IntRect) -> SdlRect { SdlRect::new(int_rect.x(), int_rect.y(), int_rect.width(), int_rect.height()) } }
{ self.xy.y }
identifier_body
int_rect.rs
use math::IntVector; use sdl2::rect::Rect as SdlRect; #[derive(Debug, Copy, PartialEq, Clone)] pub struct IntRect { pub xy: IntVector, pub width: u32, pub height: u32, } impl IntRect { fn new(x: i32, y: i32, width: u32, height: u32) -> IntRect { IntRect { xy: IntVector::new(x, y), width: width, height: height, } } pub fn x(&self) -> i32 { self.xy.x } pub fn y(&self) -> i32 { self.xy.y } pub fn width(&self) -> u32 { self.width } pub fn height(&self) -> u32 { self.height } } impl From<SdlRect> for IntRect { fn from(sdl_rect: SdlRect) -> IntRect { IntRect::new(sdl_rect.x(), sdl_rect.y(), sdl_rect.width(), sdl_rect.height()) } } impl From<IntRect> for SdlRect { fn
(int_rect: IntRect) -> SdlRect { SdlRect::new(int_rect.x(), int_rect.y(), int_rect.width(), int_rect.height()) } }
from
identifier_name
decodable.rs
// Copyright 2012-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. //! The compiler code necessary for `#[deriving(Decodable)]`. See encodable.rs for more. use ast; use ast::{MetaItem, Item, Expr, MutMutable}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use parse::token; use ptr::P; pub fn expand_deriving_decodable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: |P<Item>|) { let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new_(vec!("serialize", "Decodable"), None, vec!(box Literal(Path::new_local("__D")), box Literal(Path::new_local("__E"))), true), additional_bounds: Vec::new(), generics: LifetimeBounds { lifetimes: Vec::new(), bounds: vec!(("__D", None, vec!(Path::new_( vec!("serialize", "Decoder"), None, vec!(box Literal(Path::new_local("__E"))), true))), ("__E", None, vec!())) }, methods: vec!( MethodDef { name: "decode", generics: LifetimeBounds::empty(), explicit_self: None, args: vec!(Ptr(box Literal(Path::new_local("__D")), Borrowed(None, MutMutable))), ret_ty: Literal(Path::new_(vec!("std", "result", "Result"), None, vec!(box Self, box Literal(Path::new_local("__E"))), true)), attributes: Vec::new(), combine_substructure: combine_substructure(|a, b, c| { decodable_substructure(a, b, c) }), }) }; trait_def.expand(cx, mitem, item, push) } fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr>
let result = decode_static_fields(cx, trait_span, path, summary, |cx, span, name, field| { cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), read_struct_field, vec!(cx.expr_str(span, name), cx.expr_uint(span, field), lambdadecode.clone()))) }); let result = cx.expr_ok(trait_span, result); cx.expr_method_call(trait_span, decoder, cx.ident_of("read_struct"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), cx.expr_uint(trait_span, nfields), cx.lambda_expr_1(trait_span, result, blkarg) )) } StaticEnum(_, ref fields) => { let variant = cx.ident_of("i"); let mut arms = Vec::new(); let mut variants = Vec::new(); let rvariant_arg = cx.ident_of("read_enum_variant_arg"); for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() { variants.push(cx.expr_str(v_span, token::get_ident(name))); let path = cx.path(trait_span, vec![substr.type_ident, name]); let decoded = decode_static_fields(cx, v_span, path, parts, |cx, span, _, field| { let idx = cx.expr_uint(span, field); cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg, vec!(idx, lambdadecode.clone()))) }); arms.push(cx.arm(v_span, vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))), decoded)); } arms.push(cx.arm_unreachable(trait_span)); let result = cx.expr_ok(trait_span, cx.expr_match(trait_span, cx.expr_ident(trait_span, variant), arms)); let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result); let variant_vec = cx.expr_vec(trait_span, variants); let variant_vec = cx.expr_addr_of(trait_span, variant_vec); let result = cx.expr_method_call(trait_span, blkdecoder, cx.ident_of("read_enum_variant"), vec!(variant_vec, lambda)); cx.expr_method_call(trait_span, decoder, cx.ident_of("read_enum"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), cx.lambda_expr_1(trait_span, result, blkarg) )) } _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)") }; } /// Create a decoder for a single enum variant/struct: /// - `outer_pat_path` is the path to this enum variant/struct /// - `getarg` should retrieve the `uint`-th field with name `@str`. fn decode_static_fields(cx: &mut ExtCtxt, trait_span: Span, outer_pat_path: ast::Path, fields: &StaticFields, getarg: |&mut ExtCtxt, Span, InternedString, uint| -> P<Expr>) -> P<Expr> { match *fields { Unnamed(ref fields) => { let path_expr = cx.expr_path(outer_pat_path); if fields.is_empty() { path_expr } else { let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(cx, span, token::intern_and_get_ident(format!("_field{}", i).as_slice()), i) }).collect(); cx.expr_call(trait_span, path_expr, fields) } } Named(ref fields) => { // use the field's span to get nicer error messages. let fields = fields.iter().enumerate().map(|(i, &(name, span))| { let arg = getarg(cx, span, token::get_ident(name), i); cx.field_imm(span, name, arg) }).collect(); cx.expr_struct(trait_span, outer_pat_path, fields) } } }
{ let decoder = substr.nonself_args[0].clone(); let recurse = vec!(cx.ident_of("serialize"), cx.ident_of("Decodable"), cx.ident_of("decode")); // throw an underscore in front to suppress unused variable warnings let blkarg = cx.ident_of("_d"); let blkdecoder = cx.expr_ident(trait_span, blkarg); let calldecode = cx.expr_call_global(trait_span, recurse, vec!(blkdecoder.clone())); let lambdadecode = cx.lambda_expr_1(trait_span, calldecode, blkarg); return match *substr.fields { StaticStruct(_, ref summary) => { let nfields = match *summary { Unnamed(ref fields) => fields.len(), Named(ref fields) => fields.len() }; let read_struct_field = cx.ident_of("read_struct_field"); let path = cx.path_ident(trait_span, substr.type_ident);
identifier_body
decodable.rs
// Copyright 2012-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. //! The compiler code necessary for `#[deriving(Decodable)]`. See encodable.rs for more. use ast; use ast::{MetaItem, Item, Expr, MutMutable}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use parse::token; use ptr::P; pub fn expand_deriving_decodable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: |P<Item>|) { let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new_(vec!("serialize", "Decodable"), None, vec!(box Literal(Path::new_local("__D")), box Literal(Path::new_local("__E"))), true), additional_bounds: Vec::new(), generics: LifetimeBounds { lifetimes: Vec::new(), bounds: vec!(("__D", None, vec!(Path::new_( vec!("serialize", "Decoder"), None, vec!(box Literal(Path::new_local("__E"))), true))), ("__E", None, vec!())) }, methods: vec!( MethodDef { name: "decode", generics: LifetimeBounds::empty(), explicit_self: None, args: vec!(Ptr(box Literal(Path::new_local("__D")), Borrowed(None, MutMutable))), ret_ty: Literal(Path::new_(vec!("std", "result", "Result"), None, vec!(box Self, box Literal(Path::new_local("__E"))), true)), attributes: Vec::new(), combine_substructure: combine_substructure(|a, b, c| { decodable_substructure(a, b, c) }), }) }; trait_def.expand(cx, mitem, item, push) } fn
(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let decoder = substr.nonself_args[0].clone(); let recurse = vec!(cx.ident_of("serialize"), cx.ident_of("Decodable"), cx.ident_of("decode")); // throw an underscore in front to suppress unused variable warnings let blkarg = cx.ident_of("_d"); let blkdecoder = cx.expr_ident(trait_span, blkarg); let calldecode = cx.expr_call_global(trait_span, recurse, vec!(blkdecoder.clone())); let lambdadecode = cx.lambda_expr_1(trait_span, calldecode, blkarg); return match *substr.fields { StaticStruct(_, ref summary) => { let nfields = match *summary { Unnamed(ref fields) => fields.len(), Named(ref fields) => fields.len() }; let read_struct_field = cx.ident_of("read_struct_field"); let path = cx.path_ident(trait_span, substr.type_ident); let result = decode_static_fields(cx, trait_span, path, summary, |cx, span, name, field| { cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), read_struct_field, vec!(cx.expr_str(span, name), cx.expr_uint(span, field), lambdadecode.clone()))) }); let result = cx.expr_ok(trait_span, result); cx.expr_method_call(trait_span, decoder, cx.ident_of("read_struct"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), cx.expr_uint(trait_span, nfields), cx.lambda_expr_1(trait_span, result, blkarg) )) } StaticEnum(_, ref fields) => { let variant = cx.ident_of("i"); let mut arms = Vec::new(); let mut variants = Vec::new(); let rvariant_arg = cx.ident_of("read_enum_variant_arg"); for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() { variants.push(cx.expr_str(v_span, token::get_ident(name))); let path = cx.path(trait_span, vec![substr.type_ident, name]); let decoded = decode_static_fields(cx, v_span, path, parts, |cx, span, _, field| { let idx = cx.expr_uint(span, field); cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg, vec!(idx, lambdadecode.clone()))) }); arms.push(cx.arm(v_span, vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))), decoded)); } arms.push(cx.arm_unreachable(trait_span)); let result = cx.expr_ok(trait_span, cx.expr_match(trait_span, cx.expr_ident(trait_span, variant), arms)); let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result); let variant_vec = cx.expr_vec(trait_span, variants); let variant_vec = cx.expr_addr_of(trait_span, variant_vec); let result = cx.expr_method_call(trait_span, blkdecoder, cx.ident_of("read_enum_variant"), vec!(variant_vec, lambda)); cx.expr_method_call(trait_span, decoder, cx.ident_of("read_enum"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), cx.lambda_expr_1(trait_span, result, blkarg) )) } _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)") }; } /// Create a decoder for a single enum variant/struct: /// - `outer_pat_path` is the path to this enum variant/struct /// - `getarg` should retrieve the `uint`-th field with name `@str`. fn decode_static_fields(cx: &mut ExtCtxt, trait_span: Span, outer_pat_path: ast::Path, fields: &StaticFields, getarg: |&mut ExtCtxt, Span, InternedString, uint| -> P<Expr>) -> P<Expr> { match *fields { Unnamed(ref fields) => { let path_expr = cx.expr_path(outer_pat_path); if fields.is_empty() { path_expr } else { let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(cx, span, token::intern_and_get_ident(format!("_field{}", i).as_slice()), i) }).collect(); cx.expr_call(trait_span, path_expr, fields) } } Named(ref fields) => { // use the field's span to get nicer error messages. let fields = fields.iter().enumerate().map(|(i, &(name, span))| { let arg = getarg(cx, span, token::get_ident(name), i); cx.field_imm(span, name, arg) }).collect(); cx.expr_struct(trait_span, outer_pat_path, fields) } } }
decodable_substructure
identifier_name
decodable.rs
// Copyright 2012-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. //! The compiler code necessary for `#[deriving(Decodable)]`. See encodable.rs for more. use ast; use ast::{MetaItem, Item, Expr, MutMutable}; use codemap::Span;
use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use parse::token; use ptr::P; pub fn expand_deriving_decodable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: |P<Item>|) { let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new_(vec!("serialize", "Decodable"), None, vec!(box Literal(Path::new_local("__D")), box Literal(Path::new_local("__E"))), true), additional_bounds: Vec::new(), generics: LifetimeBounds { lifetimes: Vec::new(), bounds: vec!(("__D", None, vec!(Path::new_( vec!("serialize", "Decoder"), None, vec!(box Literal(Path::new_local("__E"))), true))), ("__E", None, vec!())) }, methods: vec!( MethodDef { name: "decode", generics: LifetimeBounds::empty(), explicit_self: None, args: vec!(Ptr(box Literal(Path::new_local("__D")), Borrowed(None, MutMutable))), ret_ty: Literal(Path::new_(vec!("std", "result", "Result"), None, vec!(box Self, box Literal(Path::new_local("__E"))), true)), attributes: Vec::new(), combine_substructure: combine_substructure(|a, b, c| { decodable_substructure(a, b, c) }), }) }; trait_def.expand(cx, mitem, item, push) } fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let decoder = substr.nonself_args[0].clone(); let recurse = vec!(cx.ident_of("serialize"), cx.ident_of("Decodable"), cx.ident_of("decode")); // throw an underscore in front to suppress unused variable warnings let blkarg = cx.ident_of("_d"); let blkdecoder = cx.expr_ident(trait_span, blkarg); let calldecode = cx.expr_call_global(trait_span, recurse, vec!(blkdecoder.clone())); let lambdadecode = cx.lambda_expr_1(trait_span, calldecode, blkarg); return match *substr.fields { StaticStruct(_, ref summary) => { let nfields = match *summary { Unnamed(ref fields) => fields.len(), Named(ref fields) => fields.len() }; let read_struct_field = cx.ident_of("read_struct_field"); let path = cx.path_ident(trait_span, substr.type_ident); let result = decode_static_fields(cx, trait_span, path, summary, |cx, span, name, field| { cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), read_struct_field, vec!(cx.expr_str(span, name), cx.expr_uint(span, field), lambdadecode.clone()))) }); let result = cx.expr_ok(trait_span, result); cx.expr_method_call(trait_span, decoder, cx.ident_of("read_struct"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), cx.expr_uint(trait_span, nfields), cx.lambda_expr_1(trait_span, result, blkarg) )) } StaticEnum(_, ref fields) => { let variant = cx.ident_of("i"); let mut arms = Vec::new(); let mut variants = Vec::new(); let rvariant_arg = cx.ident_of("read_enum_variant_arg"); for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() { variants.push(cx.expr_str(v_span, token::get_ident(name))); let path = cx.path(trait_span, vec![substr.type_ident, name]); let decoded = decode_static_fields(cx, v_span, path, parts, |cx, span, _, field| { let idx = cx.expr_uint(span, field); cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg, vec!(idx, lambdadecode.clone()))) }); arms.push(cx.arm(v_span, vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))), decoded)); } arms.push(cx.arm_unreachable(trait_span)); let result = cx.expr_ok(trait_span, cx.expr_match(trait_span, cx.expr_ident(trait_span, variant), arms)); let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result); let variant_vec = cx.expr_vec(trait_span, variants); let variant_vec = cx.expr_addr_of(trait_span, variant_vec); let result = cx.expr_method_call(trait_span, blkdecoder, cx.ident_of("read_enum_variant"), vec!(variant_vec, lambda)); cx.expr_method_call(trait_span, decoder, cx.ident_of("read_enum"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), cx.lambda_expr_1(trait_span, result, blkarg) )) } _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)") }; } /// Create a decoder for a single enum variant/struct: /// - `outer_pat_path` is the path to this enum variant/struct /// - `getarg` should retrieve the `uint`-th field with name `@str`. fn decode_static_fields(cx: &mut ExtCtxt, trait_span: Span, outer_pat_path: ast::Path, fields: &StaticFields, getarg: |&mut ExtCtxt, Span, InternedString, uint| -> P<Expr>) -> P<Expr> { match *fields { Unnamed(ref fields) => { let path_expr = cx.expr_path(outer_pat_path); if fields.is_empty() { path_expr } else { let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(cx, span, token::intern_and_get_ident(format!("_field{}", i).as_slice()), i) }).collect(); cx.expr_call(trait_span, path_expr, fields) } } Named(ref fields) => { // use the field's span to get nicer error messages. let fields = fields.iter().enumerate().map(|(i, &(name, span))| { let arg = getarg(cx, span, token::get_ident(name), i); cx.field_imm(span, name, arg) }).collect(); cx.expr_struct(trait_span, outer_pat_path, fields) } } }
use ext::base::ExtCtxt;
random_line_split
process.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Unix-specific extensions to primitives in the `std::process` module. #![stable(feature = "rust1", since = "1.0.0")] use os::unix::raw::{uid_t, gid_t}; use os::unix::io::{FromRawFd, RawFd, AsRawFd}; use prelude::v1::*; use process; use sys; use sys_common::{AsInnerMut, AsInner, FromInner}; /// Unix-specific extensions to the `std::process::Command` builder #[stable(feature = "rust1", since = "1.0.0")] pub trait CommandExt { /// Sets the child process's user id. This translates to a /// `setuid` call in the child process. Failure in the `setuid` /// call will cause the spawn to fail. #[stable(feature = "rust1", since = "1.0.0")] fn uid(&mut self, id: uid_t) -> &mut process::Command; /// Similar to `uid`, but sets the group id of the child process. This has /// the same semantics as the `uid` field. #[stable(feature = "rust1", since = "1.0.0")] fn gid(&mut self, id: gid_t) -> &mut process::Command; } #[stable(feature = "rust1", since = "1.0.0")] impl CommandExt for process::Command { fn uid(&mut self, id: uid_t) -> &mut process::Command { self.as_inner_mut().uid = Some(id); self } fn gid(&mut self, id: gid_t) -> &mut process::Command { self.as_inner_mut().gid = Some(id); self } } /// Unix-specific extensions to `std::process::ExitStatus` #[stable(feature = "rust1", since = "1.0.0")] pub trait ExitStatusExt { /// If the process was terminated by a signal, returns that signal. #[stable(feature = "rust1", since = "1.0.0")] fn signal(&self) -> Option<i32>; } #[stable(feature = "rust1", since = "1.0.0")] impl ExitStatusExt for process::ExitStatus { fn signal(&self) -> Option<i32>
} #[stable(feature = "process_extensions", since = "1.2.0")] impl FromRawFd for process::Stdio { unsafe fn from_raw_fd(fd: RawFd) -> process::Stdio { process::Stdio::from_inner(sys::fd::FileDesc::new(fd)) } } #[stable(feature = "process_extensions", since = "1.2.0")] impl AsRawFd for process::ChildStdin { fn as_raw_fd(&self) -> RawFd { self.as_inner().fd().raw() } } #[stable(feature = "process_extensions", since = "1.2.0")] impl AsRawFd for process::ChildStdout { fn as_raw_fd(&self) -> RawFd { self.as_inner().fd().raw() } } #[stable(feature = "process_extensions", since = "1.2.0")] impl AsRawFd for process::ChildStderr { fn as_raw_fd(&self) -> RawFd { self.as_inner().fd().raw() } }
{ match *self.as_inner() { sys::process::ExitStatus::Signal(s) => Some(s), _ => None } }
identifier_body
process.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// except according to those terms. //! Unix-specific extensions to primitives in the `std::process` module. #![stable(feature = "rust1", since = "1.0.0")] use os::unix::raw::{uid_t, gid_t}; use os::unix::io::{FromRawFd, RawFd, AsRawFd}; use prelude::v1::*; use process; use sys; use sys_common::{AsInnerMut, AsInner, FromInner}; /// Unix-specific extensions to the `std::process::Command` builder #[stable(feature = "rust1", since = "1.0.0")] pub trait CommandExt { /// Sets the child process's user id. This translates to a /// `setuid` call in the child process. Failure in the `setuid` /// call will cause the spawn to fail. #[stable(feature = "rust1", since = "1.0.0")] fn uid(&mut self, id: uid_t) -> &mut process::Command; /// Similar to `uid`, but sets the group id of the child process. This has /// the same semantics as the `uid` field. #[stable(feature = "rust1", since = "1.0.0")] fn gid(&mut self, id: gid_t) -> &mut process::Command; } #[stable(feature = "rust1", since = "1.0.0")] impl CommandExt for process::Command { fn uid(&mut self, id: uid_t) -> &mut process::Command { self.as_inner_mut().uid = Some(id); self } fn gid(&mut self, id: gid_t) -> &mut process::Command { self.as_inner_mut().gid = Some(id); self } } /// Unix-specific extensions to `std::process::ExitStatus` #[stable(feature = "rust1", since = "1.0.0")] pub trait ExitStatusExt { /// If the process was terminated by a signal, returns that signal. #[stable(feature = "rust1", since = "1.0.0")] fn signal(&self) -> Option<i32>; } #[stable(feature = "rust1", since = "1.0.0")] impl ExitStatusExt for process::ExitStatus { fn signal(&self) -> Option<i32> { match *self.as_inner() { sys::process::ExitStatus::Signal(s) => Some(s), _ => None } } } #[stable(feature = "process_extensions", since = "1.2.0")] impl FromRawFd for process::Stdio { unsafe fn from_raw_fd(fd: RawFd) -> process::Stdio { process::Stdio::from_inner(sys::fd::FileDesc::new(fd)) } } #[stable(feature = "process_extensions", since = "1.2.0")] impl AsRawFd for process::ChildStdin { fn as_raw_fd(&self) -> RawFd { self.as_inner().fd().raw() } } #[stable(feature = "process_extensions", since = "1.2.0")] impl AsRawFd for process::ChildStdout { fn as_raw_fd(&self) -> RawFd { self.as_inner().fd().raw() } } #[stable(feature = "process_extensions", since = "1.2.0")] impl AsRawFd for process::ChildStderr { fn as_raw_fd(&self) -> RawFd { self.as_inner().fd().raw() } }
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
process.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Unix-specific extensions to primitives in the `std::process` module. #![stable(feature = "rust1", since = "1.0.0")] use os::unix::raw::{uid_t, gid_t}; use os::unix::io::{FromRawFd, RawFd, AsRawFd}; use prelude::v1::*; use process; use sys; use sys_common::{AsInnerMut, AsInner, FromInner}; /// Unix-specific extensions to the `std::process::Command` builder #[stable(feature = "rust1", since = "1.0.0")] pub trait CommandExt { /// Sets the child process's user id. This translates to a /// `setuid` call in the child process. Failure in the `setuid` /// call will cause the spawn to fail. #[stable(feature = "rust1", since = "1.0.0")] fn uid(&mut self, id: uid_t) -> &mut process::Command; /// Similar to `uid`, but sets the group id of the child process. This has /// the same semantics as the `uid` field. #[stable(feature = "rust1", since = "1.0.0")] fn gid(&mut self, id: gid_t) -> &mut process::Command; } #[stable(feature = "rust1", since = "1.0.0")] impl CommandExt for process::Command { fn uid(&mut self, id: uid_t) -> &mut process::Command { self.as_inner_mut().uid = Some(id); self } fn gid(&mut self, id: gid_t) -> &mut process::Command { self.as_inner_mut().gid = Some(id); self } } /// Unix-specific extensions to `std::process::ExitStatus` #[stable(feature = "rust1", since = "1.0.0")] pub trait ExitStatusExt { /// If the process was terminated by a signal, returns that signal. #[stable(feature = "rust1", since = "1.0.0")] fn signal(&self) -> Option<i32>; } #[stable(feature = "rust1", since = "1.0.0")] impl ExitStatusExt for process::ExitStatus { fn signal(&self) -> Option<i32> { match *self.as_inner() { sys::process::ExitStatus::Signal(s) => Some(s), _ => None } } } #[stable(feature = "process_extensions", since = "1.2.0")] impl FromRawFd for process::Stdio { unsafe fn from_raw_fd(fd: RawFd) -> process::Stdio { process::Stdio::from_inner(sys::fd::FileDesc::new(fd)) } } #[stable(feature = "process_extensions", since = "1.2.0")] impl AsRawFd for process::ChildStdin { fn as_raw_fd(&self) -> RawFd { self.as_inner().fd().raw() } } #[stable(feature = "process_extensions", since = "1.2.0")] impl AsRawFd for process::ChildStdout { fn
(&self) -> RawFd { self.as_inner().fd().raw() } } #[stable(feature = "process_extensions", since = "1.2.0")] impl AsRawFd for process::ChildStderr { fn as_raw_fd(&self) -> RawFd { self.as_inner().fd().raw() } }
as_raw_fd
identifier_name
htmlolistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLOListElementBinding; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; use util::str::DOMString; #[dom_struct] pub struct HTMLOListElement { htmlelement: HTMLElement, } impl HTMLOListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLOListElement
#[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLOListElement> { let element = HTMLOListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOListElementBinding::Wrap) } }
{ HTMLOListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
identifier_body
htmlolistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLOListElementBinding; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement;
#[dom_struct] pub struct HTMLOListElement { htmlelement: HTMLElement, } impl HTMLOListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLOListElement { HTMLOListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLOListElement> { let element = HTMLOListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOListElementBinding::Wrap) } }
use dom::node::Node; use string_cache::Atom; use util::str::DOMString;
random_line_split
htmlolistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLOListElementBinding; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; use util::str::DOMString; #[dom_struct] pub struct HTMLOListElement { htmlelement: HTMLElement, } impl HTMLOListElement { fn
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLOListElement { HTMLOListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLOListElement> { let element = HTMLOListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOListElementBinding::Wrap) } }
new_inherited
identifier_name
deriving-copyclone.rs
// run-pass //! Test that #[derive(Copy, Clone)] produces a shallow copy //! even when a member violates RFC 1521 use std::sync::atomic::{AtomicBool, Ordering}; /// A struct that pretends to be Copy, but actually does something /// in its Clone impl #[derive(Copy)] struct
; /// Static cooperating with the rogue Clone impl static CLONED: AtomicBool = AtomicBool::new(false); impl Clone for Liar { fn clone(&self) -> Self { // this makes Clone vs Copy observable CLONED.store(true, Ordering::SeqCst); *self } } /// This struct is actually Copy... at least, it thinks it is! #[derive(Copy, Clone)] struct Innocent(Liar); impl Innocent { fn new() -> Self { Innocent(Liar) } } fn main() { let _ = Innocent::new().clone(); // if Innocent was byte-for-byte copied, CLONED will still be false assert!(!CLONED.load(Ordering::SeqCst)); }
Liar
identifier_name
deriving-copyclone.rs
// run-pass //! Test that #[derive(Copy, Clone)] produces a shallow copy //! even when a member violates RFC 1521 use std::sync::atomic::{AtomicBool, Ordering};
struct Liar; /// Static cooperating with the rogue Clone impl static CLONED: AtomicBool = AtomicBool::new(false); impl Clone for Liar { fn clone(&self) -> Self { // this makes Clone vs Copy observable CLONED.store(true, Ordering::SeqCst); *self } } /// This struct is actually Copy... at least, it thinks it is! #[derive(Copy, Clone)] struct Innocent(Liar); impl Innocent { fn new() -> Self { Innocent(Liar) } } fn main() { let _ = Innocent::new().clone(); // if Innocent was byte-for-byte copied, CLONED will still be false assert!(!CLONED.load(Ordering::SeqCst)); }
/// A struct that pretends to be Copy, but actually does something /// in its Clone impl #[derive(Copy)]
random_line_split
deriving-copyclone.rs
// run-pass //! Test that #[derive(Copy, Clone)] produces a shallow copy //! even when a member violates RFC 1521 use std::sync::atomic::{AtomicBool, Ordering}; /// A struct that pretends to be Copy, but actually does something /// in its Clone impl #[derive(Copy)] struct Liar; /// Static cooperating with the rogue Clone impl static CLONED: AtomicBool = AtomicBool::new(false); impl Clone for Liar { fn clone(&self) -> Self { // this makes Clone vs Copy observable CLONED.store(true, Ordering::SeqCst); *self } } /// This struct is actually Copy... at least, it thinks it is! #[derive(Copy, Clone)] struct Innocent(Liar); impl Innocent { fn new() -> Self { Innocent(Liar) } } fn main()
{ let _ = Innocent::new().clone(); // if Innocent was byte-for-byte copied, CLONED will still be false assert!(!CLONED.load(Ordering::SeqCst)); }
identifier_body
_6_1_coordinate_systems.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; use cgmath::{Matrix4, vec3, Deg, perspective}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 800; const SCR_HEIGHT: u32 = 600; #[allow(non_snake_case)] pub fn main_1_6_1() { // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_key_polling(true); window.set_framebuffer_size_polling(true); // gl: load all OpenGL function pointers // --------------------------------------- gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (ourShader, VBO, VAO, EBO, texture1, texture2) = unsafe { // build and compile our shader program // ------------------------------------ let ourShader = Shader::new( "src/_1_getting_started/shaders/6.1.coordinate_systems.vs", "src/_1_getting_started/shaders/6.1.coordinate_systems.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ // HINT: type annotation is crucial since default for float literals is f64 let vertices: [f32; 20] = [ // positions // texture coords 0.5, 0.5, 0.0, 1.0, 1.0, // top right 0.5, -0.5, 0.0, 1.0, 0.0, // bottom right -0.5, -0.5, 0.0, 0.0, 0.0, // bottom left -0.5, 0.5, 0.0, 0.0, 1.0 // top left ]; let indices = [ 0, 1, 3, // first Triangle 1, 2, 3 // second Triangle ]; let (mut VBO, mut VAO, mut EBO) = (0, 0, 0); gl::GenVertexArrays(1, &mut VAO); gl::GenBuffers(1, &mut VBO); gl::GenBuffers(1, &mut EBO); gl::BindVertexArray(VAO); gl::BindBuffer(gl::ARRAY_BUFFER, VBO); gl::BufferData(gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &vertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, EBO); gl::BufferData(gl::ELEMENT_ARRAY_BUFFER, (indices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &indices[0] as *const i32 as *const c_void, gl::STATIC_DRAW); let stride = 5 * mem::size_of::<GLfloat>() as GLsizei; // position attribute gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(0); // texture coord attribute gl::VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(1); // load and create a texture // ------------------------- let (mut texture1, mut texture2) = (0, 0); // texture 1 // --------- gl::GenTextures(1, &mut texture1); gl::BindTexture(gl::TEXTURE_2D, texture1); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/container.jpg")).expect("Failed to load texture"); let data = img.raw_pixels(); gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGB, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // texture 2 // --------- gl::GenTextures(1, &mut texture2); gl::BindTexture(gl::TEXTURE_2D, texture2); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/awesomeface.png")).expect("Failed to load texture"); let img = img.flipv(); // flip loaded texture on the y-axis. let data = img.raw_pixels(); // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGBA, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.useProgram(); ourShader.setInt(c_str!("texture1"), 0); ourShader.setInt(c_str!("texture2"), 1); (ourShader, VBO, VAO, EBO, texture1, texture2) }; // render loop // ----------- while!window.should_close() { // events // ----- process_events(&mut window, &events); // render // ------ unsafe { gl::ClearColor(0.2, 0.3, 0.3, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); // bind textures on corresponding texture units gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, texture1); gl::ActiveTexture(gl::TEXTURE1); gl::BindTexture(gl::TEXTURE_2D, texture2); // activate shader ourShader.useProgram(); // create transformations let model: Matrix4<f32> = Matrix4::from_angle_x(Deg(-55.)); let view: Matrix4<f32> = Matrix4::from_translation(vec3(0., 0., -3.)); let projection: Matrix4<f32> = perspective(Deg(45.0), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); // retrieve the matrix uniform locations let modelLoc = gl::GetUniformLocation(ourShader.ID, c_str!("model").as_ptr()); let viewLoc = gl::GetUniformLocation(ourShader.ID, c_str!("view").as_ptr()); // pass them to the shaders (3 different ways) gl::UniformMatrix4fv(modelLoc, 1, gl::FALSE, model.as_ptr()); gl::UniformMatrix4fv(viewLoc, 1, gl::FALSE, &view[0][0]); // note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. ourShader.setMat4(c_str!("projection"), &projection); // render container gl::BindVertexArray(VAO); gl::DrawElements(gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null()); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); }
gl::DeleteBuffers(1, &VBO); gl::DeleteBuffers(1, &EBO); } } fn process_events(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) { for (_, event) in glfw::flush_messages(events) { match event { glfw::WindowEvent::FramebufferSize(width, height) => { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. unsafe { gl::Viewport(0, 0, width, height) } } glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true), _ => {} } } }
// optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &VAO);
random_line_split
_6_1_coordinate_systems.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; use cgmath::{Matrix4, vec3, Deg, perspective}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 800; const SCR_HEIGHT: u32 = 600; #[allow(non_snake_case)] pub fn main_1_6_1() { // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_key_polling(true); window.set_framebuffer_size_polling(true); // gl: load all OpenGL function pointers // --------------------------------------- gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (ourShader, VBO, VAO, EBO, texture1, texture2) = unsafe { // build and compile our shader program // ------------------------------------ let ourShader = Shader::new( "src/_1_getting_started/shaders/6.1.coordinate_systems.vs", "src/_1_getting_started/shaders/6.1.coordinate_systems.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ // HINT: type annotation is crucial since default for float literals is f64 let vertices: [f32; 20] = [ // positions // texture coords 0.5, 0.5, 0.0, 1.0, 1.0, // top right 0.5, -0.5, 0.0, 1.0, 0.0, // bottom right -0.5, -0.5, 0.0, 0.0, 0.0, // bottom left -0.5, 0.5, 0.0, 0.0, 1.0 // top left ]; let indices = [ 0, 1, 3, // first Triangle 1, 2, 3 // second Triangle ]; let (mut VBO, mut VAO, mut EBO) = (0, 0, 0); gl::GenVertexArrays(1, &mut VAO); gl::GenBuffers(1, &mut VBO); gl::GenBuffers(1, &mut EBO); gl::BindVertexArray(VAO); gl::BindBuffer(gl::ARRAY_BUFFER, VBO); gl::BufferData(gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &vertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, EBO); gl::BufferData(gl::ELEMENT_ARRAY_BUFFER, (indices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &indices[0] as *const i32 as *const c_void, gl::STATIC_DRAW); let stride = 5 * mem::size_of::<GLfloat>() as GLsizei; // position attribute gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(0); // texture coord attribute gl::VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(1); // load and create a texture // ------------------------- let (mut texture1, mut texture2) = (0, 0); // texture 1 // --------- gl::GenTextures(1, &mut texture1); gl::BindTexture(gl::TEXTURE_2D, texture1); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/container.jpg")).expect("Failed to load texture"); let data = img.raw_pixels(); gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGB, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // texture 2 // --------- gl::GenTextures(1, &mut texture2); gl::BindTexture(gl::TEXTURE_2D, texture2); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/awesomeface.png")).expect("Failed to load texture"); let img = img.flipv(); // flip loaded texture on the y-axis. let data = img.raw_pixels(); // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGBA, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.useProgram(); ourShader.setInt(c_str!("texture1"), 0); ourShader.setInt(c_str!("texture2"), 1); (ourShader, VBO, VAO, EBO, texture1, texture2) }; // render loop // ----------- while!window.should_close() { // events // ----- process_events(&mut window, &events); // render // ------ unsafe { gl::ClearColor(0.2, 0.3, 0.3, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); // bind textures on corresponding texture units gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, texture1); gl::ActiveTexture(gl::TEXTURE1); gl::BindTexture(gl::TEXTURE_2D, texture2); // activate shader ourShader.useProgram(); // create transformations let model: Matrix4<f32> = Matrix4::from_angle_x(Deg(-55.)); let view: Matrix4<f32> = Matrix4::from_translation(vec3(0., 0., -3.)); let projection: Matrix4<f32> = perspective(Deg(45.0), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); // retrieve the matrix uniform locations let modelLoc = gl::GetUniformLocation(ourShader.ID, c_str!("model").as_ptr()); let viewLoc = gl::GetUniformLocation(ourShader.ID, c_str!("view").as_ptr()); // pass them to the shaders (3 different ways) gl::UniformMatrix4fv(modelLoc, 1, gl::FALSE, model.as_ptr()); gl::UniformMatrix4fv(viewLoc, 1, gl::FALSE, &view[0][0]); // note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. ourShader.setMat4(c_str!("projection"), &projection); // render container gl::BindVertexArray(VAO); gl::DrawElements(gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null()); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &VAO); gl::DeleteBuffers(1, &VBO); gl::DeleteBuffers(1, &EBO); } } fn
(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) { for (_, event) in glfw::flush_messages(events) { match event { glfw::WindowEvent::FramebufferSize(width, height) => { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. unsafe { gl::Viewport(0, 0, width, height) } } glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true), _ => {} } } }
process_events
identifier_name
_6_1_coordinate_systems.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; use cgmath::{Matrix4, vec3, Deg, perspective}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 800; const SCR_HEIGHT: u32 = 600; #[allow(non_snake_case)] pub fn main_1_6_1() { // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_key_polling(true); window.set_framebuffer_size_polling(true); // gl: load all OpenGL function pointers // --------------------------------------- gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (ourShader, VBO, VAO, EBO, texture1, texture2) = unsafe { // build and compile our shader program // ------------------------------------ let ourShader = Shader::new( "src/_1_getting_started/shaders/6.1.coordinate_systems.vs", "src/_1_getting_started/shaders/6.1.coordinate_systems.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ // HINT: type annotation is crucial since default for float literals is f64 let vertices: [f32; 20] = [ // positions // texture coords 0.5, 0.5, 0.0, 1.0, 1.0, // top right 0.5, -0.5, 0.0, 1.0, 0.0, // bottom right -0.5, -0.5, 0.0, 0.0, 0.0, // bottom left -0.5, 0.5, 0.0, 0.0, 1.0 // top left ]; let indices = [ 0, 1, 3, // first Triangle 1, 2, 3 // second Triangle ]; let (mut VBO, mut VAO, mut EBO) = (0, 0, 0); gl::GenVertexArrays(1, &mut VAO); gl::GenBuffers(1, &mut VBO); gl::GenBuffers(1, &mut EBO); gl::BindVertexArray(VAO); gl::BindBuffer(gl::ARRAY_BUFFER, VBO); gl::BufferData(gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &vertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, EBO); gl::BufferData(gl::ELEMENT_ARRAY_BUFFER, (indices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &indices[0] as *const i32 as *const c_void, gl::STATIC_DRAW); let stride = 5 * mem::size_of::<GLfloat>() as GLsizei; // position attribute gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(0); // texture coord attribute gl::VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(1); // load and create a texture // ------------------------- let (mut texture1, mut texture2) = (0, 0); // texture 1 // --------- gl::GenTextures(1, &mut texture1); gl::BindTexture(gl::TEXTURE_2D, texture1); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/container.jpg")).expect("Failed to load texture"); let data = img.raw_pixels(); gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGB, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // texture 2 // --------- gl::GenTextures(1, &mut texture2); gl::BindTexture(gl::TEXTURE_2D, texture2); // set the texture wrapping parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method) gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); // set texture filtering parameters gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); // load image, create texture and generate mipmaps let img = image::open(&Path::new("resources/textures/awesomeface.png")).expect("Failed to load texture"); let img = img.flipv(); // flip loaded texture on the y-axis. let data = img.raw_pixels(); // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGB as i32, img.width() as i32, img.height() as i32, 0, gl::RGBA, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.useProgram(); ourShader.setInt(c_str!("texture1"), 0); ourShader.setInt(c_str!("texture2"), 1); (ourShader, VBO, VAO, EBO, texture1, texture2) }; // render loop // ----------- while!window.should_close() { // events // ----- process_events(&mut window, &events); // render // ------ unsafe { gl::ClearColor(0.2, 0.3, 0.3, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); // bind textures on corresponding texture units gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, texture1); gl::ActiveTexture(gl::TEXTURE1); gl::BindTexture(gl::TEXTURE_2D, texture2); // activate shader ourShader.useProgram(); // create transformations let model: Matrix4<f32> = Matrix4::from_angle_x(Deg(-55.)); let view: Matrix4<f32> = Matrix4::from_translation(vec3(0., 0., -3.)); let projection: Matrix4<f32> = perspective(Deg(45.0), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); // retrieve the matrix uniform locations let modelLoc = gl::GetUniformLocation(ourShader.ID, c_str!("model").as_ptr()); let viewLoc = gl::GetUniformLocation(ourShader.ID, c_str!("view").as_ptr()); // pass them to the shaders (3 different ways) gl::UniformMatrix4fv(modelLoc, 1, gl::FALSE, model.as_ptr()); gl::UniformMatrix4fv(viewLoc, 1, gl::FALSE, &view[0][0]); // note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. ourShader.setMat4(c_str!("projection"), &projection); // render container gl::BindVertexArray(VAO); gl::DrawElements(gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null()); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &VAO); gl::DeleteBuffers(1, &VBO); gl::DeleteBuffers(1, &EBO); } } fn process_events(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>)
{ for (_, event) in glfw::flush_messages(events) { match event { glfw::WindowEvent::FramebufferSize(width, height) => { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. unsafe { gl::Viewport(0, 0, width, height) } } glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true), _ => {} } } }
identifier_body
generic-trait-generic-static-default-method.rs
// xfail-test // 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
// compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print arg1 // check:$1 = 1000 // debugger:print *arg2 // check:$2 = {1, 2.5} // debugger:continue // debugger:finish // debugger:print arg1 // check:$3 = 2000 // debugger:print *arg2 // check:$4 = {3.5, {4, 5, 6}} // debugger:continue struct Struct { x: int } trait Trait<T1> { fn generic_static_default_method<T2>(arg1: int, arg2: &(T1, T2)) -> int { zzz(); arg1 } } impl<T> Trait<T> for Struct {} fn main() { // Is this really how to use these? Trait::generic_static_default_method::<int, Struct, float>(1000, &(1, 2.5)); Trait::generic_static_default_method::<float, Struct, (int, int, int)>(2000, &(3.5, (4, 5, 6))); } fn zzz() {()}
// <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.
random_line_split
generic-trait-generic-static-default-method.rs
// xfail-test // 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. // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print arg1 // check:$1 = 1000 // debugger:print *arg2 // check:$2 = {1, 2.5} // debugger:continue // debugger:finish // debugger:print arg1 // check:$3 = 2000 // debugger:print *arg2 // check:$4 = {3.5, {4, 5, 6}} // debugger:continue struct Struct { x: int } trait Trait<T1> { fn generic_static_default_method<T2>(arg1: int, arg2: &(T1, T2)) -> int { zzz(); arg1 } } impl<T> Trait<T> for Struct {} fn main() { // Is this really how to use these? Trait::generic_static_default_method::<int, Struct, float>(1000, &(1, 2.5)); Trait::generic_static_default_method::<float, Struct, (int, int, int)>(2000, &(3.5, (4, 5, 6))); } fn
() {()}
zzz
identifier_name
lib.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/. */ extern crate hashglobe; extern crate smallvec; use hashglobe::FailedAllocationError; use smallvec::Array; use smallvec::SmallVec; use std::vec::Vec; #[cfg(feature = "known_system_malloc")] extern "C" { fn realloc(ptr: *mut u8, bytes: usize) -> *mut u8; fn malloc(bytes: usize) -> *mut u8; } pub trait FallibleVec<T> { /// Append |val| to the end of |vec|. Returns Ok(()) on success, /// Err(reason) if it fails, with |reason| describing the failure. fn try_push(&mut self, value: T) -> Result<(), FailedAllocationError>; } ///////////////////////////////////////////////////////////////// // Vec impl<T> FallibleVec<T> for Vec<T> { #[inline(always)] fn try_push(&mut self, val: T) -> Result<(), FailedAllocationError> { #[cfg(feature = "known_system_malloc")] { if self.capacity() == self.len() { try_double_vec(self)?; debug_assert!(self.capacity() > self.len()); } } self.push(val); Ok(()) } } // Double the capacity of |vec|, or fail to do so due to lack of memory. // Returns Ok(()) on success, Err(..) on failure. #[cfg(feature = "known_system_malloc")] #[inline(never)] #[cold] fn try_double_vec<T>(vec: &mut Vec<T>) -> Result<(), FailedAllocationError> { use std::mem; let old_ptr = vec.as_mut_ptr(); let old_len = vec.len(); let old_cap: usize = vec.capacity(); let new_cap: usize = if old_cap == 0 { 4 } else { old_cap.checked_mul(2).ok_or(FailedAllocationError::new( "capacity overflow for Vec", ))? }; let new_size_bytes = new_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for Vec"), )?; let new_ptr = unsafe { if old_cap == 0 { malloc(new_size_bytes) } else { realloc(old_ptr as *mut u8, new_size_bytes) } }; if new_ptr.is_null() { return Err(FailedAllocationError::new( "out of memory when allocating Vec", )); } let new_vec = unsafe { Vec::from_raw_parts(new_ptr as *mut T, old_len, new_cap) }; mem::forget(mem::replace(vec, new_vec)); Ok(()) } ///////////////////////////////////////////////////////////////// // SmallVec impl<T: Array> FallibleVec<T::Item> for SmallVec<T> { #[inline(always)] fn try_push(&mut self, val: T::Item) -> Result<(), FailedAllocationError> { #[cfg(feature = "known_system_malloc")] { if self.capacity() == self.len() { try_double_small_vec(self)?; debug_assert!(self.capacity() > self.len()); } } self.push(val); Ok(()) } } // Double the capacity of |svec|, or fail to do so due to lack of memory. // Returns Ok(()) on success, Err(..) on failure. #[cfg(feature = "known_system_malloc")] #[inline(never)] #[cold] fn try_double_small_vec<T>(svec: &mut SmallVec<T>) -> Result<(), FailedAllocationError> where T: Array, { use std::mem; use std::ptr::copy_nonoverlapping; let old_ptr = svec.as_mut_ptr(); let old_len = svec.len(); let old_cap: usize = svec.capacity(); let new_cap: usize = if old_cap == 0 { 4 } else { old_cap.checked_mul(2).ok_or(FailedAllocationError::new( "capacity overflow for SmallVec", ))? }; // This surely shouldn't fail, if |old_cap| was previously accepted as a // valid value. But err on the side of caution. let old_size_bytes = old_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for SmallVec"), )?; let new_size_bytes = new_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for SmallVec"), )?; let new_ptr; if svec.spilled() { // There's an old block to free, and, presumably, old contents to // copy. realloc takes care of both aspects. unsafe { new_ptr = realloc(old_ptr as *mut u8, new_size_bytes); } } else { // There's no old block to free. There may be old contents to copy. unsafe { new_ptr = malloc(new_size_bytes); if!new_ptr.is_null() && old_size_bytes > 0
} } if new_ptr.is_null() { return Err(FailedAllocationError::new( "out of memory when allocating SmallVec", )); } let new_vec = unsafe { Vec::from_raw_parts(new_ptr as *mut T::Item, old_len, new_cap) }; let new_svec = SmallVec::from_vec(new_vec); mem::forget(mem::replace(svec, new_svec)); Ok(()) }
{ copy_nonoverlapping(old_ptr as *const u8, new_ptr as *mut u8, old_size_bytes); }
conditional_block
lib.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/. */ extern crate hashglobe; extern crate smallvec; use hashglobe::FailedAllocationError; use smallvec::Array; use smallvec::SmallVec; use std::vec::Vec; #[cfg(feature = "known_system_malloc")] extern "C" { fn realloc(ptr: *mut u8, bytes: usize) -> *mut u8; fn malloc(bytes: usize) -> *mut u8; } pub trait FallibleVec<T> { /// Append |val| to the end of |vec|. Returns Ok(()) on success, /// Err(reason) if it fails, with |reason| describing the failure. fn try_push(&mut self, value: T) -> Result<(), FailedAllocationError>; } ///////////////////////////////////////////////////////////////// // Vec impl<T> FallibleVec<T> for Vec<T> { #[inline(always)] fn try_push(&mut self, val: T) -> Result<(), FailedAllocationError> { #[cfg(feature = "known_system_malloc")] { if self.capacity() == self.len() { try_double_vec(self)?; debug_assert!(self.capacity() > self.len()); } } self.push(val); Ok(()) } } // Double the capacity of |vec|, or fail to do so due to lack of memory. // Returns Ok(()) on success, Err(..) on failure. #[cfg(feature = "known_system_malloc")] #[inline(never)] #[cold] fn try_double_vec<T>(vec: &mut Vec<T>) -> Result<(), FailedAllocationError> { use std::mem; let old_ptr = vec.as_mut_ptr(); let old_len = vec.len(); let old_cap: usize = vec.capacity(); let new_cap: usize = if old_cap == 0 { 4
"capacity overflow for Vec", ))? }; let new_size_bytes = new_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for Vec"), )?; let new_ptr = unsafe { if old_cap == 0 { malloc(new_size_bytes) } else { realloc(old_ptr as *mut u8, new_size_bytes) } }; if new_ptr.is_null() { return Err(FailedAllocationError::new( "out of memory when allocating Vec", )); } let new_vec = unsafe { Vec::from_raw_parts(new_ptr as *mut T, old_len, new_cap) }; mem::forget(mem::replace(vec, new_vec)); Ok(()) } ///////////////////////////////////////////////////////////////// // SmallVec impl<T: Array> FallibleVec<T::Item> for SmallVec<T> { #[inline(always)] fn try_push(&mut self, val: T::Item) -> Result<(), FailedAllocationError> { #[cfg(feature = "known_system_malloc")] { if self.capacity() == self.len() { try_double_small_vec(self)?; debug_assert!(self.capacity() > self.len()); } } self.push(val); Ok(()) } } // Double the capacity of |svec|, or fail to do so due to lack of memory. // Returns Ok(()) on success, Err(..) on failure. #[cfg(feature = "known_system_malloc")] #[inline(never)] #[cold] fn try_double_small_vec<T>(svec: &mut SmallVec<T>) -> Result<(), FailedAllocationError> where T: Array, { use std::mem; use std::ptr::copy_nonoverlapping; let old_ptr = svec.as_mut_ptr(); let old_len = svec.len(); let old_cap: usize = svec.capacity(); let new_cap: usize = if old_cap == 0 { 4 } else { old_cap.checked_mul(2).ok_or(FailedAllocationError::new( "capacity overflow for SmallVec", ))? }; // This surely shouldn't fail, if |old_cap| was previously accepted as a // valid value. But err on the side of caution. let old_size_bytes = old_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for SmallVec"), )?; let new_size_bytes = new_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for SmallVec"), )?; let new_ptr; if svec.spilled() { // There's an old block to free, and, presumably, old contents to // copy. realloc takes care of both aspects. unsafe { new_ptr = realloc(old_ptr as *mut u8, new_size_bytes); } } else { // There's no old block to free. There may be old contents to copy. unsafe { new_ptr = malloc(new_size_bytes); if!new_ptr.is_null() && old_size_bytes > 0 { copy_nonoverlapping(old_ptr as *const u8, new_ptr as *mut u8, old_size_bytes); } } } if new_ptr.is_null() { return Err(FailedAllocationError::new( "out of memory when allocating SmallVec", )); } let new_vec = unsafe { Vec::from_raw_parts(new_ptr as *mut T::Item, old_len, new_cap) }; let new_svec = SmallVec::from_vec(new_vec); mem::forget(mem::replace(svec, new_svec)); Ok(()) }
} else { old_cap.checked_mul(2).ok_or(FailedAllocationError::new(
random_line_split
lib.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/. */ extern crate hashglobe; extern crate smallvec; use hashglobe::FailedAllocationError; use smallvec::Array; use smallvec::SmallVec; use std::vec::Vec; #[cfg(feature = "known_system_malloc")] extern "C" { fn realloc(ptr: *mut u8, bytes: usize) -> *mut u8; fn malloc(bytes: usize) -> *mut u8; } pub trait FallibleVec<T> { /// Append |val| to the end of |vec|. Returns Ok(()) on success, /// Err(reason) if it fails, with |reason| describing the failure. fn try_push(&mut self, value: T) -> Result<(), FailedAllocationError>; } ///////////////////////////////////////////////////////////////// // Vec impl<T> FallibleVec<T> for Vec<T> { #[inline(always)] fn try_push(&mut self, val: T) -> Result<(), FailedAllocationError> { #[cfg(feature = "known_system_malloc")] { if self.capacity() == self.len() { try_double_vec(self)?; debug_assert!(self.capacity() > self.len()); } } self.push(val); Ok(()) } } // Double the capacity of |vec|, or fail to do so due to lack of memory. // Returns Ok(()) on success, Err(..) on failure. #[cfg(feature = "known_system_malloc")] #[inline(never)] #[cold] fn try_double_vec<T>(vec: &mut Vec<T>) -> Result<(), FailedAllocationError> { use std::mem; let old_ptr = vec.as_mut_ptr(); let old_len = vec.len(); let old_cap: usize = vec.capacity(); let new_cap: usize = if old_cap == 0 { 4 } else { old_cap.checked_mul(2).ok_or(FailedAllocationError::new( "capacity overflow for Vec", ))? }; let new_size_bytes = new_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for Vec"), )?; let new_ptr = unsafe { if old_cap == 0 { malloc(new_size_bytes) } else { realloc(old_ptr as *mut u8, new_size_bytes) } }; if new_ptr.is_null() { return Err(FailedAllocationError::new( "out of memory when allocating Vec", )); } let new_vec = unsafe { Vec::from_raw_parts(new_ptr as *mut T, old_len, new_cap) }; mem::forget(mem::replace(vec, new_vec)); Ok(()) } ///////////////////////////////////////////////////////////////// // SmallVec impl<T: Array> FallibleVec<T::Item> for SmallVec<T> { #[inline(always)] fn try_push(&mut self, val: T::Item) -> Result<(), FailedAllocationError> { #[cfg(feature = "known_system_malloc")] { if self.capacity() == self.len() { try_double_small_vec(self)?; debug_assert!(self.capacity() > self.len()); } } self.push(val); Ok(()) } } // Double the capacity of |svec|, or fail to do so due to lack of memory. // Returns Ok(()) on success, Err(..) on failure. #[cfg(feature = "known_system_malloc")] #[inline(never)] #[cold] fn try_double_small_vec<T>(svec: &mut SmallVec<T>) -> Result<(), FailedAllocationError> where T: Array,
)?; let new_size_bytes = new_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for SmallVec"), )?; let new_ptr; if svec.spilled() { // There's an old block to free, and, presumably, old contents to // copy. realloc takes care of both aspects. unsafe { new_ptr = realloc(old_ptr as *mut u8, new_size_bytes); } } else { // There's no old block to free. There may be old contents to copy. unsafe { new_ptr = malloc(new_size_bytes); if!new_ptr.is_null() && old_size_bytes > 0 { copy_nonoverlapping(old_ptr as *const u8, new_ptr as *mut u8, old_size_bytes); } } } if new_ptr.is_null() { return Err(FailedAllocationError::new( "out of memory when allocating SmallVec", )); } let new_vec = unsafe { Vec::from_raw_parts(new_ptr as *mut T::Item, old_len, new_cap) }; let new_svec = SmallVec::from_vec(new_vec); mem::forget(mem::replace(svec, new_svec)); Ok(()) }
{ use std::mem; use std::ptr::copy_nonoverlapping; let old_ptr = svec.as_mut_ptr(); let old_len = svec.len(); let old_cap: usize = svec.capacity(); let new_cap: usize = if old_cap == 0 { 4 } else { old_cap.checked_mul(2).ok_or(FailedAllocationError::new( "capacity overflow for SmallVec", ))? }; // This surely shouldn't fail, if |old_cap| was previously accepted as a // valid value. But err on the side of caution. let old_size_bytes = old_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for SmallVec"),
identifier_body
lib.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/. */ extern crate hashglobe; extern crate smallvec; use hashglobe::FailedAllocationError; use smallvec::Array; use smallvec::SmallVec; use std::vec::Vec; #[cfg(feature = "known_system_malloc")] extern "C" { fn realloc(ptr: *mut u8, bytes: usize) -> *mut u8; fn malloc(bytes: usize) -> *mut u8; } pub trait FallibleVec<T> { /// Append |val| to the end of |vec|. Returns Ok(()) on success, /// Err(reason) if it fails, with |reason| describing the failure. fn try_push(&mut self, value: T) -> Result<(), FailedAllocationError>; } ///////////////////////////////////////////////////////////////// // Vec impl<T> FallibleVec<T> for Vec<T> { #[inline(always)] fn
(&mut self, val: T) -> Result<(), FailedAllocationError> { #[cfg(feature = "known_system_malloc")] { if self.capacity() == self.len() { try_double_vec(self)?; debug_assert!(self.capacity() > self.len()); } } self.push(val); Ok(()) } } // Double the capacity of |vec|, or fail to do so due to lack of memory. // Returns Ok(()) on success, Err(..) on failure. #[cfg(feature = "known_system_malloc")] #[inline(never)] #[cold] fn try_double_vec<T>(vec: &mut Vec<T>) -> Result<(), FailedAllocationError> { use std::mem; let old_ptr = vec.as_mut_ptr(); let old_len = vec.len(); let old_cap: usize = vec.capacity(); let new_cap: usize = if old_cap == 0 { 4 } else { old_cap.checked_mul(2).ok_or(FailedAllocationError::new( "capacity overflow for Vec", ))? }; let new_size_bytes = new_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for Vec"), )?; let new_ptr = unsafe { if old_cap == 0 { malloc(new_size_bytes) } else { realloc(old_ptr as *mut u8, new_size_bytes) } }; if new_ptr.is_null() { return Err(FailedAllocationError::new( "out of memory when allocating Vec", )); } let new_vec = unsafe { Vec::from_raw_parts(new_ptr as *mut T, old_len, new_cap) }; mem::forget(mem::replace(vec, new_vec)); Ok(()) } ///////////////////////////////////////////////////////////////// // SmallVec impl<T: Array> FallibleVec<T::Item> for SmallVec<T> { #[inline(always)] fn try_push(&mut self, val: T::Item) -> Result<(), FailedAllocationError> { #[cfg(feature = "known_system_malloc")] { if self.capacity() == self.len() { try_double_small_vec(self)?; debug_assert!(self.capacity() > self.len()); } } self.push(val); Ok(()) } } // Double the capacity of |svec|, or fail to do so due to lack of memory. // Returns Ok(()) on success, Err(..) on failure. #[cfg(feature = "known_system_malloc")] #[inline(never)] #[cold] fn try_double_small_vec<T>(svec: &mut SmallVec<T>) -> Result<(), FailedAllocationError> where T: Array, { use std::mem; use std::ptr::copy_nonoverlapping; let old_ptr = svec.as_mut_ptr(); let old_len = svec.len(); let old_cap: usize = svec.capacity(); let new_cap: usize = if old_cap == 0 { 4 } else { old_cap.checked_mul(2).ok_or(FailedAllocationError::new( "capacity overflow for SmallVec", ))? }; // This surely shouldn't fail, if |old_cap| was previously accepted as a // valid value. But err on the side of caution. let old_size_bytes = old_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for SmallVec"), )?; let new_size_bytes = new_cap.checked_mul(mem::size_of::<T>()).ok_or( FailedAllocationError::new("capacity overflow for SmallVec"), )?; let new_ptr; if svec.spilled() { // There's an old block to free, and, presumably, old contents to // copy. realloc takes care of both aspects. unsafe { new_ptr = realloc(old_ptr as *mut u8, new_size_bytes); } } else { // There's no old block to free. There may be old contents to copy. unsafe { new_ptr = malloc(new_size_bytes); if!new_ptr.is_null() && old_size_bytes > 0 { copy_nonoverlapping(old_ptr as *const u8, new_ptr as *mut u8, old_size_bytes); } } } if new_ptr.is_null() { return Err(FailedAllocationError::new( "out of memory when allocating SmallVec", )); } let new_vec = unsafe { Vec::from_raw_parts(new_ptr as *mut T::Item, old_len, new_cap) }; let new_svec = SmallVec::from_vec(new_vec); mem::forget(mem::replace(svec, new_svec)); Ok(()) }
try_push
identifier_name
lib.rs
// The MIT License (MIT) // Copyright (c) 2016 Connor Hilarides // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #![allow(dead_code)] extern crate image; extern crate gif; extern crate owning_ref; extern crate memmap; use std::path::PathBuf; use std::rc::Rc; use std::{io, fs, slice}; pub mod ffi; pub enum Buffer { Boxed(Box<[u8]>), Allocated(*const u8, usize, unsafe fn(*const u8, usize)), } impl Buffer { pub fn get(&self) -> &[u8] { match *self { Buffer::Boxed(ref data) => &**data, Buffer::Allocated(data, size, _) => unsafe { slice::from_raw_parts(data, size) }, } } } impl Drop for Buffer { fn drop(&mut self) { match *self { Buffer::Allocated(data, size, free) => unsafe { free(data, size) }, _ => {} } } } pub enum ImageId { File(PathBuf), Borrowed(*const [u8]), Owned(Buffer), } pub struct Image { frame: image::Frame, } impl Image { fn get_reader(id: &ImageId) -> io::Result<io::Cursor<SrcData>> { let id = match *id { ImageId::File(ref path) => ImageId::File(path.clone()), ImageId::Borrowed(ptr) => ImageId::Borrowed(ptr), ImageId::Owned(ref data) => ImageId::Borrowed(data.get() as *const [u8]), }; Ok(io::Cursor::new(try!(ImageSrc::new(id)))) } pub fn load(id: &ImageId, format: image::ImageFormat) -> image::ImageResult<Image> { let reader = try!(Image::get_reader(id)); let dyn = try!(image::load(reader, format)); let frame = image::Frame::new(dyn.to_rgba()); Ok(Image { frame: frame, }) } } type SrcData = owning_ref::OwningRef<Rc<ImageSrc>, [u8]>; enum ImageSrc { File(memmap::Mmap), Borrowed(*const [u8]), Owned(Buffer), } impl ImageSrc { pub fn new(id: ImageId) -> io::Result<SrcData> { Ok(ImageSrc::make_data(try!(ImageSrc::open_src(id)))) } fn open_src(id: ImageId) -> io::Result<ImageSrc> { use ImageSrc::*; Ok(match id { ImageId::File(path) => { let file = try!(fs::File::open(path)); let mmap = try!(memmap::Mmap::open(&file, memmap::Protection::Read)); File(mmap) }, ImageId::Borrowed(ptr) => Borrowed(ptr), ImageId::Owned(data) => Owned(data), }) } fn make_data(data: ImageSrc) -> SrcData { use owning_ref::OwningRef; let base_ref = OwningRef::<Rc<ImageSrc>, ImageSrc>::new(Rc::new(data)); base_ref.map(|data| { use ImageSrc::*; match *data { File(ref mmap) => unsafe { mmap.as_slice() }, Borrowed(ptr) => unsafe { &*ptr }, Owned(ref data) => data.get(), } }) } } pub struct MultiImage { current_frame: Option<image::Frame>, decoder: Option<gif::Reader<io::Cursor<SrcData>>>, source: SrcData, next_frame: usize, width: u32, height: u32, delay: u16, } impl MultiImage { pub fn new(id: ImageId) -> Result<MultiImage, gif::DecodingError> { let mut image = MultiImage { next_frame: 0, width: 0, height: 0, delay: 0, current_frame: None, decoder: None, source: try!(ImageSrc::new(id)), }; try!(image.setup_decoder()); Ok(image) } pub fn request_frame(&mut self, num: usize) -> Option<&image::Frame> { if self.current_frame.is_none() || num + 1!= self.next_frame { self.load_frame(num) } else { self.current_frame.as_ref() } } fn setup_decoder(&mut self) -> Result<(), gif::DecodingError> { use gif::{ColorOutput, SetParameter}; let mut decoder = gif::Decoder::new(io::Cursor::new(self.source.clone())); decoder.set(ColorOutput::RGBA); let reader = try!(decoder.read_info()); self.width = reader.width() as u32; self.height = reader.height() as u32; self.decoder = Some(reader); self.next_frame = 0; self.current_frame = None; Ok(()) } fn
(&mut self, num: usize) -> Option<&image::Frame> { use image::{ImageBuffer, DynamicImage}; if self.decoder.is_none() || self.next_frame > num { match self.setup_decoder() { Ok(_) => {}, Err(_) => return None, } } let mut reader = self.decoder.take().unwrap(); while self.next_frame < num { match reader.next_frame_info() { Ok(Some(_)) => {}, _ => return None, } self.next_frame += 1; } let (width, height, frame_buf) = match reader.read_next_frame() { Ok(Some(frame)) => { self.delay = frame.delay; ( frame.width as u32, frame.height as u32, frame.buffer.clone().into_owned(), ) }, _ => return None, }; self.next_frame += 1; let raw_buf = ImageBuffer::from_raw(width, height, frame_buf); let buf = match raw_buf.map(|v| DynamicImage::ImageRgba8(v)) { Some(buf) => buf, None => return None, }; self.decoder = Some(reader); self.current_frame = Some(image::Frame::new(buf.to_rgba())); self.current_frame.as_ref() } }
load_frame
identifier_name
lib.rs
// The MIT License (MIT) // Copyright (c) 2016 Connor Hilarides // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #![allow(dead_code)] extern crate image; extern crate gif; extern crate owning_ref; extern crate memmap; use std::path::PathBuf; use std::rc::Rc; use std::{io, fs, slice}; pub mod ffi; pub enum Buffer { Boxed(Box<[u8]>), Allocated(*const u8, usize, unsafe fn(*const u8, usize)), } impl Buffer { pub fn get(&self) -> &[u8] { match *self { Buffer::Boxed(ref data) => &**data, Buffer::Allocated(data, size, _) => unsafe { slice::from_raw_parts(data, size) }, } } } impl Drop for Buffer { fn drop(&mut self) { match *self { Buffer::Allocated(data, size, free) => unsafe { free(data, size) }, _ => {} } } } pub enum ImageId { File(PathBuf), Borrowed(*const [u8]), Owned(Buffer), } pub struct Image { frame: image::Frame, } impl Image { fn get_reader(id: &ImageId) -> io::Result<io::Cursor<SrcData>> { let id = match *id { ImageId::File(ref path) => ImageId::File(path.clone()), ImageId::Borrowed(ptr) => ImageId::Borrowed(ptr), ImageId::Owned(ref data) => ImageId::Borrowed(data.get() as *const [u8]), }; Ok(io::Cursor::new(try!(ImageSrc::new(id)))) } pub fn load(id: &ImageId, format: image::ImageFormat) -> image::ImageResult<Image> { let reader = try!(Image::get_reader(id)); let dyn = try!(image::load(reader, format)); let frame = image::Frame::new(dyn.to_rgba()); Ok(Image { frame: frame, }) } } type SrcData = owning_ref::OwningRef<Rc<ImageSrc>, [u8]>; enum ImageSrc { File(memmap::Mmap), Borrowed(*const [u8]), Owned(Buffer), } impl ImageSrc { pub fn new(id: ImageId) -> io::Result<SrcData> { Ok(ImageSrc::make_data(try!(ImageSrc::open_src(id)))) } fn open_src(id: ImageId) -> io::Result<ImageSrc> { use ImageSrc::*; Ok(match id { ImageId::File(path) => { let file = try!(fs::File::open(path)); let mmap = try!(memmap::Mmap::open(&file, memmap::Protection::Read)); File(mmap) }, ImageId::Borrowed(ptr) => Borrowed(ptr), ImageId::Owned(data) => Owned(data), }) } fn make_data(data: ImageSrc) -> SrcData { use owning_ref::OwningRef; let base_ref = OwningRef::<Rc<ImageSrc>, ImageSrc>::new(Rc::new(data)); base_ref.map(|data| { use ImageSrc::*; match *data { File(ref mmap) => unsafe { mmap.as_slice() }, Borrowed(ptr) => unsafe { &*ptr }, Owned(ref data) => data.get(), } }) } } pub struct MultiImage { current_frame: Option<image::Frame>, decoder: Option<gif::Reader<io::Cursor<SrcData>>>, source: SrcData, next_frame: usize, width: u32, height: u32, delay: u16, } impl MultiImage { pub fn new(id: ImageId) -> Result<MultiImage, gif::DecodingError> { let mut image = MultiImage { next_frame: 0, width: 0, height: 0, delay: 0, current_frame: None, decoder: None, source: try!(ImageSrc::new(id)), }; try!(image.setup_decoder()); Ok(image) } pub fn request_frame(&mut self, num: usize) -> Option<&image::Frame>
fn setup_decoder(&mut self) -> Result<(), gif::DecodingError> { use gif::{ColorOutput, SetParameter}; let mut decoder = gif::Decoder::new(io::Cursor::new(self.source.clone())); decoder.set(ColorOutput::RGBA); let reader = try!(decoder.read_info()); self.width = reader.width() as u32; self.height = reader.height() as u32; self.decoder = Some(reader); self.next_frame = 0; self.current_frame = None; Ok(()) } fn load_frame(&mut self, num: usize) -> Option<&image::Frame> { use image::{ImageBuffer, DynamicImage}; if self.decoder.is_none() || self.next_frame > num { match self.setup_decoder() { Ok(_) => {}, Err(_) => return None, } } let mut reader = self.decoder.take().unwrap(); while self.next_frame < num { match reader.next_frame_info() { Ok(Some(_)) => {}, _ => return None, } self.next_frame += 1; } let (width, height, frame_buf) = match reader.read_next_frame() { Ok(Some(frame)) => { self.delay = frame.delay; ( frame.width as u32, frame.height as u32, frame.buffer.clone().into_owned(), ) }, _ => return None, }; self.next_frame += 1; let raw_buf = ImageBuffer::from_raw(width, height, frame_buf); let buf = match raw_buf.map(|v| DynamicImage::ImageRgba8(v)) { Some(buf) => buf, None => return None, }; self.decoder = Some(reader); self.current_frame = Some(image::Frame::new(buf.to_rgba())); self.current_frame.as_ref() } }
{ if self.current_frame.is_none() || num + 1 != self.next_frame { self.load_frame(num) } else { self.current_frame.as_ref() } }
identifier_body
lib.rs
// The MIT License (MIT) // Copyright (c) 2016 Connor Hilarides // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #![allow(dead_code)] extern crate image; extern crate gif; extern crate owning_ref; extern crate memmap; use std::path::PathBuf; use std::rc::Rc; use std::{io, fs, slice}; pub mod ffi; pub enum Buffer { Boxed(Box<[u8]>), Allocated(*const u8, usize, unsafe fn(*const u8, usize)), } impl Buffer { pub fn get(&self) -> &[u8] { match *self { Buffer::Boxed(ref data) => &**data, Buffer::Allocated(data, size, _) => unsafe { slice::from_raw_parts(data, size) }, } } } impl Drop for Buffer { fn drop(&mut self) { match *self { Buffer::Allocated(data, size, free) => unsafe { free(data, size) }, _ => {} } } } pub enum ImageId { File(PathBuf), Borrowed(*const [u8]), Owned(Buffer), } pub struct Image { frame: image::Frame, } impl Image { fn get_reader(id: &ImageId) -> io::Result<io::Cursor<SrcData>> { let id = match *id { ImageId::File(ref path) => ImageId::File(path.clone()), ImageId::Borrowed(ptr) => ImageId::Borrowed(ptr), ImageId::Owned(ref data) => ImageId::Borrowed(data.get() as *const [u8]), }; Ok(io::Cursor::new(try!(ImageSrc::new(id)))) } pub fn load(id: &ImageId, format: image::ImageFormat) -> image::ImageResult<Image> { let reader = try!(Image::get_reader(id)); let dyn = try!(image::load(reader, format)); let frame = image::Frame::new(dyn.to_rgba()); Ok(Image { frame: frame, }) } } type SrcData = owning_ref::OwningRef<Rc<ImageSrc>, [u8]>; enum ImageSrc { File(memmap::Mmap), Borrowed(*const [u8]), Owned(Buffer), } impl ImageSrc { pub fn new(id: ImageId) -> io::Result<SrcData> { Ok(ImageSrc::make_data(try!(ImageSrc::open_src(id)))) } fn open_src(id: ImageId) -> io::Result<ImageSrc> { use ImageSrc::*; Ok(match id { ImageId::File(path) => { let file = try!(fs::File::open(path)); let mmap = try!(memmap::Mmap::open(&file, memmap::Protection::Read)); File(mmap) }, ImageId::Borrowed(ptr) => Borrowed(ptr), ImageId::Owned(data) => Owned(data), }) } fn make_data(data: ImageSrc) -> SrcData { use owning_ref::OwningRef; let base_ref = OwningRef::<Rc<ImageSrc>, ImageSrc>::new(Rc::new(data)); base_ref.map(|data| { use ImageSrc::*; match *data { File(ref mmap) => unsafe { mmap.as_slice() }, Borrowed(ptr) => unsafe { &*ptr }, Owned(ref data) => data.get(), } }) } } pub struct MultiImage { current_frame: Option<image::Frame>, decoder: Option<gif::Reader<io::Cursor<SrcData>>>, source: SrcData, next_frame: usize, width: u32, height: u32, delay: u16, } impl MultiImage { pub fn new(id: ImageId) -> Result<MultiImage, gif::DecodingError> { let mut image = MultiImage { next_frame: 0, width: 0, height: 0, delay: 0, current_frame: None, decoder: None, source: try!(ImageSrc::new(id)), }; try!(image.setup_decoder()); Ok(image) } pub fn request_frame(&mut self, num: usize) -> Option<&image::Frame> { if self.current_frame.is_none() || num + 1!= self.next_frame { self.load_frame(num) } else { self.current_frame.as_ref() } } fn setup_decoder(&mut self) -> Result<(), gif::DecodingError> { use gif::{ColorOutput, SetParameter}; let mut decoder = gif::Decoder::new(io::Cursor::new(self.source.clone())); decoder.set(ColorOutput::RGBA); let reader = try!(decoder.read_info()); self.width = reader.width() as u32; self.height = reader.height() as u32; self.decoder = Some(reader); self.next_frame = 0; self.current_frame = None; Ok(()) } fn load_frame(&mut self, num: usize) -> Option<&image::Frame> { use image::{ImageBuffer, DynamicImage}; if self.decoder.is_none() || self.next_frame > num { match self.setup_decoder() { Ok(_) => {}, Err(_) => return None, } } let mut reader = self.decoder.take().unwrap(); while self.next_frame < num { match reader.next_frame_info() { Ok(Some(_)) => {}, _ => return None, } self.next_frame += 1; } let (width, height, frame_buf) = match reader.read_next_frame() { Ok(Some(frame)) => {
( frame.width as u32, frame.height as u32, frame.buffer.clone().into_owned(), ) }, _ => return None, }; self.next_frame += 1; let raw_buf = ImageBuffer::from_raw(width, height, frame_buf); let buf = match raw_buf.map(|v| DynamicImage::ImageRgba8(v)) { Some(buf) => buf, None => return None, }; self.decoder = Some(reader); self.current_frame = Some(image::Frame::new(buf.to_rgba())); self.current_frame.as_ref() } }
self.delay = frame.delay;
random_line_split
example.rs
extern crate itertools; use itertools::Itertools; /// Encrypt the input string using square cryptography pub fn encrypt(input: &str) -> String { let prepared = prepare(input); if prepared.is_empty() { return String::new(); } let (cols, rows) = dimensions(prepared.len()); let mut output = String::with_capacity(input.len()); for chunk_iterator in SquareIndexer::new(rows, cols).chunks(cols).into_iter() { for ch_idx in chunk_iterator { if ch_idx < prepared.len() { output.push(prepared[ch_idx]); } } output.push(' '); } // we know there's one extra space at the end output.pop(); output } /// Construct a vector of characters from the given input. /// /// Constrain it to the allowed chars: lowercase ascii letters. /// We construct a vector here because the length of the input /// matters when constructing the output, so we need to know /// how many input chars there are. We could treat it as a stream /// and just stream twice, but collecting it into a vector works /// equally well and might be a bit faster. fn prepare(input: &str) -> Vec<char> { let mut output = Vec::with_capacity(input.len()); output.extend( input .chars() .filter(|&c| c.is_ascii() &&!c.is_whitespace() &&!c.is_ascii_punctuation()) .map(|c| c.to_ascii_lowercase()), ); // add space padding to the end such that the actual string returned // forms a perfect rectangle let (r, c) = dimensions(output.len()); output.resize(r * c,''); output.shrink_to_fit(); output } /// Get the dimensions of the appropriate bounding rectangle for this encryption /// /// To find `(rows, cols)` such that `cols >= rows && cols - rows <= 1`, we find /// the least square greater than or equal to the message length. Its square root /// is the cols. If the message length is a perfect square, `rows` is the same. /// Otherwise, it is one less. fn
(length: usize) -> (usize, usize) { let cols = (length as f64).sqrt().ceil() as usize; let rows = if cols * cols == length { cols } else { cols - 1 }; (rows, cols) } /// Iterator over the indices of the appropriate chars of the output. /// /// For a (2, 3) (r, c) grid, yields (0, 3, 1, 4, 2, 5). /// Does no bounds checking or space insertion: that's handled elsewhere. #[derive(Debug)] struct SquareIndexer { rows: usize, cols: usize, cur_row: usize, cur_col: usize, max_value: usize, } impl SquareIndexer { fn new(rows: usize, cols: usize) -> SquareIndexer { SquareIndexer { rows, cols, cur_row: 0, cur_col: 0, max_value: rows * cols, } } } impl Iterator for SquareIndexer { type Item = usize; fn next(&mut self) -> Option<usize> { let value = self.cur_row + (self.cur_col * self.rows); let output = if value < self.max_value && self.cur_row < self.rows { Some(value) } else { None }; // now increment internal state to next value self.cur_col += 1; if self.cur_col >= self.cols { self.cur_col = 0; self.cur_row += 1; } output } }
dimensions
identifier_name
example.rs
extern crate itertools; use itertools::Itertools; /// Encrypt the input string using square cryptography pub fn encrypt(input: &str) -> String { let prepared = prepare(input); if prepared.is_empty() { return String::new(); } let (cols, rows) = dimensions(prepared.len()); let mut output = String::with_capacity(input.len()); for chunk_iterator in SquareIndexer::new(rows, cols).chunks(cols).into_iter() { for ch_idx in chunk_iterator { if ch_idx < prepared.len() { output.push(prepared[ch_idx]); } } output.push(' '); } // we know there's one extra space at the end output.pop(); output } /// Construct a vector of characters from the given input. /// /// Constrain it to the allowed chars: lowercase ascii letters. /// We construct a vector here because the length of the input /// matters when constructing the output, so we need to know /// how many input chars there are. We could treat it as a stream /// and just stream twice, but collecting it into a vector works /// equally well and might be a bit faster. fn prepare(input: &str) -> Vec<char> { let mut output = Vec::with_capacity(input.len()); output.extend( input .chars() .filter(|&c| c.is_ascii() &&!c.is_whitespace() &&!c.is_ascii_punctuation()) .map(|c| c.to_ascii_lowercase()), ); // add space padding to the end such that the actual string returned // forms a perfect rectangle let (r, c) = dimensions(output.len()); output.resize(r * c,''); output.shrink_to_fit(); output } /// Get the dimensions of the appropriate bounding rectangle for this encryption /// /// To find `(rows, cols)` such that `cols >= rows && cols - rows <= 1`, we find /// the least square greater than or equal to the message length. Its square root /// is the cols. If the message length is a perfect square, `rows` is the same. /// Otherwise, it is one less. fn dimensions(length: usize) -> (usize, usize) { let cols = (length as f64).sqrt().ceil() as usize; let rows = if cols * cols == length { cols } else { cols - 1 }; (rows, cols) } /// Iterator over the indices of the appropriate chars of the output. /// /// For a (2, 3) (r, c) grid, yields (0, 3, 1, 4, 2, 5). /// Does no bounds checking or space insertion: that's handled elsewhere. #[derive(Debug)] struct SquareIndexer { rows: usize, cols: usize, cur_row: usize, cur_col: usize, max_value: usize, } impl SquareIndexer { fn new(rows: usize, cols: usize) -> SquareIndexer { SquareIndexer { rows, cols, cur_row: 0, cur_col: 0, max_value: rows * cols, } } } impl Iterator for SquareIndexer { type Item = usize; fn next(&mut self) -> Option<usize> { let value = self.cur_row + (self.cur_col * self.rows); let output = if value < self.max_value && self.cur_row < self.rows { Some(value) } else
; // now increment internal state to next value self.cur_col += 1; if self.cur_col >= self.cols { self.cur_col = 0; self.cur_row += 1; } output } }
{ None }
conditional_block
example.rs
extern crate itertools; use itertools::Itertools; /// Encrypt the input string using square cryptography pub fn encrypt(input: &str) -> String { let prepared = prepare(input); if prepared.is_empty() { return String::new(); } let (cols, rows) = dimensions(prepared.len()); let mut output = String::with_capacity(input.len()); for chunk_iterator in SquareIndexer::new(rows, cols).chunks(cols).into_iter() { for ch_idx in chunk_iterator { if ch_idx < prepared.len() { output.push(prepared[ch_idx]); } } output.push(' '); } // we know there's one extra space at the end output.pop(); output } /// Construct a vector of characters from the given input. /// /// Constrain it to the allowed chars: lowercase ascii letters. /// We construct a vector here because the length of the input /// matters when constructing the output, so we need to know /// how many input chars there are. We could treat it as a stream /// and just stream twice, but collecting it into a vector works /// equally well and might be a bit faster. fn prepare(input: &str) -> Vec<char> { let mut output = Vec::with_capacity(input.len()); output.extend( input .chars() .filter(|&c| c.is_ascii() &&!c.is_whitespace() &&!c.is_ascii_punctuation()) .map(|c| c.to_ascii_lowercase()), ); // add space padding to the end such that the actual string returned // forms a perfect rectangle let (r, c) = dimensions(output.len()); output.resize(r * c,''); output.shrink_to_fit(); output } /// Get the dimensions of the appropriate bounding rectangle for this encryption /// /// To find `(rows, cols)` such that `cols >= rows && cols - rows <= 1`, we find /// the least square greater than or equal to the message length. Its square root /// is the cols. If the message length is a perfect square, `rows` is the same. /// Otherwise, it is one less. fn dimensions(length: usize) -> (usize, usize)
/// Iterator over the indices of the appropriate chars of the output. /// /// For a (2, 3) (r, c) grid, yields (0, 3, 1, 4, 2, 5). /// Does no bounds checking or space insertion: that's handled elsewhere. #[derive(Debug)] struct SquareIndexer { rows: usize, cols: usize, cur_row: usize, cur_col: usize, max_value: usize, } impl SquareIndexer { fn new(rows: usize, cols: usize) -> SquareIndexer { SquareIndexer { rows, cols, cur_row: 0, cur_col: 0, max_value: rows * cols, } } } impl Iterator for SquareIndexer { type Item = usize; fn next(&mut self) -> Option<usize> { let value = self.cur_row + (self.cur_col * self.rows); let output = if value < self.max_value && self.cur_row < self.rows { Some(value) } else { None }; // now increment internal state to next value self.cur_col += 1; if self.cur_col >= self.cols { self.cur_col = 0; self.cur_row += 1; } output } }
{ let cols = (length as f64).sqrt().ceil() as usize; let rows = if cols * cols == length { cols } else { cols - 1 }; (rows, cols) }
identifier_body
example.rs
extern crate itertools; use itertools::Itertools; /// Encrypt the input string using square cryptography pub fn encrypt(input: &str) -> String { let prepared = prepare(input); if prepared.is_empty() { return String::new(); } let (cols, rows) = dimensions(prepared.len()); let mut output = String::with_capacity(input.len()); for chunk_iterator in SquareIndexer::new(rows, cols).chunks(cols).into_iter() { for ch_idx in chunk_iterator { if ch_idx < prepared.len() { output.push(prepared[ch_idx]); } } output.push(' '); } // we know there's one extra space at the end output.pop(); output } /// Construct a vector of characters from the given input. /// /// Constrain it to the allowed chars: lowercase ascii letters. /// We construct a vector here because the length of the input /// matters when constructing the output, so we need to know /// how many input chars there are. We could treat it as a stream /// and just stream twice, but collecting it into a vector works /// equally well and might be a bit faster. fn prepare(input: &str) -> Vec<char> { let mut output = Vec::with_capacity(input.len()); output.extend( input .chars()
.filter(|&c| c.is_ascii() &&!c.is_whitespace() &&!c.is_ascii_punctuation()) .map(|c| c.to_ascii_lowercase()), ); // add space padding to the end such that the actual string returned // forms a perfect rectangle let (r, c) = dimensions(output.len()); output.resize(r * c,''); output.shrink_to_fit(); output } /// Get the dimensions of the appropriate bounding rectangle for this encryption /// /// To find `(rows, cols)` such that `cols >= rows && cols - rows <= 1`, we find /// the least square greater than or equal to the message length. Its square root /// is the cols. If the message length is a perfect square, `rows` is the same. /// Otherwise, it is one less. fn dimensions(length: usize) -> (usize, usize) { let cols = (length as f64).sqrt().ceil() as usize; let rows = if cols * cols == length { cols } else { cols - 1 }; (rows, cols) } /// Iterator over the indices of the appropriate chars of the output. /// /// For a (2, 3) (r, c) grid, yields (0, 3, 1, 4, 2, 5). /// Does no bounds checking or space insertion: that's handled elsewhere. #[derive(Debug)] struct SquareIndexer { rows: usize, cols: usize, cur_row: usize, cur_col: usize, max_value: usize, } impl SquareIndexer { fn new(rows: usize, cols: usize) -> SquareIndexer { SquareIndexer { rows, cols, cur_row: 0, cur_col: 0, max_value: rows * cols, } } } impl Iterator for SquareIndexer { type Item = usize; fn next(&mut self) -> Option<usize> { let value = self.cur_row + (self.cur_col * self.rows); let output = if value < self.max_value && self.cur_row < self.rows { Some(value) } else { None }; // now increment internal state to next value self.cur_col += 1; if self.cur_col >= self.cols { self.cur_col = 0; self.cur_row += 1; } output } }
random_line_split
mod.rs
use bytes::Buf; use futures::{Async, Future, Poll}; use h2::{Reason, SendStream}; use http::header::{ HeaderName, CONNECTION, PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, TE, TRAILER, TRANSFER_ENCODING, UPGRADE, }; use http::HeaderMap; use body::Payload; mod client; pub(crate) mod server; pub(crate) use self::client::Client; pub(crate) use self::server::Server; fn strip_connection_headers(headers: &mut HeaderMap, is_request: bool) { // List of connection headers from: // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection // // TE headers are allowed in HTTP/2 requests as long as the value is "trailers", so they're // tested separately. let connection_headers = [ HeaderName::from_lowercase(b"keep-alive").unwrap(), HeaderName::from_lowercase(b"proxy-connection").unwrap(), PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, TRAILER, TRANSFER_ENCODING, UPGRADE, ]; for header in connection_headers.iter() { if headers.remove(header).is_some() { warn!("Connection header illegal in HTTP/2: {}", header.as_str()); } } if is_request { if headers.get(TE).map(|te_header| te_header!= "trailers").unwrap_or(false) { warn!("TE headers not set to \"trailers\" are illegal in HTTP/2 requests"); headers.remove(TE); } } else { if headers.remove(TE).is_some() { warn!("TE headers illegal in HTTP/2 responses"); } } if let Some(header) = headers.remove(CONNECTION) { warn!( "Connection header illegal in HTTP/2: {}", CONNECTION.as_str() ); let header_contents = header.to_str().unwrap(); // A `Connection` header may have a comma-separated list of names of other headers that // are meant for only this specific connection. // // Iterate these names and remove them as headers. Connection-specific headers are // forbidden in HTTP2, as that information has been moved into frame types of the h2 // protocol. for name in header_contents.split(',') { let name = name.trim(); headers.remove(name); } } } // body adapters used by both Client and Server struct PipeToSendStream<S> where S: Payload, { body_tx: SendStream<SendBuf<S::Data>>, data_done: bool, stream: S, } impl<S> PipeToSendStream<S> where S: Payload, { fn new(stream: S, tx: SendStream<SendBuf<S::Data>>) -> PipeToSendStream<S> { PipeToSendStream { body_tx: tx, data_done: false, stream: stream, } } fn on_err(&mut self, err: S::Error) -> ::Error { let err = ::Error::new_user_body(err); trace!("send body user stream error: {}", err); self.body_tx.send_reset(Reason::INTERNAL_ERROR); err } fn send_eos_frame(&mut self) -> ::Result<()> { trace!("send body eos"); self.body_tx .send_data(SendBuf(None), true) .map_err(::Error::new_body_write) } } impl<S> Future for PipeToSendStream<S> where S: Payload, { type Item = (); type Error = ::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { loop { if!self.data_done { // we don't have the next chunk of data yet, so just reserve 1 byte to make // sure there's some capacity available. h2 will handle the capacity management // for the actual body chunk. self.body_tx.reserve_capacity(1); if self.body_tx.capacity() == 0 { loop { match try_ready!(self.body_tx.poll_capacity().map_err(::Error::new_h2)) { Some(0) => {} Some(_) => break, None => return Err(::Error::new_canceled(None::<::Error>)), } } } else { if let Async::Ready(reason) = self.body_tx.poll_reset().map_err(|e| ::Error::new_h2(e))? { debug!("stream received RST_STREAM: {:?}", reason); return Err(::Error::new_h2(reason.into())); } } match try_ready!(self.stream.poll_data().map_err(|e| self.on_err(e))) { Some(chunk) => { let is_eos = self.stream.is_end_stream(); trace!( "send body chunk: {} bytes, eos={}", chunk.remaining(), is_eos, ); let buf = SendBuf(Some(chunk)); self.body_tx .send_data(buf, is_eos) .map_err(::Error::new_body_write)?; if is_eos { return Ok(Async::Ready(())); } } None => { self.body_tx.reserve_capacity(0); let is_eos = self.stream.is_end_stream(); if is_eos { return self.send_eos_frame().map(Async::Ready); } else { self.data_done = true; // loop again to poll_trailers } } } } else { if let Async::Ready(reason) = self.body_tx.poll_reset().map_err(|e| ::Error::new_h2(e))? { debug!("stream received RST_STREAM: {:?}", reason); return Err(::Error::new_h2(reason.into())); } match try_ready!(self.stream.poll_trailers().map_err(|e| self.on_err(e))) { Some(trailers) => { self.body_tx .send_trailers(trailers) .map_err(::Error::new_body_write)?; return Ok(Async::Ready(())); } None => {
} } } struct SendBuf<B>(Option<B>); impl<B: Buf> Buf for SendBuf<B> { #[inline] fn remaining(&self) -> usize { self.0.as_ref().map(|b| b.remaining()).unwrap_or(0) } #[inline] fn bytes(&self) -> &[u8] { self.0.as_ref().map(|b| b.bytes()).unwrap_or(&[]) } #[inline] fn advance(&mut self, cnt: usize) { self.0.as_mut().map(|b| b.advance(cnt)); } }
// There were no trailers, so send an empty DATA frame... return self.send_eos_frame().map(Async::Ready); } } }
random_line_split
mod.rs
use bytes::Buf; use futures::{Async, Future, Poll}; use h2::{Reason, SendStream}; use http::header::{ HeaderName, CONNECTION, PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, TE, TRAILER, TRANSFER_ENCODING, UPGRADE, }; use http::HeaderMap; use body::Payload; mod client; pub(crate) mod server; pub(crate) use self::client::Client; pub(crate) use self::server::Server; fn strip_connection_headers(headers: &mut HeaderMap, is_request: bool) { // List of connection headers from: // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection // // TE headers are allowed in HTTP/2 requests as long as the value is "trailers", so they're // tested separately. let connection_headers = [ HeaderName::from_lowercase(b"keep-alive").unwrap(), HeaderName::from_lowercase(b"proxy-connection").unwrap(), PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, TRAILER, TRANSFER_ENCODING, UPGRADE, ]; for header in connection_headers.iter() { if headers.remove(header).is_some() { warn!("Connection header illegal in HTTP/2: {}", header.as_str()); } } if is_request { if headers.get(TE).map(|te_header| te_header!= "trailers").unwrap_or(false) { warn!("TE headers not set to \"trailers\" are illegal in HTTP/2 requests"); headers.remove(TE); } } else { if headers.remove(TE).is_some() { warn!("TE headers illegal in HTTP/2 responses"); } } if let Some(header) = headers.remove(CONNECTION) { warn!( "Connection header illegal in HTTP/2: {}", CONNECTION.as_str() ); let header_contents = header.to_str().unwrap(); // A `Connection` header may have a comma-separated list of names of other headers that // are meant for only this specific connection. // // Iterate these names and remove them as headers. Connection-specific headers are // forbidden in HTTP2, as that information has been moved into frame types of the h2 // protocol. for name in header_contents.split(',') { let name = name.trim(); headers.remove(name); } } } // body adapters used by both Client and Server struct PipeToSendStream<S> where S: Payload, { body_tx: SendStream<SendBuf<S::Data>>, data_done: bool, stream: S, } impl<S> PipeToSendStream<S> where S: Payload, { fn new(stream: S, tx: SendStream<SendBuf<S::Data>>) -> PipeToSendStream<S> { PipeToSendStream { body_tx: tx, data_done: false, stream: stream, } } fn on_err(&mut self, err: S::Error) -> ::Error { let err = ::Error::new_user_body(err); trace!("send body user stream error: {}", err); self.body_tx.send_reset(Reason::INTERNAL_ERROR); err } fn send_eos_frame(&mut self) -> ::Result<()> { trace!("send body eos"); self.body_tx .send_data(SendBuf(None), true) .map_err(::Error::new_body_write) } } impl<S> Future for PipeToSendStream<S> where S: Payload, { type Item = (); type Error = ::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { loop { if!self.data_done { // we don't have the next chunk of data yet, so just reserve 1 byte to make // sure there's some capacity available. h2 will handle the capacity management // for the actual body chunk. self.body_tx.reserve_capacity(1); if self.body_tx.capacity() == 0 { loop { match try_ready!(self.body_tx.poll_capacity().map_err(::Error::new_h2)) { Some(0) => {} Some(_) => break, None => return Err(::Error::new_canceled(None::<::Error>)), } } } else { if let Async::Ready(reason) = self.body_tx.poll_reset().map_err(|e| ::Error::new_h2(e))? { debug!("stream received RST_STREAM: {:?}", reason); return Err(::Error::new_h2(reason.into())); } } match try_ready!(self.stream.poll_data().map_err(|e| self.on_err(e))) { Some(chunk) => { let is_eos = self.stream.is_end_stream(); trace!( "send body chunk: {} bytes, eos={}", chunk.remaining(), is_eos, ); let buf = SendBuf(Some(chunk)); self.body_tx .send_data(buf, is_eos) .map_err(::Error::new_body_write)?; if is_eos { return Ok(Async::Ready(())); } } None => { self.body_tx.reserve_capacity(0); let is_eos = self.stream.is_end_stream(); if is_eos { return self.send_eos_frame().map(Async::Ready); } else { self.data_done = true; // loop again to poll_trailers } } } } else { if let Async::Ready(reason) = self.body_tx.poll_reset().map_err(|e| ::Error::new_h2(e))? { debug!("stream received RST_STREAM: {:?}", reason); return Err(::Error::new_h2(reason.into())); } match try_ready!(self.stream.poll_trailers().map_err(|e| self.on_err(e))) { Some(trailers) => { self.body_tx .send_trailers(trailers) .map_err(::Error::new_body_write)?; return Ok(Async::Ready(())); } None => { // There were no trailers, so send an empty DATA frame... return self.send_eos_frame().map(Async::Ready); } } } } } } struct
<B>(Option<B>); impl<B: Buf> Buf for SendBuf<B> { #[inline] fn remaining(&self) -> usize { self.0.as_ref().map(|b| b.remaining()).unwrap_or(0) } #[inline] fn bytes(&self) -> &[u8] { self.0.as_ref().map(|b| b.bytes()).unwrap_or(&[]) } #[inline] fn advance(&mut self, cnt: usize) { self.0.as_mut().map(|b| b.advance(cnt)); } }
SendBuf
identifier_name
mod.rs
use bytes::Buf; use futures::{Async, Future, Poll}; use h2::{Reason, SendStream}; use http::header::{ HeaderName, CONNECTION, PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, TE, TRAILER, TRANSFER_ENCODING, UPGRADE, }; use http::HeaderMap; use body::Payload; mod client; pub(crate) mod server; pub(crate) use self::client::Client; pub(crate) use self::server::Server; fn strip_connection_headers(headers: &mut HeaderMap, is_request: bool) { // List of connection headers from: // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection // // TE headers are allowed in HTTP/2 requests as long as the value is "trailers", so they're // tested separately. let connection_headers = [ HeaderName::from_lowercase(b"keep-alive").unwrap(), HeaderName::from_lowercase(b"proxy-connection").unwrap(), PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, TRAILER, TRANSFER_ENCODING, UPGRADE, ]; for header in connection_headers.iter() { if headers.remove(header).is_some() { warn!("Connection header illegal in HTTP/2: {}", header.as_str()); } } if is_request { if headers.get(TE).map(|te_header| te_header!= "trailers").unwrap_or(false) { warn!("TE headers not set to \"trailers\" are illegal in HTTP/2 requests"); headers.remove(TE); } } else { if headers.remove(TE).is_some() { warn!("TE headers illegal in HTTP/2 responses"); } } if let Some(header) = headers.remove(CONNECTION) { warn!( "Connection header illegal in HTTP/2: {}", CONNECTION.as_str() ); let header_contents = header.to_str().unwrap(); // A `Connection` header may have a comma-separated list of names of other headers that // are meant for only this specific connection. // // Iterate these names and remove them as headers. Connection-specific headers are // forbidden in HTTP2, as that information has been moved into frame types of the h2 // protocol. for name in header_contents.split(',') { let name = name.trim(); headers.remove(name); } } } // body adapters used by both Client and Server struct PipeToSendStream<S> where S: Payload, { body_tx: SendStream<SendBuf<S::Data>>, data_done: bool, stream: S, } impl<S> PipeToSendStream<S> where S: Payload, { fn new(stream: S, tx: SendStream<SendBuf<S::Data>>) -> PipeToSendStream<S> { PipeToSendStream { body_tx: tx, data_done: false, stream: stream, } } fn on_err(&mut self, err: S::Error) -> ::Error { let err = ::Error::new_user_body(err); trace!("send body user stream error: {}", err); self.body_tx.send_reset(Reason::INTERNAL_ERROR); err } fn send_eos_frame(&mut self) -> ::Result<()> { trace!("send body eos"); self.body_tx .send_data(SendBuf(None), true) .map_err(::Error::new_body_write) } } impl<S> Future for PipeToSendStream<S> where S: Payload, { type Item = (); type Error = ::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { loop { if!self.data_done
} } match try_ready!(self.stream.poll_data().map_err(|e| self.on_err(e))) { Some(chunk) => { let is_eos = self.stream.is_end_stream(); trace!( "send body chunk: {} bytes, eos={}", chunk.remaining(), is_eos, ); let buf = SendBuf(Some(chunk)); self.body_tx .send_data(buf, is_eos) .map_err(::Error::new_body_write)?; if is_eos { return Ok(Async::Ready(())); } } None => { self.body_tx.reserve_capacity(0); let is_eos = self.stream.is_end_stream(); if is_eos { return self.send_eos_frame().map(Async::Ready); } else { self.data_done = true; // loop again to poll_trailers } } } } else { if let Async::Ready(reason) = self.body_tx.poll_reset().map_err(|e| ::Error::new_h2(e))? { debug!("stream received RST_STREAM: {:?}", reason); return Err(::Error::new_h2(reason.into())); } match try_ready!(self.stream.poll_trailers().map_err(|e| self.on_err(e))) { Some(trailers) => { self.body_tx .send_trailers(trailers) .map_err(::Error::new_body_write)?; return Ok(Async::Ready(())); } None => { // There were no trailers, so send an empty DATA frame... return self.send_eos_frame().map(Async::Ready); } } } } } } struct SendBuf<B>(Option<B>); impl<B: Buf> Buf for SendBuf<B> { #[inline] fn remaining(&self) -> usize { self.0.as_ref().map(|b| b.remaining()).unwrap_or(0) } #[inline] fn bytes(&self) -> &[u8] { self.0.as_ref().map(|b| b.bytes()).unwrap_or(&[]) } #[inline] fn advance(&mut self, cnt: usize) { self.0.as_mut().map(|b| b.advance(cnt)); } }
{ // we don't have the next chunk of data yet, so just reserve 1 byte to make // sure there's some capacity available. h2 will handle the capacity management // for the actual body chunk. self.body_tx.reserve_capacity(1); if self.body_tx.capacity() == 0 { loop { match try_ready!(self.body_tx.poll_capacity().map_err(::Error::new_h2)) { Some(0) => {} Some(_) => break, None => return Err(::Error::new_canceled(None::<::Error>)), } } } else { if let Async::Ready(reason) = self.body_tx.poll_reset().map_err(|e| ::Error::new_h2(e))? { debug!("stream received RST_STREAM: {:?}", reason); return Err(::Error::new_h2(reason.into()));
conditional_block