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
effects.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> // Box-shadow, etc. <% data.new_style_struct("Effects", inherited=False) %> ${helpers.predefined_type( "opacity", "Opacity", "1.0", engines="gecko servo-2013 servo-2020", animation_value_type="ComputedValue", flags="CREATES_STACKING_CONTEXT CAN_ANIMATE_ON_COMPOSITOR", spec="https://drafts.csswg.org/css-color/#transparency", servo_restyle_damage = "reflow_out_of_flow", )} ${helpers.predefined_type( "box-shadow", "BoxShadow", None, engines="gecko servo-2013 servo-2020", servo_2020_pref="layout.2020.unimplemented", vector=True, simple_vector_bindings=True, animation_value_type="AnimatedBoxShadowList", vector_animation_type="with_zero", extra_prefixes="webkit", ignored_when_colors_disabled=True, spec="https://drafts.csswg.org/css-backgrounds/#box-shadow", )} ${helpers.predefined_type( "clip", "ClipRectOrAuto", "computed::ClipRectOrAuto::auto()", engines="gecko servo-2013 servo-2020", servo_2020_pref="layout.2020.unimplemented", animation_value_type="ComputedValue", boxed=True, allow_quirks="Yes", spec="https://drafts.fxtf.org/css-masking/#clip-property", )} ${helpers.predefined_type( "filter", "Filter", None, engines="gecko servo-2013 servo-2020",
animation_value_type="AnimatedFilterList", vector_animation_type="with_zero", extra_prefixes="webkit", flags="CREATES_STACKING_CONTEXT FIXPOS_CB", spec="https://drafts.fxtf.org/filters/#propdef-filter", )} ${helpers.predefined_type( "backdrop-filter", "Filter", None, engines="gecko", vector=True, simple_vector_bindings=True, gecko_ffi_name="mBackdropFilters", separator="Space", animation_value_type="AnimatedFilterList", vector_animation_type="with_zero", flags="CREATES_STACKING_CONTEXT FIXPOS_CB", gecko_pref="layout.css.backdrop-filter.enabled", spec="https://drafts.fxtf.org/filter-effects-2/#propdef-backdrop-filter", )} ${helpers.single_keyword( "mix-blend-mode", """normal multiply screen overlay darken lighten color-dodge color-burn hard-light soft-light difference exclusion hue saturation color luminosity""", engines="gecko servo-2013 servo-2020", gecko_constant_prefix="NS_STYLE_BLEND", animation_value_type="discrete", flags="CREATES_STACKING_CONTEXT", spec="https://drafts.fxtf.org/compositing/#propdef-mix-blend-mode", )}
vector=True, simple_vector_bindings=True, gecko_ffi_name="mFilters", separator="Space",
random_line_split
car.rs
use super::camera::Camera; use crate::color::*; use cgmath::{Vector2, Vector3}; // Present a car that can be drawed, check for collision // with other car and bullet, turn left/right, move forward // and jump. pub trait Car { fn render(&self, _: &Camera) -> Vec<([Vector2<f64>; 2], Color)>; fn crashed(&self, _: &Self) -> bool; fn hit(&self, _: &[Vector3<f64>; 3]) -> bool; fn forward(&mut self, dt: f64, outside_speed: f64); fn turn_left(&mut self, dt: f64); fn turn_right(&mut self, dt: f64); fn update_jump(&mut self, dt: f64); fn jump(&mut self); fn pos(&self) -> Vector3<f64>; fn turn_speed(&self) -> f64; } // Car with shape of a box #[derive(Clone)] pub struct BoxCar { pub size: Vector3<f64>, pub position: Vector3<f64>, pub speed: f64, pub turn_speed: f64, pub color: Color, pub jump_v: f64, pub jump_a: f64, pub jumping: bool, pub current_t: f64, pub jump_turn_decrease: f64, } impl Car for BoxCar { fn render(&self, camera: &Camera) -> Vec<([Vector2<f64>; 2], Color)> { let mut front = [self.position; 4]; front[0].y += self.size.y; front[1].y += self.size.y; front[0].x -= self.size.x / 2.; front[3].x -= self.size.x / 2.; front[1].x += self.size.x / 2.; front[2].x += self.size.x / 2.; let mut rear = front; for x in &mut rear { x.z += self.size.z; } let mut ret = Vec::new(); for i in 0..4 { ret.push(camera.render_line(&front[i], &front[(i + 1) % 4])); ret.push(camera.render_line(&rear[i], &rear[(i + 1) % 4])); ret.push(camera.render_line(&front[i], &rear[i])); } ret.into_iter() .filter_map(|x| x.map(|x| (x, self.color))) .collect() } fn turn_left(&mut self, dt: f64) { self.position.x -= dt * self.turn_speed(); } fn turn_right(&mut self, dt: f64) { self.position.x += dt * self.turn_speed(); } fn pos(&self) -> Vector3<f64> { self.position } fn crashed(&self, a: &Self) -> bool { (f64::abs(self.position.x - a.position.x) < (self.size.x + a.size.x) / 2.) && ((self.position.z < a.position.z && a.position.z - self.position.z < self.size.z) || (self.position.z >= a.position.z && self.position.z - a.position.z < a.size.z)) && ((self.position.y < a.position.y && a.position.y - self.position.y < self.size.y) || (self.position.y >= a.position.y && self.position.y - a.position.y < a.size.y)) } fn jump(&mut self) { if self.jumping || self.position.y > 0. { } else { self.jumping = true; self.current_t = 0.; } }
fn forward(&mut self, dt: f64, outside_speed: f64) { self.position.z -= dt * (self.speed + outside_speed); self.update_jump(dt); } fn update_jump(&mut self, dt: f64) { if self.jumping { self.current_t += dt; self.position.y = self.current_t * (self.jump_v - 0.5 * self.jump_a * self.current_t); if self.position.y < 0. { self.position.y = 0.; self.jumping = false; } } } fn hit(&self, bullet: &[Vector3<f64>; 3]) -> bool { let (x, y) = (bullet[0], bullet[0] + bullet[1]); let check = |x: &Vector3<f64>| { f64::abs(x.x - self.position.x) < self.size.x / 2. && x.y >= self.position.y && x.y - self.position.y < self.size.y && x.z >= self.position.z && x.z - self.position.z < self.size.z }; check(&x) || check(&y) } fn turn_speed(&self) -> f64 { if self.jumping { self.turn_speed / self.jump_turn_decrease } else { self.turn_speed } } }
random_line_split
car.rs
use super::camera::Camera; use crate::color::*; use cgmath::{Vector2, Vector3}; // Present a car that can be drawed, check for collision // with other car and bullet, turn left/right, move forward // and jump. pub trait Car { fn render(&self, _: &Camera) -> Vec<([Vector2<f64>; 2], Color)>; fn crashed(&self, _: &Self) -> bool; fn hit(&self, _: &[Vector3<f64>; 3]) -> bool; fn forward(&mut self, dt: f64, outside_speed: f64); fn turn_left(&mut self, dt: f64); fn turn_right(&mut self, dt: f64); fn update_jump(&mut self, dt: f64); fn jump(&mut self); fn pos(&self) -> Vector3<f64>; fn turn_speed(&self) -> f64; } // Car with shape of a box #[derive(Clone)] pub struct BoxCar { pub size: Vector3<f64>, pub position: Vector3<f64>, pub speed: f64, pub turn_speed: f64, pub color: Color, pub jump_v: f64, pub jump_a: f64, pub jumping: bool, pub current_t: f64, pub jump_turn_decrease: f64, } impl Car for BoxCar { fn render(&self, camera: &Camera) -> Vec<([Vector2<f64>; 2], Color)> { let mut front = [self.position; 4]; front[0].y += self.size.y; front[1].y += self.size.y; front[0].x -= self.size.x / 2.; front[3].x -= self.size.x / 2.; front[1].x += self.size.x / 2.; front[2].x += self.size.x / 2.; let mut rear = front; for x in &mut rear { x.z += self.size.z; } let mut ret = Vec::new(); for i in 0..4 { ret.push(camera.render_line(&front[i], &front[(i + 1) % 4])); ret.push(camera.render_line(&rear[i], &rear[(i + 1) % 4])); ret.push(camera.render_line(&front[i], &rear[i])); } ret.into_iter() .filter_map(|x| x.map(|x| (x, self.color))) .collect() } fn turn_left(&mut self, dt: f64) { self.position.x -= dt * self.turn_speed(); } fn turn_right(&mut self, dt: f64) { self.position.x += dt * self.turn_speed(); } fn
(&self) -> Vector3<f64> { self.position } fn crashed(&self, a: &Self) -> bool { (f64::abs(self.position.x - a.position.x) < (self.size.x + a.size.x) / 2.) && ((self.position.z < a.position.z && a.position.z - self.position.z < self.size.z) || (self.position.z >= a.position.z && self.position.z - a.position.z < a.size.z)) && ((self.position.y < a.position.y && a.position.y - self.position.y < self.size.y) || (self.position.y >= a.position.y && self.position.y - a.position.y < a.size.y)) } fn jump(&mut self) { if self.jumping || self.position.y > 0. { } else { self.jumping = true; self.current_t = 0.; } } fn forward(&mut self, dt: f64, outside_speed: f64) { self.position.z -= dt * (self.speed + outside_speed); self.update_jump(dt); } fn update_jump(&mut self, dt: f64) { if self.jumping { self.current_t += dt; self.position.y = self.current_t * (self.jump_v - 0.5 * self.jump_a * self.current_t); if self.position.y < 0. { self.position.y = 0.; self.jumping = false; } } } fn hit(&self, bullet: &[Vector3<f64>; 3]) -> bool { let (x, y) = (bullet[0], bullet[0] + bullet[1]); let check = |x: &Vector3<f64>| { f64::abs(x.x - self.position.x) < self.size.x / 2. && x.y >= self.position.y && x.y - self.position.y < self.size.y && x.z >= self.position.z && x.z - self.position.z < self.size.z }; check(&x) || check(&y) } fn turn_speed(&self) -> f64 { if self.jumping { self.turn_speed / self.jump_turn_decrease } else { self.turn_speed } } }
pos
identifier_name
car.rs
use super::camera::Camera; use crate::color::*; use cgmath::{Vector2, Vector3}; // Present a car that can be drawed, check for collision // with other car and bullet, turn left/right, move forward // and jump. pub trait Car { fn render(&self, _: &Camera) -> Vec<([Vector2<f64>; 2], Color)>; fn crashed(&self, _: &Self) -> bool; fn hit(&self, _: &[Vector3<f64>; 3]) -> bool; fn forward(&mut self, dt: f64, outside_speed: f64); fn turn_left(&mut self, dt: f64); fn turn_right(&mut self, dt: f64); fn update_jump(&mut self, dt: f64); fn jump(&mut self); fn pos(&self) -> Vector3<f64>; fn turn_speed(&self) -> f64; } // Car with shape of a box #[derive(Clone)] pub struct BoxCar { pub size: Vector3<f64>, pub position: Vector3<f64>, pub speed: f64, pub turn_speed: f64, pub color: Color, pub jump_v: f64, pub jump_a: f64, pub jumping: bool, pub current_t: f64, pub jump_turn_decrease: f64, } impl Car for BoxCar { fn render(&self, camera: &Camera) -> Vec<([Vector2<f64>; 2], Color)> { let mut front = [self.position; 4]; front[0].y += self.size.y; front[1].y += self.size.y; front[0].x -= self.size.x / 2.; front[3].x -= self.size.x / 2.; front[1].x += self.size.x / 2.; front[2].x += self.size.x / 2.; let mut rear = front; for x in &mut rear { x.z += self.size.z; } let mut ret = Vec::new(); for i in 0..4 { ret.push(camera.render_line(&front[i], &front[(i + 1) % 4])); ret.push(camera.render_line(&rear[i], &rear[(i + 1) % 4])); ret.push(camera.render_line(&front[i], &rear[i])); } ret.into_iter() .filter_map(|x| x.map(|x| (x, self.color))) .collect() } fn turn_left(&mut self, dt: f64) { self.position.x -= dt * self.turn_speed(); } fn turn_right(&mut self, dt: f64) { self.position.x += dt * self.turn_speed(); } fn pos(&self) -> Vector3<f64> { self.position } fn crashed(&self, a: &Self) -> bool { (f64::abs(self.position.x - a.position.x) < (self.size.x + a.size.x) / 2.) && ((self.position.z < a.position.z && a.position.z - self.position.z < self.size.z) || (self.position.z >= a.position.z && self.position.z - a.position.z < a.size.z)) && ((self.position.y < a.position.y && a.position.y - self.position.y < self.size.y) || (self.position.y >= a.position.y && self.position.y - a.position.y < a.size.y)) } fn jump(&mut self) { if self.jumping || self.position.y > 0. { } else { self.jumping = true; self.current_t = 0.; } } fn forward(&mut self, dt: f64, outside_speed: f64) { self.position.z -= dt * (self.speed + outside_speed); self.update_jump(dt); } fn update_jump(&mut self, dt: f64)
fn hit(&self, bullet: &[Vector3<f64>; 3]) -> bool { let (x, y) = (bullet[0], bullet[0] + bullet[1]); let check = |x: &Vector3<f64>| { f64::abs(x.x - self.position.x) < self.size.x / 2. && x.y >= self.position.y && x.y - self.position.y < self.size.y && x.z >= self.position.z && x.z - self.position.z < self.size.z }; check(&x) || check(&y) } fn turn_speed(&self) -> f64 { if self.jumping { self.turn_speed / self.jump_turn_decrease } else { self.turn_speed } } }
{ if self.jumping { self.current_t += dt; self.position.y = self.current_t * (self.jump_v - 0.5 * self.jump_a * self.current_t); if self.position.y < 0. { self.position.y = 0.; self.jumping = false; } } }
identifier_body
car.rs
use super::camera::Camera; use crate::color::*; use cgmath::{Vector2, Vector3}; // Present a car that can be drawed, check for collision // with other car and bullet, turn left/right, move forward // and jump. pub trait Car { fn render(&self, _: &Camera) -> Vec<([Vector2<f64>; 2], Color)>; fn crashed(&self, _: &Self) -> bool; fn hit(&self, _: &[Vector3<f64>; 3]) -> bool; fn forward(&mut self, dt: f64, outside_speed: f64); fn turn_left(&mut self, dt: f64); fn turn_right(&mut self, dt: f64); fn update_jump(&mut self, dt: f64); fn jump(&mut self); fn pos(&self) -> Vector3<f64>; fn turn_speed(&self) -> f64; } // Car with shape of a box #[derive(Clone)] pub struct BoxCar { pub size: Vector3<f64>, pub position: Vector3<f64>, pub speed: f64, pub turn_speed: f64, pub color: Color, pub jump_v: f64, pub jump_a: f64, pub jumping: bool, pub current_t: f64, pub jump_turn_decrease: f64, } impl Car for BoxCar { fn render(&self, camera: &Camera) -> Vec<([Vector2<f64>; 2], Color)> { let mut front = [self.position; 4]; front[0].y += self.size.y; front[1].y += self.size.y; front[0].x -= self.size.x / 2.; front[3].x -= self.size.x / 2.; front[1].x += self.size.x / 2.; front[2].x += self.size.x / 2.; let mut rear = front; for x in &mut rear { x.z += self.size.z; } let mut ret = Vec::new(); for i in 0..4 { ret.push(camera.render_line(&front[i], &front[(i + 1) % 4])); ret.push(camera.render_line(&rear[i], &rear[(i + 1) % 4])); ret.push(camera.render_line(&front[i], &rear[i])); } ret.into_iter() .filter_map(|x| x.map(|x| (x, self.color))) .collect() } fn turn_left(&mut self, dt: f64) { self.position.x -= dt * self.turn_speed(); } fn turn_right(&mut self, dt: f64) { self.position.x += dt * self.turn_speed(); } fn pos(&self) -> Vector3<f64> { self.position } fn crashed(&self, a: &Self) -> bool { (f64::abs(self.position.x - a.position.x) < (self.size.x + a.size.x) / 2.) && ((self.position.z < a.position.z && a.position.z - self.position.z < self.size.z) || (self.position.z >= a.position.z && self.position.z - a.position.z < a.size.z)) && ((self.position.y < a.position.y && a.position.y - self.position.y < self.size.y) || (self.position.y >= a.position.y && self.position.y - a.position.y < a.size.y)) } fn jump(&mut self) { if self.jumping || self.position.y > 0. { } else
} fn forward(&mut self, dt: f64, outside_speed: f64) { self.position.z -= dt * (self.speed + outside_speed); self.update_jump(dt); } fn update_jump(&mut self, dt: f64) { if self.jumping { self.current_t += dt; self.position.y = self.current_t * (self.jump_v - 0.5 * self.jump_a * self.current_t); if self.position.y < 0. { self.position.y = 0.; self.jumping = false; } } } fn hit(&self, bullet: &[Vector3<f64>; 3]) -> bool { let (x, y) = (bullet[0], bullet[0] + bullet[1]); let check = |x: &Vector3<f64>| { f64::abs(x.x - self.position.x) < self.size.x / 2. && x.y >= self.position.y && x.y - self.position.y < self.size.y && x.z >= self.position.z && x.z - self.position.z < self.size.z }; check(&x) || check(&y) } fn turn_speed(&self) -> f64 { if self.jumping { self.turn_speed / self.jump_turn_decrease } else { self.turn_speed } } }
{ self.jumping = true; self.current_t = 0.; }
conditional_block
codegen.rs
//! Various helpers for code-generation. use std::io; #[cfg(feature = "pattern_class")] use std::cmp; use std::char; use std::iter; use std::usize; #[cfg(all(test, feature = "pattern_class"))] use std::iter::FromIterator; #[cfg(feature = "pattern_class")] use super::{Atom, Class, ClassMember}; use super::SizeBound; // ================================================================ /// Trait for atom types that can be converted to byte sequences. pub trait Bytes<'a> { /// Iterator type returned by `bytes`. type Iter: 'a + Iterator<Item=u8>; /// Fetch an iterator over "self" as a series of bytes. fn bytes(&self) -> Self::Iter; } /// Interface for types which can bound the number of bytes required to match /// a particular instance of themselves. pub trait SizedRead { /// Get the size of this object when read directly from something /// implementing `std::io::Read`. fn read_size(&self) -> SizeBound; } /// Trait for use with fixed-size types pub trait ReadToBuffer { /// Read at most `max_count` instances of this atom type from the given /// stream, placing them into the supplied buffer. fn read_to_buffer<R>(r: &mut R, dest: &mut [u8], max_count: usize) -> io::Result<usize> where R: io::Read; } // ---------------------------------------------------------------- // Implementations impl<'a> Bytes<'a> for u8 { type Iter = iter::Once<u8>; fn bytes(&self) -> Self::Iter { iter::once(*self) } } impl SizedRead for u8 { #[inline(always)] fn read_size(&self) -> SizeBound { SizeBound::Exact(1) } } impl ReadToBuffer for u8 { #[inline(always)] fn read_to_buffer<R>(r: &mut R, dest: &mut [u8], max_count: usize) -> io::Result<usize> where R: io::Read { r.read(&mut dest[0..max_count]) } } // ---------------------------------------------------------------- // This table was copied from the Rust source tree, // file "src/libcore/str/mod.rs". // https://tools.ietf.org/html/rfc3629 static UTF8_CHAR_WIDTH: [u8; 256] = [ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF ]; /*impl<'a> Bytes<'a> for char { type Iter = ::std::char::EncodeUtf8; fn bytes(&self) -> Self::Iter { self.encode_utf8() } }*/ impl SizedRead for char { #[inline] fn read_size(&self) -> SizeBound { self.len_utf8().into() } } impl ReadToBuffer for char { #[inline] fn read_to_buffer<R>(r: &mut R, dest: &mut [u8], max_count: usize) -> io::Result<usize> where R: io::Read { let mut i = 0; let mut n = 0; while i < dest.len() && n < max_count { try!(r.read_exact(&mut dest[i..(i+1)])); let w = UTF8_CHAR_WIDTH[dest[i] as usize]; try!(r.read_exact(&mut dest[(i+1)..(i + w as usize)])); i += w as usize; n += 1; } Ok(i) } } #[cfg(test)] #[test] fn test_sizedread_char() { assert_eq!(SizeBound::Exact(1), 'a'.read_size()); assert_eq!(SizeBound::Exact(3), 'βœ“'.read_size()); } #[cfg(test)] #[test] fn test_readable_char() { let mut buf = ['\0' as u8; 32]; { let mut r = io::repeat('a' as u8); assert_eq!(3, char::read_to_buffer(&mut r, &mut buf, 3).unwrap()); assert_eq!(&['a' as u8 as u8, 'a' as u8, 'a' as u8, '\0' as u8], &buf[0..4]); } { let s = "βœ“β˜ βš”"; let mut r = io::Cursor::new(s.as_bytes()); assert_eq!(9, char::read_to_buffer(&mut r, &mut buf, 3).unwrap()); assert_eq!(s.as_bytes(), &buf[0..9]); } } // ---------------------------------------------------------------- /*impl<T> SizedRead for Transition<T> where T: Atom + SizedRead { fn read_size(&self) -> SizeBound { match self { &Transition::Atom(a) => a.read_size(), &Transition::Literal(ref atoms) => atoms.iter().map(|a| a.read_size()).sum(), &Transition::Wildcard => SizeBound::Range(1, 4), &Transition::Anchor(..) => SizeBound::Exact(0), &Transition::Class(ref c) => c.read_size(), } } }*/ #[cfg(test)] #[test] fn test_siz
assert_eq!(SizeBound::Exact(1), 'a'.read_size()); assert_eq!(SizeBound::Exact(3), 'βœ“'.read_size()); #[cfg(feature = "pattern_class")] assert_eq!(SizeBound::Range(1, 3), Class::from_iter(['x', 'y', 'βš”'].into_iter().cloned()).read_size()); } // ---------------------------------------------------------------- #[cfg(feature = "pattern_class")] impl<T> SizedRead for ClassMember<T> where T: Atom + SizedRead { fn read_size(&self) -> SizeBound { match self { &ClassMember::Atom(a) => a.read_size(), &ClassMember::Range(first, last) => { // We'll assume that any differences in read size between // `first` and `last` follow a linear function between the two; // this _assumption_ allows us to avoid evaluating `read_size` // for every single member of the range. let frs = first.read_size(); let lrs = last.read_size(); (cmp::min(frs.min(), lrs.min())..(cmp::max(frs.max(), lrs.max()) + 1)).into() } } } } #[cfg(feature = "pattern_class")] impl<T> SizedRead for Class<T> where T: Atom + SizedRead { fn read_size(&self) -> SizeBound { let mut min = usize::MAX; let mut max = usize::MIN; for m in self.iter_members() { let rs = m.read_size(); min = cmp::min(min, rs.min()); max = cmp::max(max, rs.max()); } (min..(max + 1)).into() } }
edread() {
identifier_name
codegen.rs
//! Various helpers for code-generation. use std::io;
use std::usize; #[cfg(all(test, feature = "pattern_class"))] use std::iter::FromIterator; #[cfg(feature = "pattern_class")] use super::{Atom, Class, ClassMember}; use super::SizeBound; // ================================================================ /// Trait for atom types that can be converted to byte sequences. pub trait Bytes<'a> { /// Iterator type returned by `bytes`. type Iter: 'a + Iterator<Item=u8>; /// Fetch an iterator over "self" as a series of bytes. fn bytes(&self) -> Self::Iter; } /// Interface for types which can bound the number of bytes required to match /// a particular instance of themselves. pub trait SizedRead { /// Get the size of this object when read directly from something /// implementing `std::io::Read`. fn read_size(&self) -> SizeBound; } /// Trait for use with fixed-size types pub trait ReadToBuffer { /// Read at most `max_count` instances of this atom type from the given /// stream, placing them into the supplied buffer. fn read_to_buffer<R>(r: &mut R, dest: &mut [u8], max_count: usize) -> io::Result<usize> where R: io::Read; } // ---------------------------------------------------------------- // Implementations impl<'a> Bytes<'a> for u8 { type Iter = iter::Once<u8>; fn bytes(&self) -> Self::Iter { iter::once(*self) } } impl SizedRead for u8 { #[inline(always)] fn read_size(&self) -> SizeBound { SizeBound::Exact(1) } } impl ReadToBuffer for u8 { #[inline(always)] fn read_to_buffer<R>(r: &mut R, dest: &mut [u8], max_count: usize) -> io::Result<usize> where R: io::Read { r.read(&mut dest[0..max_count]) } } // ---------------------------------------------------------------- // This table was copied from the Rust source tree, // file "src/libcore/str/mod.rs". // https://tools.ietf.org/html/rfc3629 static UTF8_CHAR_WIDTH: [u8; 256] = [ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF ]; /*impl<'a> Bytes<'a> for char { type Iter = ::std::char::EncodeUtf8; fn bytes(&self) -> Self::Iter { self.encode_utf8() } }*/ impl SizedRead for char { #[inline] fn read_size(&self) -> SizeBound { self.len_utf8().into() } } impl ReadToBuffer for char { #[inline] fn read_to_buffer<R>(r: &mut R, dest: &mut [u8], max_count: usize) -> io::Result<usize> where R: io::Read { let mut i = 0; let mut n = 0; while i < dest.len() && n < max_count { try!(r.read_exact(&mut dest[i..(i+1)])); let w = UTF8_CHAR_WIDTH[dest[i] as usize]; try!(r.read_exact(&mut dest[(i+1)..(i + w as usize)])); i += w as usize; n += 1; } Ok(i) } } #[cfg(test)] #[test] fn test_sizedread_char() { assert_eq!(SizeBound::Exact(1), 'a'.read_size()); assert_eq!(SizeBound::Exact(3), 'βœ“'.read_size()); } #[cfg(test)] #[test] fn test_readable_char() { let mut buf = ['\0' as u8; 32]; { let mut r = io::repeat('a' as u8); assert_eq!(3, char::read_to_buffer(&mut r, &mut buf, 3).unwrap()); assert_eq!(&['a' as u8 as u8, 'a' as u8, 'a' as u8, '\0' as u8], &buf[0..4]); } { let s = "βœ“β˜ βš”"; let mut r = io::Cursor::new(s.as_bytes()); assert_eq!(9, char::read_to_buffer(&mut r, &mut buf, 3).unwrap()); assert_eq!(s.as_bytes(), &buf[0..9]); } } // ---------------------------------------------------------------- /*impl<T> SizedRead for Transition<T> where T: Atom + SizedRead { fn read_size(&self) -> SizeBound { match self { &Transition::Atom(a) => a.read_size(), &Transition::Literal(ref atoms) => atoms.iter().map(|a| a.read_size()).sum(), &Transition::Wildcard => SizeBound::Range(1, 4), &Transition::Anchor(..) => SizeBound::Exact(0), &Transition::Class(ref c) => c.read_size(), } } }*/ #[cfg(test)] #[test] fn test_sizedread() { assert_eq!(SizeBound::Exact(1), 'a'.read_size()); assert_eq!(SizeBound::Exact(3), 'βœ“'.read_size()); #[cfg(feature = "pattern_class")] assert_eq!(SizeBound::Range(1, 3), Class::from_iter(['x', 'y', 'βš”'].into_iter().cloned()).read_size()); } // ---------------------------------------------------------------- #[cfg(feature = "pattern_class")] impl<T> SizedRead for ClassMember<T> where T: Atom + SizedRead { fn read_size(&self) -> SizeBound { match self { &ClassMember::Atom(a) => a.read_size(), &ClassMember::Range(first, last) => { // We'll assume that any differences in read size between // `first` and `last` follow a linear function between the two; // this _assumption_ allows us to avoid evaluating `read_size` // for every single member of the range. let frs = first.read_size(); let lrs = last.read_size(); (cmp::min(frs.min(), lrs.min())..(cmp::max(frs.max(), lrs.max()) + 1)).into() } } } } #[cfg(feature = "pattern_class")] impl<T> SizedRead for Class<T> where T: Atom + SizedRead { fn read_size(&self) -> SizeBound { let mut min = usize::MAX; let mut max = usize::MIN; for m in self.iter_members() { let rs = m.read_size(); min = cmp::min(min, rs.min()); max = cmp::max(max, rs.max()); } (min..(max + 1)).into() } }
#[cfg(feature = "pattern_class")] use std::cmp; use std::char; use std::iter;
random_line_split
codegen.rs
//! Various helpers for code-generation. use std::io; #[cfg(feature = "pattern_class")] use std::cmp; use std::char; use std::iter; use std::usize; #[cfg(all(test, feature = "pattern_class"))] use std::iter::FromIterator; #[cfg(feature = "pattern_class")] use super::{Atom, Class, ClassMember}; use super::SizeBound; // ================================================================ /// Trait for atom types that can be converted to byte sequences. pub trait Bytes<'a> { /// Iterator type returned by `bytes`. type Iter: 'a + Iterator<Item=u8>; /// Fetch an iterator over "self" as a series of bytes. fn bytes(&self) -> Self::Iter; } /// Interface for types which can bound the number of bytes required to match /// a particular instance of themselves. pub trait SizedRead { /// Get the size of this object when read directly from something /// implementing `std::io::Read`. fn read_size(&self) -> SizeBound; } /// Trait for use with fixed-size types pub trait ReadToBuffer { /// Read at most `max_count` instances of this atom type from the given /// stream, placing them into the supplied buffer. fn read_to_buffer<R>(r: &mut R, dest: &mut [u8], max_count: usize) -> io::Result<usize> where R: io::Read; } // ---------------------------------------------------------------- // Implementations impl<'a> Bytes<'a> for u8 { type Iter = iter::Once<u8>; fn bytes(&self) -> Self::Iter { iter::once(*self) } } impl SizedRead for u8 { #[inline(always)] fn read_size(&self) -> SizeBound { SizeBound::Exact(1) } } impl ReadToBuffer for u8 { #[inline(always)] fn read_to_buffer<R>(r: &mut R, dest: &mut [u8], max_count: usize) -> io::Result<usize> where R: io::Read { r.read(&mut dest[0..max_count]) } } // ---------------------------------------------------------------- // This table was copied from the Rust source tree, // file "src/libcore/str/mod.rs". // https://tools.ietf.org/html/rfc3629 static UTF8_CHAR_WIDTH: [u8; 256] = [ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF ]; /*impl<'a> Bytes<'a> for char { type Iter = ::std::char::EncodeUtf8; fn bytes(&self) -> Self::Iter { self.encode_utf8() } }*/ impl SizedRead for char { #[inline] fn read_size(&self) -> SizeBound { self.len_utf8().into() } } impl ReadToBuffer for char { #[inline] fn read_to_buffer<R>(r: &mut R, dest: &mut [u8], max_count: usize) -> io::Result<usize> where R: io::Read
} #[cfg(test)] #[test] fn test_sizedread_char() { assert_eq!(SizeBound::Exact(1), 'a'.read_size()); assert_eq!(SizeBound::Exact(3), 'βœ“'.read_size()); } #[cfg(test)] #[test] fn test_readable_char() { let mut buf = ['\0' as u8; 32]; { let mut r = io::repeat('a' as u8); assert_eq!(3, char::read_to_buffer(&mut r, &mut buf, 3).unwrap()); assert_eq!(&['a' as u8 as u8, 'a' as u8, 'a' as u8, '\0' as u8], &buf[0..4]); } { let s = "βœ“β˜ βš”"; let mut r = io::Cursor::new(s.as_bytes()); assert_eq!(9, char::read_to_buffer(&mut r, &mut buf, 3).unwrap()); assert_eq!(s.as_bytes(), &buf[0..9]); } } // ---------------------------------------------------------------- /*impl<T> SizedRead for Transition<T> where T: Atom + SizedRead { fn read_size(&self) -> SizeBound { match self { &Transition::Atom(a) => a.read_size(), &Transition::Literal(ref atoms) => atoms.iter().map(|a| a.read_size()).sum(), &Transition::Wildcard => SizeBound::Range(1, 4), &Transition::Anchor(..) => SizeBound::Exact(0), &Transition::Class(ref c) => c.read_size(), } } }*/ #[cfg(test)] #[test] fn test_sizedread() { assert_eq!(SizeBound::Exact(1), 'a'.read_size()); assert_eq!(SizeBound::Exact(3), 'βœ“'.read_size()); #[cfg(feature = "pattern_class")] assert_eq!(SizeBound::Range(1, 3), Class::from_iter(['x', 'y', 'βš”'].into_iter().cloned()).read_size()); } // ---------------------------------------------------------------- #[cfg(feature = "pattern_class")] impl<T> SizedRead for ClassMember<T> where T: Atom + SizedRead { fn read_size(&self) -> SizeBound { match self { &ClassMember::Atom(a) => a.read_size(), &ClassMember::Range(first, last) => { // We'll assume that any differences in read size between // `first` and `last` follow a linear function between the two; // this _assumption_ allows us to avoid evaluating `read_size` // for every single member of the range. let frs = first.read_size(); let lrs = last.read_size(); (cmp::min(frs.min(), lrs.min())..(cmp::max(frs.max(), lrs.max()) + 1)).into() } } } } #[cfg(feature = "pattern_class")] impl<T> SizedRead for Class<T> where T: Atom + SizedRead { fn read_size(&self) -> SizeBound { let mut min = usize::MAX; let mut max = usize::MIN; for m in self.iter_members() { let rs = m.read_size(); min = cmp::min(min, rs.min()); max = cmp::max(max, rs.max()); } (min..(max + 1)).into() } }
{ let mut i = 0; let mut n = 0; while i < dest.len() && n < max_count { try!(r.read_exact(&mut dest[i..(i+1)])); let w = UTF8_CHAR_WIDTH[dest[i] as usize]; try!(r.read_exact(&mut dest[(i+1)..(i + w as usize)])); i += w as usize; n += 1; } Ok(i) }
identifier_body
mutation.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Tracking of commit mutations (amends, rebases, etc.) use std::io::{Read, Write}; use anyhow::{anyhow, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use vlqencoding::{VLQDecode, VLQEncode}; use crate::node::{Node, ReadNodeExt, WriteNodeExt}; #[derive(Clone, PartialEq, PartialOrd)] pub struct MutationEntry { pub succ: Node, pub preds: Vec<Node>, pub split: Vec<Node>, pub op: String, pub user: String, pub time: i64, pub tz: i32, pub extra: Vec<(Box<[u8]>, Box<[u8]>)>, } /// Default size for a buffer that will be used for serializing a mutation entry. /// /// This is: /// * Version (1 byte) /// * Successor hash (20 bytes) /// * Predecessor count (1 byte) /// * Predecessor hash (20 bytes) - most entries have only one predecessor /// * Operation (~7 bytes) - e.g. amend, rebase /// * User (~40 bytes) /// * Time (4-8 bytes) /// * Timezone (~2 bytes) /// * Extra count (1 byte) pub const DEFAULT_ENTRY_SIZE: usize = 100; const DEFAULT_VERSION: u8 = 1; impl MutationEntry { pub fn serialize(&self, w: &mut dyn Write) -> Result<()>
w.write_all(&key)?; w.write_vlq(value.len())?; w.write_all(&value)?; } Ok(()) } pub fn deserialize(r: &mut dyn Read) -> Result<Self> { enum EntryFormat { FloatDate, Latest, } let format = match r.read_u8()? { 0 => return Err(anyhow!("invalid mutation entry version: 0")), 1..=4 => { // These versions stored the date as an f64. EntryFormat::FloatDate } 5 => EntryFormat::Latest, v => return Err(anyhow!("unsupported mutation entry version: {}", v)), }; let succ = r.read_node()?; let pred_count = r.read_vlq()?; let mut preds = Vec::with_capacity(pred_count); for _ in 0..pred_count { preds.push(r.read_node()?); } let split_count = r.read_vlq()?; let mut split = Vec::with_capacity(split_count); for _ in 0..split_count { split.push(r.read_node()?); } let op_len = r.read_vlq()?; let mut op = vec![0; op_len]; r.read_exact(&mut op)?; let op = String::from_utf8(op)?; let user_len = r.read_vlq()?; let mut user = vec![0; user_len]; r.read_exact(&mut user)?; let user = String::from_utf8(user)?; let time = match format { EntryFormat::FloatDate => { // The date was stored as a floating point number. We // actually want an integer, so truncate and convert. r.read_f64::<BigEndian>()?.trunc() as i64 } _ => r.read_vlq()?, }; let tz = r.read_vlq()?; let extra_count = r.read_vlq()?; let mut extra = Vec::with_capacity(extra_count); for _ in 0..extra_count { let key_len = r.read_vlq()?; let mut key = vec![0; key_len]; r.read_exact(&mut key)?; let value_len = r.read_vlq()?; let mut value = vec![0; value_len]; r.read_exact(&mut value)?; extra.push((key.into_boxed_slice(), value.into_boxed_slice())); } Ok(MutationEntry { succ, preds, split, op, user, time, tz, extra, }) } /// Return true if this represents an 1:1 commit replacement. /// A split or a fold are not 1:1 replacement. /// /// Note: Resolving divergence should use multiple 1:1 records /// and are considered 1:1 replacements. /// /// If this function returns true, `preds` is ensured to only /// have one item. pub fn is_one_to_one(&self) -> bool { self.split.is_empty() && self.preds.len() == 1 } }
{ w.write_u8(DEFAULT_VERSION)?; w.write_node(&self.succ)?; w.write_vlq(self.preds.len())?; for pred in self.preds.iter() { w.write_node(pred)?; } w.write_vlq(self.split.len())?; for split in self.split.iter() { w.write_node(split)?; } w.write_vlq(self.op.len())?; w.write_all(self.op.as_bytes())?; w.write_vlq(self.user.len())?; w.write_all(&self.user.as_bytes())?; w.write_f64::<BigEndian>(self.time as f64)?; w.write_vlq(self.tz)?; w.write_vlq(self.extra.len())?; for (key, value) in self.extra.iter() { w.write_vlq(key.len())?;
identifier_body
mutation.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Tracking of commit mutations (amends, rebases, etc.) use std::io::{Read, Write}; use anyhow::{anyhow, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use vlqencoding::{VLQDecode, VLQEncode}; use crate::node::{Node, ReadNodeExt, WriteNodeExt}; #[derive(Clone, PartialEq, PartialOrd)] pub struct MutationEntry { pub succ: Node, pub preds: Vec<Node>, pub split: Vec<Node>, pub op: String, pub user: String, pub time: i64, pub tz: i32, pub extra: Vec<(Box<[u8]>, Box<[u8]>)>, } /// Default size for a buffer that will be used for serializing a mutation entry. /// /// This is: /// * Version (1 byte) /// * Successor hash (20 bytes) /// * Predecessor count (1 byte) /// * Predecessor hash (20 bytes) - most entries have only one predecessor /// * Operation (~7 bytes) - e.g. amend, rebase /// * User (~40 bytes) /// * Time (4-8 bytes) /// * Timezone (~2 bytes) /// * Extra count (1 byte) pub const DEFAULT_ENTRY_SIZE: usize = 100; const DEFAULT_VERSION: u8 = 1; impl MutationEntry { pub fn serialize(&self, w: &mut dyn Write) -> Result<()> { w.write_u8(DEFAULT_VERSION)?; w.write_node(&self.succ)?; w.write_vlq(self.preds.len())?; for pred in self.preds.iter() { w.write_node(pred)?; } w.write_vlq(self.split.len())?; for split in self.split.iter() { w.write_node(split)?; } w.write_vlq(self.op.len())?; w.write_all(self.op.as_bytes())?; w.write_vlq(self.user.len())?; w.write_all(&self.user.as_bytes())?; w.write_f64::<BigEndian>(self.time as f64)?; w.write_vlq(self.tz)?; w.write_vlq(self.extra.len())?; for (key, value) in self.extra.iter() { w.write_vlq(key.len())?; w.write_all(&key)?; w.write_vlq(value.len())?; w.write_all(&value)?; } Ok(()) } pub fn deserialize(r: &mut dyn Read) -> Result<Self> { enum EntryFormat { FloatDate, Latest, } let format = match r.read_u8()? { 0 => return Err(anyhow!("invalid mutation entry version: 0")), 1..=4 => { // These versions stored the date as an f64. EntryFormat::FloatDate } 5 => EntryFormat::Latest, v => return Err(anyhow!("unsupported mutation entry version: {}", v)), }; let succ = r.read_node()?; let pred_count = r.read_vlq()?; let mut preds = Vec::with_capacity(pred_count); for _ in 0..pred_count { preds.push(r.read_node()?); } let split_count = r.read_vlq()?; let mut split = Vec::with_capacity(split_count); for _ in 0..split_count { split.push(r.read_node()?); } let op_len = r.read_vlq()?; let mut op = vec![0; op_len]; r.read_exact(&mut op)?; let op = String::from_utf8(op)?; let user_len = r.read_vlq()?; let mut user = vec![0; user_len]; r.read_exact(&mut user)?; let user = String::from_utf8(user)?; let time = match format { EntryFormat::FloatDate =>
_ => r.read_vlq()?, }; let tz = r.read_vlq()?; let extra_count = r.read_vlq()?; let mut extra = Vec::with_capacity(extra_count); for _ in 0..extra_count { let key_len = r.read_vlq()?; let mut key = vec![0; key_len]; r.read_exact(&mut key)?; let value_len = r.read_vlq()?; let mut value = vec![0; value_len]; r.read_exact(&mut value)?; extra.push((key.into_boxed_slice(), value.into_boxed_slice())); } Ok(MutationEntry { succ, preds, split, op, user, time, tz, extra, }) } /// Return true if this represents an 1:1 commit replacement. /// A split or a fold are not 1:1 replacement. /// /// Note: Resolving divergence should use multiple 1:1 records /// and are considered 1:1 replacements. /// /// If this function returns true, `preds` is ensured to only /// have one item. pub fn is_one_to_one(&self) -> bool { self.split.is_empty() && self.preds.len() == 1 } }
{ // The date was stored as a floating point number. We // actually want an integer, so truncate and convert. r.read_f64::<BigEndian>()?.trunc() as i64 }
conditional_block
mutation.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. *
//! Tracking of commit mutations (amends, rebases, etc.) use std::io::{Read, Write}; use anyhow::{anyhow, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use vlqencoding::{VLQDecode, VLQEncode}; use crate::node::{Node, ReadNodeExt, WriteNodeExt}; #[derive(Clone, PartialEq, PartialOrd)] pub struct MutationEntry { pub succ: Node, pub preds: Vec<Node>, pub split: Vec<Node>, pub op: String, pub user: String, pub time: i64, pub tz: i32, pub extra: Vec<(Box<[u8]>, Box<[u8]>)>, } /// Default size for a buffer that will be used for serializing a mutation entry. /// /// This is: /// * Version (1 byte) /// * Successor hash (20 bytes) /// * Predecessor count (1 byte) /// * Predecessor hash (20 bytes) - most entries have only one predecessor /// * Operation (~7 bytes) - e.g. amend, rebase /// * User (~40 bytes) /// * Time (4-8 bytes) /// * Timezone (~2 bytes) /// * Extra count (1 byte) pub const DEFAULT_ENTRY_SIZE: usize = 100; const DEFAULT_VERSION: u8 = 1; impl MutationEntry { pub fn serialize(&self, w: &mut dyn Write) -> Result<()> { w.write_u8(DEFAULT_VERSION)?; w.write_node(&self.succ)?; w.write_vlq(self.preds.len())?; for pred in self.preds.iter() { w.write_node(pred)?; } w.write_vlq(self.split.len())?; for split in self.split.iter() { w.write_node(split)?; } w.write_vlq(self.op.len())?; w.write_all(self.op.as_bytes())?; w.write_vlq(self.user.len())?; w.write_all(&self.user.as_bytes())?; w.write_f64::<BigEndian>(self.time as f64)?; w.write_vlq(self.tz)?; w.write_vlq(self.extra.len())?; for (key, value) in self.extra.iter() { w.write_vlq(key.len())?; w.write_all(&key)?; w.write_vlq(value.len())?; w.write_all(&value)?; } Ok(()) } pub fn deserialize(r: &mut dyn Read) -> Result<Self> { enum EntryFormat { FloatDate, Latest, } let format = match r.read_u8()? { 0 => return Err(anyhow!("invalid mutation entry version: 0")), 1..=4 => { // These versions stored the date as an f64. EntryFormat::FloatDate } 5 => EntryFormat::Latest, v => return Err(anyhow!("unsupported mutation entry version: {}", v)), }; let succ = r.read_node()?; let pred_count = r.read_vlq()?; let mut preds = Vec::with_capacity(pred_count); for _ in 0..pred_count { preds.push(r.read_node()?); } let split_count = r.read_vlq()?; let mut split = Vec::with_capacity(split_count); for _ in 0..split_count { split.push(r.read_node()?); } let op_len = r.read_vlq()?; let mut op = vec![0; op_len]; r.read_exact(&mut op)?; let op = String::from_utf8(op)?; let user_len = r.read_vlq()?; let mut user = vec![0; user_len]; r.read_exact(&mut user)?; let user = String::from_utf8(user)?; let time = match format { EntryFormat::FloatDate => { // The date was stored as a floating point number. We // actually want an integer, so truncate and convert. r.read_f64::<BigEndian>()?.trunc() as i64 } _ => r.read_vlq()?, }; let tz = r.read_vlq()?; let extra_count = r.read_vlq()?; let mut extra = Vec::with_capacity(extra_count); for _ in 0..extra_count { let key_len = r.read_vlq()?; let mut key = vec![0; key_len]; r.read_exact(&mut key)?; let value_len = r.read_vlq()?; let mut value = vec![0; value_len]; r.read_exact(&mut value)?; extra.push((key.into_boxed_slice(), value.into_boxed_slice())); } Ok(MutationEntry { succ, preds, split, op, user, time, tz, extra, }) } /// Return true if this represents an 1:1 commit replacement. /// A split or a fold are not 1:1 replacement. /// /// Note: Resolving divergence should use multiple 1:1 records /// and are considered 1:1 replacements. /// /// If this function returns true, `preds` is ensured to only /// have one item. pub fn is_one_to_one(&self) -> bool { self.split.is_empty() && self.preds.len() == 1 } }
* This software may be used and distributed according to the terms of the * GNU General Public License version 2. */
random_line_split
mutation.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Tracking of commit mutations (amends, rebases, etc.) use std::io::{Read, Write}; use anyhow::{anyhow, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use vlqencoding::{VLQDecode, VLQEncode}; use crate::node::{Node, ReadNodeExt, WriteNodeExt}; #[derive(Clone, PartialEq, PartialOrd)] pub struct
{ pub succ: Node, pub preds: Vec<Node>, pub split: Vec<Node>, pub op: String, pub user: String, pub time: i64, pub tz: i32, pub extra: Vec<(Box<[u8]>, Box<[u8]>)>, } /// Default size for a buffer that will be used for serializing a mutation entry. /// /// This is: /// * Version (1 byte) /// * Successor hash (20 bytes) /// * Predecessor count (1 byte) /// * Predecessor hash (20 bytes) - most entries have only one predecessor /// * Operation (~7 bytes) - e.g. amend, rebase /// * User (~40 bytes) /// * Time (4-8 bytes) /// * Timezone (~2 bytes) /// * Extra count (1 byte) pub const DEFAULT_ENTRY_SIZE: usize = 100; const DEFAULT_VERSION: u8 = 1; impl MutationEntry { pub fn serialize(&self, w: &mut dyn Write) -> Result<()> { w.write_u8(DEFAULT_VERSION)?; w.write_node(&self.succ)?; w.write_vlq(self.preds.len())?; for pred in self.preds.iter() { w.write_node(pred)?; } w.write_vlq(self.split.len())?; for split in self.split.iter() { w.write_node(split)?; } w.write_vlq(self.op.len())?; w.write_all(self.op.as_bytes())?; w.write_vlq(self.user.len())?; w.write_all(&self.user.as_bytes())?; w.write_f64::<BigEndian>(self.time as f64)?; w.write_vlq(self.tz)?; w.write_vlq(self.extra.len())?; for (key, value) in self.extra.iter() { w.write_vlq(key.len())?; w.write_all(&key)?; w.write_vlq(value.len())?; w.write_all(&value)?; } Ok(()) } pub fn deserialize(r: &mut dyn Read) -> Result<Self> { enum EntryFormat { FloatDate, Latest, } let format = match r.read_u8()? { 0 => return Err(anyhow!("invalid mutation entry version: 0")), 1..=4 => { // These versions stored the date as an f64. EntryFormat::FloatDate } 5 => EntryFormat::Latest, v => return Err(anyhow!("unsupported mutation entry version: {}", v)), }; let succ = r.read_node()?; let pred_count = r.read_vlq()?; let mut preds = Vec::with_capacity(pred_count); for _ in 0..pred_count { preds.push(r.read_node()?); } let split_count = r.read_vlq()?; let mut split = Vec::with_capacity(split_count); for _ in 0..split_count { split.push(r.read_node()?); } let op_len = r.read_vlq()?; let mut op = vec![0; op_len]; r.read_exact(&mut op)?; let op = String::from_utf8(op)?; let user_len = r.read_vlq()?; let mut user = vec![0; user_len]; r.read_exact(&mut user)?; let user = String::from_utf8(user)?; let time = match format { EntryFormat::FloatDate => { // The date was stored as a floating point number. We // actually want an integer, so truncate and convert. r.read_f64::<BigEndian>()?.trunc() as i64 } _ => r.read_vlq()?, }; let tz = r.read_vlq()?; let extra_count = r.read_vlq()?; let mut extra = Vec::with_capacity(extra_count); for _ in 0..extra_count { let key_len = r.read_vlq()?; let mut key = vec![0; key_len]; r.read_exact(&mut key)?; let value_len = r.read_vlq()?; let mut value = vec![0; value_len]; r.read_exact(&mut value)?; extra.push((key.into_boxed_slice(), value.into_boxed_slice())); } Ok(MutationEntry { succ, preds, split, op, user, time, tz, extra, }) } /// Return true if this represents an 1:1 commit replacement. /// A split or a fold are not 1:1 replacement. /// /// Note: Resolving divergence should use multiple 1:1 records /// and are considered 1:1 replacements. /// /// If this function returns true, `preds` is ensured to only /// have one item. pub fn is_one_to_one(&self) -> bool { self.split.is_empty() && self.preds.len() == 1 } }
MutationEntry
identifier_name
pseudo_element_definition.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ /// Gecko's pseudo-element definition. #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)] pub enum PseudoElement { % for pseudo in PSEUDOS: /// ${pseudo.value} % if pseudo.is_tree_pseudo_element(): ${pseudo.capitalized_pseudo()}(ThinBoxedSlice<Atom>), % else: ${pseudo.capitalized_pseudo()}, % endif % endfor /// ::-webkit-* that we don't recognize /// https://github.com/whatwg/compat/issues/103 UnknownWebkit(Atom), } /// Important: If you change this, you should also update Gecko's /// nsCSSPseudoElements::IsEagerlyCascadedInServo. <% EAGER_PSEUDOS = ["Before", "After", "FirstLine", "FirstLetter"] %> <% TREE_PSEUDOS = [pseudo for pseudo in PSEUDOS if pseudo.is_tree_pseudo_element()] %> <% SIMPLE_PSEUDOS = [pseudo for pseudo in PSEUDOS if not pseudo.is_tree_pseudo_element()] %> /// The number of eager pseudo-elements. pub const EAGER_PSEUDO_COUNT: usize = ${len(EAGER_PSEUDOS)}; /// The number of non-functional pseudo-elements. pub const SIMPLE_PSEUDO_COUNT: usize = ${len(SIMPLE_PSEUDOS)}; /// The number of tree pseudo-elements. pub const TREE_PSEUDO_COUNT: usize = ${len(TREE_PSEUDOS)}; /// The number of all pseudo-elements. pub const PSEUDO_COUNT: usize = ${len(PSEUDOS)}; /// The list of eager pseudos. pub const EAGER_PSEUDOS: [PseudoElement; EAGER_PSEUDO_COUNT] = [ % for eager_pseudo_name in EAGER_PSEUDOS: PseudoElement::${eager_pseudo_name}, % endfor ]; <%def name="pseudo_element_variant(pseudo, tree_arg='..')">\ PseudoElement::${pseudo.capitalized_pseudo()}${"({})".format(tree_arg) if pseudo.is_tree_pseudo_element() else ""}\ </%def> impl PseudoElement { /// Returns an index of the pseudo-element. #[inline] pub fn index(&self) -> usize { match *self { % for i, pseudo in enumerate(PSEUDOS): ${pseudo_element_variant(pseudo)} => ${i}, % endfor PseudoElement::UnknownWebkit(..) => unreachable!(), } } /// Returns an array of `None` values. /// /// FIXME(emilio): Integer generics can't come soon enough. pub fn pseudo_none_array<T>() -> [Option<T>; PSEUDO_COUNT] { [ ${",\n ".join(["None" for pseudo in PSEUDOS])} ] } /// Whether this pseudo-element is an anonymous box. #[inline] pub fn is_anon_box(&self) -> bool { match *self { % for pseudo in PSEUDOS: % if pseudo.is_anon_box(): ${pseudo_element_variant(pseudo)} => true, % endif % endfor _ => false, } } /// Whether this pseudo-element is eagerly-cascaded. #[inline] pub fn is_eager(&self) -> bool { matches!(*self, ${" | ".join(map(lambda name: "PseudoElement::{}".format(name), EAGER_PSEUDOS))}) } /// Whether this pseudo-element is tree pseudo-element. #[inline] pub fn is_tree_pseudo_element(&self) -> bool { match *self { % for pseudo in TREE_PSEUDOS: ${pseudo_element_variant(pseudo)} => true, % endfor _ => false, } } /// Whether this pseudo-element is an unknown Webkit-prefixed pseudo-element. #[inline] pub fn is_unknown_webkit_pseudo_element(&self) -> bool { matches!(*self, PseudoElement::UnknownWebkit(..)) } /// Gets the flags associated to this pseudo-element, or 0 if it's an /// anonymous box. pub fn flags(&self) -> u32 { match *self { % for pseudo in PSEUDOS: ${pseudo_element_variant(pseudo)} => % if pseudo.is_tree_pseudo_element(): if static_prefs::pref!("layout.css.xul-tree-pseudos.content.enabled") { 0 } else { structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS_AND_CHROME }, % elif pseudo.is_anon_box(): structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS, % else: structs::SERVO_CSS_PSEUDO_ELEMENT_FLAGS_${pseudo.pseudo_ident}, % endif % endfor PseudoElement::UnknownWebkit(..) => 0, } } /// Construct a pseudo-element from a `PseudoStyleType`. #[inline] pub fn from_pseudo_type(type_: PseudoStyleType) -> Option<Self> { match type_ { % for pseudo in PSEUDOS: % if not pseudo.is_tree_pseudo_element(): PseudoStyleType::${pseudo.pseudo_ident} => { Some(${pseudo_element_variant(pseudo)}) }, % endif % endfor _ => None, } } /// Construct a `PseudoStyleType` from a pseudo-element #[inline] pub fn pseudo_type(&self) -> PseudoStyleType { match *self { % for pseudo in PSEUDOS: % if pseudo.is_tree_pseudo_element(): PseudoElement::${pseudo.capitalized_pseudo()}(..) => PseudoStyleType::XULTree, % else: PseudoElement::${pseudo.capitalized_pseudo()} => PseudoStyleType::${pseudo.pseudo_ident}, % endif % endfor PseudoElement::UnknownWebkit(..) => unreachable!(), } } /// Get the argument list of a tree pseudo-element. #[inline] pub fn tree_pseudo_args(&self) -> Option<<&[Atom]> { match *self { % for pseudo in TREE_PSEUDOS: PseudoElement::${pseudo.capitalized_pseudo()}(ref args) => Some(args), % endfor _ => None, } } /// Construct a tree pseudo-element from atom and args.
% for pseudo in PSEUDOS: % if pseudo.is_tree_pseudo_element(): if atom == &atom!("${pseudo.value}") { return Some(PseudoElement::${pseudo.capitalized_pseudo()}(args.into())); } % endif % endfor None } /// Constructs a pseudo-element from a string of text. /// /// Returns `None` if the pseudo-element is not recognised. #[inline] pub fn from_slice(name: &str) -> Option<Self> { // We don't need to support tree pseudos because functional // pseudo-elements needs arguments, and thus should be created // via other methods. match_ignore_ascii_case! { name, % for pseudo in SIMPLE_PSEUDOS: "${pseudo.value[1:]}" => { return Some(${pseudo_element_variant(pseudo)}) } % endfor // Alias some legacy prefixed pseudos to their standardized name at parse time: "-moz-selection" => { return Some(PseudoElement::Selection); } "-moz-placeholder" => { return Some(PseudoElement::Placeholder); } "-moz-list-bullet" | "-moz-list-number" => { return Some(PseudoElement::Marker); } _ => { if starts_with_ignore_ascii_case(name, "-moz-tree-") { return PseudoElement::tree_pseudo_element(name, Box::new([])) } if static_prefs::pref!("layout.css.unknown-webkit-pseudo-element") { const WEBKIT_PREFIX: &str = "-webkit-"; if starts_with_ignore_ascii_case(name, WEBKIT_PREFIX) { let part = string_as_ascii_lowercase(&name[WEBKIT_PREFIX.len()..]); return Some(PseudoElement::UnknownWebkit(part.into())); } } } } None } /// Constructs a tree pseudo-element from the given name and arguments. /// "name" must start with "-moz-tree-". /// /// Returns `None` if the pseudo-element is not recognized. #[inline] pub fn tree_pseudo_element(name: &str, args: Box<[Atom]>) -> Option<Self> { debug_assert!(starts_with_ignore_ascii_case(name, "-moz-tree-")); let tree_part = &name[10..]; % for pseudo in TREE_PSEUDOS: if tree_part.eq_ignore_ascii_case("${pseudo.value[11:]}") { return Some(${pseudo_element_variant(pseudo, "args.into()")}); } % endfor None } } impl ToCss for PseudoElement { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_char(':')?; match *self { % for pseudo in PSEUDOS: ${pseudo_element_variant(pseudo)} => dest.write_str("${pseudo.value}")?, % endfor PseudoElement::UnknownWebkit(ref atom) => { dest.write_str(":-webkit-")?; serialize_atom_identifier(atom, dest)?; } } if let Some(args) = self.tree_pseudo_args() { if!args.is_empty() { dest.write_char('(')?; let mut iter = args.iter(); if let Some(first) = iter.next() { serialize_atom_identifier(&first, dest)?; for item in iter { dest.write_str(", ")?; serialize_atom_identifier(item, dest)?; } } dest.write_char(')')?; } } Ok(()) } }
#[inline] pub fn from_tree_pseudo_atom(atom: &Atom, args: Box<[Atom]>) -> Option<Self> {
random_line_split
pseudo_element_definition.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ /// Gecko's pseudo-element definition. #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)] pub enum PseudoElement { % for pseudo in PSEUDOS: /// ${pseudo.value} % if pseudo.is_tree_pseudo_element(): ${pseudo.capitalized_pseudo()}(ThinBoxedSlice<Atom>), % else: ${pseudo.capitalized_pseudo()}, % endif % endfor /// ::-webkit-* that we don't recognize /// https://github.com/whatwg/compat/issues/103 UnknownWebkit(Atom), } /// Important: If you change this, you should also update Gecko's /// nsCSSPseudoElements::IsEagerlyCascadedInServo. <% EAGER_PSEUDOS = ["Before", "After", "FirstLine", "FirstLetter"] %> <% TREE_PSEUDOS = [pseudo for pseudo in PSEUDOS if pseudo.is_tree_pseudo_element()] %> <% SIMPLE_PSEUDOS = [pseudo for pseudo in PSEUDOS if not pseudo.is_tree_pseudo_element()] %> /// The number of eager pseudo-elements. pub const EAGER_PSEUDO_COUNT: usize = ${len(EAGER_PSEUDOS)}; /// The number of non-functional pseudo-elements. pub const SIMPLE_PSEUDO_COUNT: usize = ${len(SIMPLE_PSEUDOS)}; /// The number of tree pseudo-elements. pub const TREE_PSEUDO_COUNT: usize = ${len(TREE_PSEUDOS)}; /// The number of all pseudo-elements. pub const PSEUDO_COUNT: usize = ${len(PSEUDOS)}; /// The list of eager pseudos. pub const EAGER_PSEUDOS: [PseudoElement; EAGER_PSEUDO_COUNT] = [ % for eager_pseudo_name in EAGER_PSEUDOS: PseudoElement::${eager_pseudo_name}, % endfor ]; <%def name="pseudo_element_variant(pseudo, tree_arg='..')">\ PseudoElement::${pseudo.capitalized_pseudo()}${"({})".format(tree_arg) if pseudo.is_tree_pseudo_element() else ""}\ </%def> impl PseudoElement { /// Returns an index of the pseudo-element. #[inline] pub fn index(&self) -> usize { match *self { % for i, pseudo in enumerate(PSEUDOS): ${pseudo_element_variant(pseudo)} => ${i}, % endfor PseudoElement::UnknownWebkit(..) => unreachable!(), } } /// Returns an array of `None` values. /// /// FIXME(emilio): Integer generics can't come soon enough. pub fn pseudo_none_array<T>() -> [Option<T>; PSEUDO_COUNT] { [ ${",\n ".join(["None" for pseudo in PSEUDOS])} ] } /// Whether this pseudo-element is an anonymous box. #[inline] pub fn is_anon_box(&self) -> bool { match *self { % for pseudo in PSEUDOS: % if pseudo.is_anon_box(): ${pseudo_element_variant(pseudo)} => true, % endif % endfor _ => false, } } /// Whether this pseudo-element is eagerly-cascaded. #[inline] pub fn is_eager(&self) -> bool { matches!(*self, ${" | ".join(map(lambda name: "PseudoElement::{}".format(name), EAGER_PSEUDOS))}) } /// Whether this pseudo-element is tree pseudo-element. #[inline] pub fn is_tree_pseudo_element(&self) -> bool { match *self { % for pseudo in TREE_PSEUDOS: ${pseudo_element_variant(pseudo)} => true, % endfor _ => false, } } /// Whether this pseudo-element is an unknown Webkit-prefixed pseudo-element. #[inline] pub fn is_unknown_webkit_pseudo_element(&self) -> bool { matches!(*self, PseudoElement::UnknownWebkit(..)) } /// Gets the flags associated to this pseudo-element, or 0 if it's an /// anonymous box. pub fn flags(&self) -> u32 { match *self { % for pseudo in PSEUDOS: ${pseudo_element_variant(pseudo)} => % if pseudo.is_tree_pseudo_element(): if static_prefs::pref!("layout.css.xul-tree-pseudos.content.enabled") { 0 } else { structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS_AND_CHROME }, % elif pseudo.is_anon_box(): structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS, % else: structs::SERVO_CSS_PSEUDO_ELEMENT_FLAGS_${pseudo.pseudo_ident}, % endif % endfor PseudoElement::UnknownWebkit(..) => 0, } } /// Construct a pseudo-element from a `PseudoStyleType`. #[inline] pub fn from_pseudo_type(type_: PseudoStyleType) -> Option<Self> { match type_ { % for pseudo in PSEUDOS: % if not pseudo.is_tree_pseudo_element(): PseudoStyleType::${pseudo.pseudo_ident} => { Some(${pseudo_element_variant(pseudo)}) }, % endif % endfor _ => None, } } /// Construct a `PseudoStyleType` from a pseudo-element #[inline] pub fn pseudo_type(&self) -> PseudoStyleType { match *self { % for pseudo in PSEUDOS: % if pseudo.is_tree_pseudo_element(): PseudoElement::${pseudo.capitalized_pseudo()}(..) => PseudoStyleType::XULTree, % else: PseudoElement::${pseudo.capitalized_pseudo()} => PseudoStyleType::${pseudo.pseudo_ident}, % endif % endfor PseudoElement::UnknownWebkit(..) => unreachable!(), } } /// Get the argument list of a tree pseudo-element. #[inline] pub fn tree_pseudo_args(&self) -> Option<<&[Atom]> { match *self { % for pseudo in TREE_PSEUDOS: PseudoElement::${pseudo.capitalized_pseudo()}(ref args) => Some(args), % endfor _ => None, } } /// Construct a tree pseudo-element from atom and args. #[inline] pub fn from_tree_pseudo_atom(atom: &Atom, args: Box<[Atom]>) -> Option<Self> { % for pseudo in PSEUDOS: % if pseudo.is_tree_pseudo_element(): if atom == &atom!("${pseudo.value}") { return Some(PseudoElement::${pseudo.capitalized_pseudo()}(args.into())); } % endif % endfor None } /// Constructs a pseudo-element from a string of text. /// /// Returns `None` if the pseudo-element is not recognised. #[inline] pub fn
(name: &str) -> Option<Self> { // We don't need to support tree pseudos because functional // pseudo-elements needs arguments, and thus should be created // via other methods. match_ignore_ascii_case! { name, % for pseudo in SIMPLE_PSEUDOS: "${pseudo.value[1:]}" => { return Some(${pseudo_element_variant(pseudo)}) } % endfor // Alias some legacy prefixed pseudos to their standardized name at parse time: "-moz-selection" => { return Some(PseudoElement::Selection); } "-moz-placeholder" => { return Some(PseudoElement::Placeholder); } "-moz-list-bullet" | "-moz-list-number" => { return Some(PseudoElement::Marker); } _ => { if starts_with_ignore_ascii_case(name, "-moz-tree-") { return PseudoElement::tree_pseudo_element(name, Box::new([])) } if static_prefs::pref!("layout.css.unknown-webkit-pseudo-element") { const WEBKIT_PREFIX: &str = "-webkit-"; if starts_with_ignore_ascii_case(name, WEBKIT_PREFIX) { let part = string_as_ascii_lowercase(&name[WEBKIT_PREFIX.len()..]); return Some(PseudoElement::UnknownWebkit(part.into())); } } } } None } /// Constructs a tree pseudo-element from the given name and arguments. /// "name" must start with "-moz-tree-". /// /// Returns `None` if the pseudo-element is not recognized. #[inline] pub fn tree_pseudo_element(name: &str, args: Box<[Atom]>) -> Option<Self> { debug_assert!(starts_with_ignore_ascii_case(name, "-moz-tree-")); let tree_part = &name[10..]; % for pseudo in TREE_PSEUDOS: if tree_part.eq_ignore_ascii_case("${pseudo.value[11:]}") { return Some(${pseudo_element_variant(pseudo, "args.into()")}); } % endfor None } } impl ToCss for PseudoElement { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_char(':')?; match *self { % for pseudo in PSEUDOS: ${pseudo_element_variant(pseudo)} => dest.write_str("${pseudo.value}")?, % endfor PseudoElement::UnknownWebkit(ref atom) => { dest.write_str(":-webkit-")?; serialize_atom_identifier(atom, dest)?; } } if let Some(args) = self.tree_pseudo_args() { if!args.is_empty() { dest.write_char('(')?; let mut iter = args.iter(); if let Some(first) = iter.next() { serialize_atom_identifier(&first, dest)?; for item in iter { dest.write_str(", ")?; serialize_atom_identifier(item, dest)?; } } dest.write_char(')')?; } } Ok(()) } }
from_slice
identifier_name
pseudo_element_definition.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ /// Gecko's pseudo-element definition. #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)] pub enum PseudoElement { % for pseudo in PSEUDOS: /// ${pseudo.value} % if pseudo.is_tree_pseudo_element(): ${pseudo.capitalized_pseudo()}(ThinBoxedSlice<Atom>), % else: ${pseudo.capitalized_pseudo()}, % endif % endfor /// ::-webkit-* that we don't recognize /// https://github.com/whatwg/compat/issues/103 UnknownWebkit(Atom), } /// Important: If you change this, you should also update Gecko's /// nsCSSPseudoElements::IsEagerlyCascadedInServo. <% EAGER_PSEUDOS = ["Before", "After", "FirstLine", "FirstLetter"] %> <% TREE_PSEUDOS = [pseudo for pseudo in PSEUDOS if pseudo.is_tree_pseudo_element()] %> <% SIMPLE_PSEUDOS = [pseudo for pseudo in PSEUDOS if not pseudo.is_tree_pseudo_element()] %> /// The number of eager pseudo-elements. pub const EAGER_PSEUDO_COUNT: usize = ${len(EAGER_PSEUDOS)}; /// The number of non-functional pseudo-elements. pub const SIMPLE_PSEUDO_COUNT: usize = ${len(SIMPLE_PSEUDOS)}; /// The number of tree pseudo-elements. pub const TREE_PSEUDO_COUNT: usize = ${len(TREE_PSEUDOS)}; /// The number of all pseudo-elements. pub const PSEUDO_COUNT: usize = ${len(PSEUDOS)}; /// The list of eager pseudos. pub const EAGER_PSEUDOS: [PseudoElement; EAGER_PSEUDO_COUNT] = [ % for eager_pseudo_name in EAGER_PSEUDOS: PseudoElement::${eager_pseudo_name}, % endfor ]; <%def name="pseudo_element_variant(pseudo, tree_arg='..')">\ PseudoElement::${pseudo.capitalized_pseudo()}${"({})".format(tree_arg) if pseudo.is_tree_pseudo_element() else ""}\ </%def> impl PseudoElement { /// Returns an index of the pseudo-element. #[inline] pub fn index(&self) -> usize { match *self { % for i, pseudo in enumerate(PSEUDOS): ${pseudo_element_variant(pseudo)} => ${i}, % endfor PseudoElement::UnknownWebkit(..) => unreachable!(), } } /// Returns an array of `None` values. /// /// FIXME(emilio): Integer generics can't come soon enough. pub fn pseudo_none_array<T>() -> [Option<T>; PSEUDO_COUNT] { [ ${",\n ".join(["None" for pseudo in PSEUDOS])} ] } /// Whether this pseudo-element is an anonymous box. #[inline] pub fn is_anon_box(&self) -> bool { match *self { % for pseudo in PSEUDOS: % if pseudo.is_anon_box(): ${pseudo_element_variant(pseudo)} => true, % endif % endfor _ => false, } } /// Whether this pseudo-element is eagerly-cascaded. #[inline] pub fn is_eager(&self) -> bool { matches!(*self, ${" | ".join(map(lambda name: "PseudoElement::{}".format(name), EAGER_PSEUDOS))}) } /// Whether this pseudo-element is tree pseudo-element. #[inline] pub fn is_tree_pseudo_element(&self) -> bool { match *self { % for pseudo in TREE_PSEUDOS: ${pseudo_element_variant(pseudo)} => true, % endfor _ => false, } } /// Whether this pseudo-element is an unknown Webkit-prefixed pseudo-element. #[inline] pub fn is_unknown_webkit_pseudo_element(&self) -> bool { matches!(*self, PseudoElement::UnknownWebkit(..)) } /// Gets the flags associated to this pseudo-element, or 0 if it's an /// anonymous box. pub fn flags(&self) -> u32 { match *self { % for pseudo in PSEUDOS: ${pseudo_element_variant(pseudo)} => % if pseudo.is_tree_pseudo_element(): if static_prefs::pref!("layout.css.xul-tree-pseudos.content.enabled") { 0 } else { structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS_AND_CHROME }, % elif pseudo.is_anon_box(): structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS, % else: structs::SERVO_CSS_PSEUDO_ELEMENT_FLAGS_${pseudo.pseudo_ident}, % endif % endfor PseudoElement::UnknownWebkit(..) => 0, } } /// Construct a pseudo-element from a `PseudoStyleType`. #[inline] pub fn from_pseudo_type(type_: PseudoStyleType) -> Option<Self> { match type_ { % for pseudo in PSEUDOS: % if not pseudo.is_tree_pseudo_element(): PseudoStyleType::${pseudo.pseudo_ident} => { Some(${pseudo_element_variant(pseudo)}) }, % endif % endfor _ => None, } } /// Construct a `PseudoStyleType` from a pseudo-element #[inline] pub fn pseudo_type(&self) -> PseudoStyleType { match *self { % for pseudo in PSEUDOS: % if pseudo.is_tree_pseudo_element(): PseudoElement::${pseudo.capitalized_pseudo()}(..) => PseudoStyleType::XULTree, % else: PseudoElement::${pseudo.capitalized_pseudo()} => PseudoStyleType::${pseudo.pseudo_ident}, % endif % endfor PseudoElement::UnknownWebkit(..) => unreachable!(), } } /// Get the argument list of a tree pseudo-element. #[inline] pub fn tree_pseudo_args(&self) -> Option<<&[Atom]> { match *self { % for pseudo in TREE_PSEUDOS: PseudoElement::${pseudo.capitalized_pseudo()}(ref args) => Some(args), % endfor _ => None, } } /// Construct a tree pseudo-element from atom and args. #[inline] pub fn from_tree_pseudo_atom(atom: &Atom, args: Box<[Atom]>) -> Option<Self> { % for pseudo in PSEUDOS: % if pseudo.is_tree_pseudo_element(): if atom == &atom!("${pseudo.value}") { return Some(PseudoElement::${pseudo.capitalized_pseudo()}(args.into())); } % endif % endfor None } /// Constructs a pseudo-element from a string of text. /// /// Returns `None` if the pseudo-element is not recognised. #[inline] pub fn from_slice(name: &str) -> Option<Self>
_ => { if starts_with_ignore_ascii_case(name, "-moz-tree-") { return PseudoElement::tree_pseudo_element(name, Box::new([])) } if static_prefs::pref!("layout.css.unknown-webkit-pseudo-element") { const WEBKIT_PREFIX: &str = "-webkit-"; if starts_with_ignore_ascii_case(name, WEBKIT_PREFIX) { let part = string_as_ascii_lowercase(&name[WEBKIT_PREFIX.len()..]); return Some(PseudoElement::UnknownWebkit(part.into())); } } } } None } /// Constructs a tree pseudo-element from the given name and arguments. /// "name" must start with "-moz-tree-". /// /// Returns `None` if the pseudo-element is not recognized. #[inline] pub fn tree_pseudo_element(name: &str, args: Box<[Atom]>) -> Option<Self> { debug_assert!(starts_with_ignore_ascii_case(name, "-moz-tree-")); let tree_part = &name[10..]; % for pseudo in TREE_PSEUDOS: if tree_part.eq_ignore_ascii_case("${pseudo.value[11:]}") { return Some(${pseudo_element_variant(pseudo, "args.into()")}); } % endfor None } } impl ToCss for PseudoElement { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_char(':')?; match *self { % for pseudo in PSEUDOS: ${pseudo_element_variant(pseudo)} => dest.write_str("${pseudo.value}")?, % endfor PseudoElement::UnknownWebkit(ref atom) => { dest.write_str(":-webkit-")?; serialize_atom_identifier(atom, dest)?; } } if let Some(args) = self.tree_pseudo_args() { if!args.is_empty() { dest.write_char('(')?; let mut iter = args.iter(); if let Some(first) = iter.next() { serialize_atom_identifier(&first, dest)?; for item in iter { dest.write_str(", ")?; serialize_atom_identifier(item, dest)?; } } dest.write_char(')')?; } } Ok(()) } }
{ // We don't need to support tree pseudos because functional // pseudo-elements needs arguments, and thus should be created // via other methods. match_ignore_ascii_case! { name, % for pseudo in SIMPLE_PSEUDOS: "${pseudo.value[1:]}" => { return Some(${pseudo_element_variant(pseudo)}) } % endfor // Alias some legacy prefixed pseudos to their standardized name at parse time: "-moz-selection" => { return Some(PseudoElement::Selection); } "-moz-placeholder" => { return Some(PseudoElement::Placeholder); } "-moz-list-bullet" | "-moz-list-number" => { return Some(PseudoElement::Marker); }
identifier_body
pseudo_element_definition.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ /// Gecko's pseudo-element definition. #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)] pub enum PseudoElement { % for pseudo in PSEUDOS: /// ${pseudo.value} % if pseudo.is_tree_pseudo_element(): ${pseudo.capitalized_pseudo()}(ThinBoxedSlice<Atom>), % else: ${pseudo.capitalized_pseudo()}, % endif % endfor /// ::-webkit-* that we don't recognize /// https://github.com/whatwg/compat/issues/103 UnknownWebkit(Atom), } /// Important: If you change this, you should also update Gecko's /// nsCSSPseudoElements::IsEagerlyCascadedInServo. <% EAGER_PSEUDOS = ["Before", "After", "FirstLine", "FirstLetter"] %> <% TREE_PSEUDOS = [pseudo for pseudo in PSEUDOS if pseudo.is_tree_pseudo_element()] %> <% SIMPLE_PSEUDOS = [pseudo for pseudo in PSEUDOS if not pseudo.is_tree_pseudo_element()] %> /// The number of eager pseudo-elements. pub const EAGER_PSEUDO_COUNT: usize = ${len(EAGER_PSEUDOS)}; /// The number of non-functional pseudo-elements. pub const SIMPLE_PSEUDO_COUNT: usize = ${len(SIMPLE_PSEUDOS)}; /// The number of tree pseudo-elements. pub const TREE_PSEUDO_COUNT: usize = ${len(TREE_PSEUDOS)}; /// The number of all pseudo-elements. pub const PSEUDO_COUNT: usize = ${len(PSEUDOS)}; /// The list of eager pseudos. pub const EAGER_PSEUDOS: [PseudoElement; EAGER_PSEUDO_COUNT] = [ % for eager_pseudo_name in EAGER_PSEUDOS: PseudoElement::${eager_pseudo_name}, % endfor ]; <%def name="pseudo_element_variant(pseudo, tree_arg='..')">\ PseudoElement::${pseudo.capitalized_pseudo()}${"({})".format(tree_arg) if pseudo.is_tree_pseudo_element() else ""}\ </%def> impl PseudoElement { /// Returns an index of the pseudo-element. #[inline] pub fn index(&self) -> usize { match *self { % for i, pseudo in enumerate(PSEUDOS): ${pseudo_element_variant(pseudo)} => ${i}, % endfor PseudoElement::UnknownWebkit(..) => unreachable!(), } } /// Returns an array of `None` values. /// /// FIXME(emilio): Integer generics can't come soon enough. pub fn pseudo_none_array<T>() -> [Option<T>; PSEUDO_COUNT] { [ ${",\n ".join(["None" for pseudo in PSEUDOS])} ] } /// Whether this pseudo-element is an anonymous box. #[inline] pub fn is_anon_box(&self) -> bool { match *self { % for pseudo in PSEUDOS: % if pseudo.is_anon_box(): ${pseudo_element_variant(pseudo)} => true, % endif % endfor _ => false, } } /// Whether this pseudo-element is eagerly-cascaded. #[inline] pub fn is_eager(&self) -> bool { matches!(*self, ${" | ".join(map(lambda name: "PseudoElement::{}".format(name), EAGER_PSEUDOS))}) } /// Whether this pseudo-element is tree pseudo-element. #[inline] pub fn is_tree_pseudo_element(&self) -> bool { match *self { % for pseudo in TREE_PSEUDOS: ${pseudo_element_variant(pseudo)} => true, % endfor _ => false, } } /// Whether this pseudo-element is an unknown Webkit-prefixed pseudo-element. #[inline] pub fn is_unknown_webkit_pseudo_element(&self) -> bool { matches!(*self, PseudoElement::UnknownWebkit(..)) } /// Gets the flags associated to this pseudo-element, or 0 if it's an /// anonymous box. pub fn flags(&self) -> u32 { match *self { % for pseudo in PSEUDOS: ${pseudo_element_variant(pseudo)} => % if pseudo.is_tree_pseudo_element(): if static_prefs::pref!("layout.css.xul-tree-pseudos.content.enabled") { 0 } else { structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS_AND_CHROME }, % elif pseudo.is_anon_box(): structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS, % else: structs::SERVO_CSS_PSEUDO_ELEMENT_FLAGS_${pseudo.pseudo_ident}, % endif % endfor PseudoElement::UnknownWebkit(..) => 0, } } /// Construct a pseudo-element from a `PseudoStyleType`. #[inline] pub fn from_pseudo_type(type_: PseudoStyleType) -> Option<Self> { match type_ { % for pseudo in PSEUDOS: % if not pseudo.is_tree_pseudo_element(): PseudoStyleType::$
=> { Some(${pseudo_element_variant(pseudo)}) }, % endif % endfor _ => None, } } /// Construct a `PseudoStyleType` from a pseudo-element #[inline] pub fn pseudo_type(&self) -> PseudoStyleType { match *self { % for pseudo in PSEUDOS: % if pseudo.is_tree_pseudo_element(): PseudoElement::${pseudo.capitalized_pseudo()}(..) => PseudoStyleType::XULTree, % else: PseudoElement::${pseudo.capitalized_pseudo()} => PseudoStyleType::${pseudo.pseudo_ident}, % endif % endfor PseudoElement::UnknownWebkit(..) => unreachable!(), } } /// Get the argument list of a tree pseudo-element. #[inline] pub fn tree_pseudo_args(&self) -> Option<<&[Atom]> { match *self { % for pseudo in TREE_PSEUDOS: PseudoElement::${pseudo.capitalized_pseudo()}(ref args) => Some(args), % endfor _ => None, } } /// Construct a tree pseudo-element from atom and args. #[inline] pub fn from_tree_pseudo_atom(atom: &Atom, args: Box<[Atom]>) -> Option<Self> { % for pseudo in PSEUDOS: % if pseudo.is_tree_pseudo_element(): if atom == &atom!("${pseudo.value}") { return Some(PseudoElement::${pseudo.capitalized_pseudo()}(args.into())); } % endif % endfor None } /// Constructs a pseudo-element from a string of text. /// /// Returns `None` if the pseudo-element is not recognised. #[inline] pub fn from_slice(name: &str) -> Option<Self> { // We don't need to support tree pseudos because functional // pseudo-elements needs arguments, and thus should be created // via other methods. match_ignore_ascii_case! { name, % for pseudo in SIMPLE_PSEUDOS: "${pseudo.value[1:]}" => { return Some(${pseudo_element_variant(pseudo)}) } % endfor // Alias some legacy prefixed pseudos to their standardized name at parse time: "-moz-selection" => { return Some(PseudoElement::Selection); } "-moz-placeholder" => { return Some(PseudoElement::Placeholder); } "-moz-list-bullet" | "-moz-list-number" => { return Some(PseudoElement::Marker); } _ => { if starts_with_ignore_ascii_case(name, "-moz-tree-") { return PseudoElement::tree_pseudo_element(name, Box::new([])) } if static_prefs::pref!("layout.css.unknown-webkit-pseudo-element") { const WEBKIT_PREFIX: &str = "-webkit-"; if starts_with_ignore_ascii_case(name, WEBKIT_PREFIX) { let part = string_as_ascii_lowercase(&name[WEBKIT_PREFIX.len()..]); return Some(PseudoElement::UnknownWebkit(part.into())); } } } } None } /// Constructs a tree pseudo-element from the given name and arguments. /// "name" must start with "-moz-tree-". /// /// Returns `None` if the pseudo-element is not recognized. #[inline] pub fn tree_pseudo_element(name: &str, args: Box<[Atom]>) -> Option<Self> { debug_assert!(starts_with_ignore_ascii_case(name, "-moz-tree-")); let tree_part = &name[10..]; % for pseudo in TREE_PSEUDOS: if tree_part.eq_ignore_ascii_case("${pseudo.value[11:]}") { return Some(${pseudo_element_variant(pseudo, "args.into()")}); } % endfor None } } impl ToCss for PseudoElement { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_char(':')?; match *self { % for pseudo in PSEUDOS: ${pseudo_element_variant(pseudo)} => dest.write_str("${pseudo.value}")?, % endfor PseudoElement::UnknownWebkit(ref atom) => { dest.write_str(":-webkit-")?; serialize_atom_identifier(atom, dest)?; } } if let Some(args) = self.tree_pseudo_args() { if!args.is_empty() { dest.write_char('(')?; let mut iter = args.iter(); if let Some(first) = iter.next() { serialize_atom_identifier(&first, dest)?; for item in iter { dest.write_str(", ")?; serialize_atom_identifier(item, dest)?; } } dest.write_char(')')?; } } Ok(()) } }
{pseudo.pseudo_ident}
conditional_block
empty-struct-braces-pat-2.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. // Can't use empty braced struct as enum pattern // aux-build:empty-struct.rs extern crate empty_struct; use empty_struct::*; struct
{} fn main() { let e1 = Empty1 {}; let xe1 = XEmpty1 {}; match e1 { Empty1() => () //~ ERROR expected tuple struct/variant, found struct `Empty1` } match xe1 { XEmpty1() => () //~ ERROR expected tuple struct/variant, found struct `XEmpty1` } match e1 { Empty1(..) => () //~ ERROR expected tuple struct/variant, found struct `Empty1` } match xe1 { XEmpty1(..) => () //~ ERROR expected tuple struct/variant, found struct `XEmpty1` } }
Empty1
identifier_name
empty-struct-braces-pat-2.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. // Can't use empty braced struct as enum pattern // aux-build:empty-struct.rs extern crate empty_struct; use empty_struct::*; struct Empty1 {} fn main() { let e1 = Empty1 {}; let xe1 = XEmpty1 {}; match e1 { Empty1() => () //~ ERROR expected tuple struct/variant, found struct `Empty1` } match xe1 { XEmpty1() => () //~ ERROR expected tuple struct/variant, found struct `XEmpty1` } match e1 { Empty1(..) => () //~ ERROR expected tuple struct/variant, found struct `Empty1` } match xe1 { XEmpty1(..) => () //~ ERROR expected tuple struct/variant, found struct `XEmpty1` }
}
random_line_split
empty-struct-braces-pat-2.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. // Can't use empty braced struct as enum pattern // aux-build:empty-struct.rs extern crate empty_struct; use empty_struct::*; struct Empty1 {} fn main()
{ let e1 = Empty1 {}; let xe1 = XEmpty1 {}; match e1 { Empty1() => () //~ ERROR expected tuple struct/variant, found struct `Empty1` } match xe1 { XEmpty1() => () //~ ERROR expected tuple struct/variant, found struct `XEmpty1` } match e1 { Empty1(..) => () //~ ERROR expected tuple struct/variant, found struct `Empty1` } match xe1 { XEmpty1(..) => () //~ ERROR expected tuple struct/variant, found struct `XEmpty1` } }
identifier_body
length_expr.rs
// Copyright (c) 2015 Robert Clipsham <[email protected]>
// option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern: Only field names, constants, integers, basic arithmetic expressions (+ - * / %) and parentheses are allowed in the "length" attribute #![feature(custom_attribute, plugin)] #![plugin(pnet_macros_plugin)] extern crate pnet; #[packet] pub struct PacketWithPayload { banana: u8, #[length = "banana + 7.5"] var_length: Vec<u8>, #[payload] payload: Vec<u8> } fn main() {}
// // 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
random_line_split
length_expr.rs
// Copyright (c) 2015 Robert Clipsham <[email protected]> // // 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. // error-pattern: Only field names, constants, integers, basic arithmetic expressions (+ - * / %) and parentheses are allowed in the "length" attribute #![feature(custom_attribute, plugin)] #![plugin(pnet_macros_plugin)] extern crate pnet; #[packet] pub struct PacketWithPayload { banana: u8, #[length = "banana + 7.5"] var_length: Vec<u8>, #[payload] payload: Vec<u8> } fn
() {}
main
identifier_name
ref.rs
#[derive(Clone, Copy)] struct Point { x: i32, y: i32 } fn
() { let c = 'Q'; // A `ref` borrow on the left side of an assignment is equivalent to // an `&` borrow on the right side. let ref ref_c1 = c; let ref_c2 = &c; println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2); let point = Point { x: 0, y: 0 }; // `ref` is also valid when destructuring a struct. let _copy_of_x = { // `ref_to_x` is a reference to the `x` field of `point`. let Point { x: ref ref_to_x, y: _ } = point; // Return a copy of the `x` field of `point`. *ref_to_x }; // A mutable copy of `point` let mut mutable_point = point; { // `ref` can be paired with `mut` to take mutable references. let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point; // Mutate the `y` field of `mutable_point` via a mutable reference. *mut_ref_to_y = 1; } println!("point is ({}, {})", point.x, point.y); println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y); // A mutable tuple that includes a pointer let mut mutable_tuple = (Box::new(5u32), 3u32); { // Destructure `mutable_ tuple` to change the value of `last`. let (_, ref mut last) = mutable_tuple; *last = 2u32; } println!("tuple is {:?}", mutable_tuple); }
main
identifier_name
ref.rs
#[derive(Clone, Copy)] struct Point { x: i32, y: i32 } fn main()
// A mutable copy of `point` let mut mutable_point = point; { // `ref` can be paired with `mut` to take mutable references. let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point; // Mutate the `y` field of `mutable_point` via a mutable reference. *mut_ref_to_y = 1; } println!("point is ({}, {})", point.x, point.y); println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y); // A mutable tuple that includes a pointer let mut mutable_tuple = (Box::new(5u32), 3u32); { // Destructure `mutable_ tuple` to change the value of `last`. let (_, ref mut last) = mutable_tuple; *last = 2u32; } println!("tuple is {:?}", mutable_tuple); }
{ let c = 'Q'; // A `ref` borrow on the left side of an assignment is equivalent to // an `&` borrow on the right side. let ref ref_c1 = c; let ref_c2 = &c; println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2); let point = Point { x: 0, y: 0 }; // `ref` is also valid when destructuring a struct. let _copy_of_x = { // `ref_to_x` is a reference to the `x` field of `point`. let Point { x: ref ref_to_x, y: _ } = point; // Return a copy of the `x` field of `point`. *ref_to_x };
identifier_body
ref.rs
#[derive(Clone, Copy)] struct Point { x: i32, y: i32 } fn main() { let c = 'Q'; // A `ref` borrow on the left side of an assignment is equivalent to // an `&` borrow on the right side. let ref ref_c1 = c; let ref_c2 = &c; println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2); let point = Point { x: 0, y: 0 }; // `ref` is also valid when destructuring a struct. let _copy_of_x = { // `ref_to_x` is a reference to the `x` field of `point`. let Point { x: ref ref_to_x, y: _ } = point; // Return a copy of the `x` field of `point`. *ref_to_x }; // A mutable copy of `point` let mut mutable_point = point; { // `ref` can be paired with `mut` to take mutable references. let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point; // Mutate the `y` field of `mutable_point` via a mutable reference. *mut_ref_to_y = 1; } println!("point is ({}, {})", point.x, point.y); println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y); // A mutable tuple that includes a pointer let mut mutable_tuple = (Box::new(5u32), 3u32); { // Destructure `mutable_ tuple` to change the value of `last`. let (_, ref mut last) = mutable_tuple; *last = 2u32; }
println!("tuple is {:?}", mutable_tuple); }
random_line_split
order_12.rs
mod lib { pub struct SessionToken(String); pub struct InvalidOrder(String); pub enum ApiError { ParsingError(String), IoError(String), } pub struct Order { amount: u8, name: String, } pub fn create_order(amount: u8, name: String) -> Result<Order, InvalidOrder> { if amount <= 0
unimplemented!() } pub fn authorize(auth_token: String) -> Result<SessionToken, ApiError> { unimplemented!() } pub fn send_order(session_token: &SessionToken, order: Order) { unimplemented!() } } pub use lib::*; fn main() { if let Ok(session_token) = authorize("My initial token".into()) { let first_order = create_order(10, "Bananas".into()); if let Ok(order) = first_order { send_order(&session_token, order); } } }
{ unimplemented!() }
conditional_block
order_12.rs
mod lib { pub struct SessionToken(String); pub struct InvalidOrder(String); pub enum ApiError { ParsingError(String), IoError(String), } pub struct Order { amount: u8, name: String, } pub fn create_order(amount: u8, name: String) -> Result<Order, InvalidOrder> { if amount <= 0 { unimplemented!() } unimplemented!() } pub fn authorize(auth_token: String) -> Result<SessionToken, ApiError> { unimplemented!() }
pub fn send_order(session_token: &SessionToken, order: Order) { unimplemented!() } } pub use lib::*; fn main() { if let Ok(session_token) = authorize("My initial token".into()) { let first_order = create_order(10, "Bananas".into()); if let Ok(order) = first_order { send_order(&session_token, order); } } }
random_line_split
order_12.rs
mod lib { pub struct SessionToken(String); pub struct InvalidOrder(String); pub enum ApiError { ParsingError(String), IoError(String), } pub struct Order { amount: u8, name: String, } pub fn create_order(amount: u8, name: String) -> Result<Order, InvalidOrder>
pub fn authorize(auth_token: String) -> Result<SessionToken, ApiError> { unimplemented!() } pub fn send_order(session_token: &SessionToken, order: Order) { unimplemented!() } } pub use lib::*; fn main() { if let Ok(session_token) = authorize("My initial token".into()) { let first_order = create_order(10, "Bananas".into()); if let Ok(order) = first_order { send_order(&session_token, order); } } }
{ if amount <= 0 { unimplemented!() } unimplemented!() }
identifier_body
order_12.rs
mod lib { pub struct SessionToken(String); pub struct
(String); pub enum ApiError { ParsingError(String), IoError(String), } pub struct Order { amount: u8, name: String, } pub fn create_order(amount: u8, name: String) -> Result<Order, InvalidOrder> { if amount <= 0 { unimplemented!() } unimplemented!() } pub fn authorize(auth_token: String) -> Result<SessionToken, ApiError> { unimplemented!() } pub fn send_order(session_token: &SessionToken, order: Order) { unimplemented!() } } pub use lib::*; fn main() { if let Ok(session_token) = authorize("My initial token".into()) { let first_order = create_order(10, "Bananas".into()); if let Ok(order) = first_order { send_order(&session_token, order); } } }
InvalidOrder
identifier_name
char.rs
// Copyright 2012-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. //! Character manipulation (`char` type, Unicode Scalar Value) //! //! This module provides the `CharExt` trait, as well as its //! implementation for the primitive `char` type, in order to allow //! basic character manipulation. //! //! A `char` actually represents a //! *[Unicode Scalar //! Value](http://www.unicode.org/glossary/#unicode_scalar_value)*, as it can //! contain any Unicode code point except high-surrogate and low-surrogate code //! points. //! //! As such, only values in the ranges \[0x0,0xD7FF\] and \[0xE000,0x10FFFF\] //! (inclusive) are allowed. A `char` can always be safely cast to a `u32`; //! however the converse is not always true due to the above range limits //! and, as such, should be performed via the `from_u32` function. #![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "char")] use core::char::CharExt as C; use core::option::Option::{self, Some}; use core::iter::Iterator; use tables::{derived_property, property, general_category, conversions, charwidth}; // stable reexports pub use core::char::{MAX, from_u32, from_digit, EscapeUnicode, EscapeDefault}; // unstable reexports #[allow(deprecated)] pub use normalize::{decompose_canonical, decompose_compatible, compose}; #[allow(deprecated)] pub use tables::normalization::canonical_combining_class; pub use tables::UNICODE_VERSION; /// An iterator over the lowercase mapping of a given character, returned from /// the [`to_lowercase` method](../primitive.char.html#method.to_lowercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToLowercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToLowercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } /// An iterator over the uppercase mapping of a given character, returned from /// the [`to_uppercase` method](../primitive.char.html#method.to_uppercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToUppercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToUppercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } #[stable(feature = "rust1", since = "1.0.0")] #[lang = "char"] impl char { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert!(c.is_digit(10)); /// /// assert!('f'.is_digit(16)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_digit(self, radix: u32) -> bool { C::is_digit(self, radix) } /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert_eq!(c.to_digit(10), Some(1)); /// /// assert_eq!('f'.to_digit(16), Some(15)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn to_digit(self, radix: u32) -> Option<u32> { C::to_digit(self, radix) } /// Returns an iterator that yields the hexadecimal Unicode escape of a /// character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. /// /// # Examples /// /// ``` /// for i in '❀'.escape_unicode() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// u /// { /// 2 /// 7 /// 6 /// 4 /// } /// ``` /// /// Collecting into a `String`: /// /// ``` /// let heart: String = '❀'.escape_unicode().collect(); /// /// assert_eq!(heart, r"\u{2764}"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_unicode(self) -> EscapeUnicode { C::escape_unicode(self) } /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. /// /// # Examples /// /// ``` /// for i in '"'.escape_default() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// " /// ``` /// /// Collecting into a `String`: /// /// ``` /// let quote: String = '"'.escape_default().collect(); /// /// assert_eq!(quote, "\\\""); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_default(self) -> EscapeDefault { C::escape_default(self) } /// Returns the number of bytes this character would need if encoded in /// UTF-8. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf8(); /// /// assert_eq!(n, 2); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf8(self) -> usize { C::len_utf8(self) } /// Returns the number of 16-bit code units this character would need if /// encoded in UTF-16. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf16(); /// /// assert_eq!(n, 1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf16(self) -> usize { C::len_utf16(self) } /// Encodes this character as UTF-8 into the provided byte buffer, and then /// returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length four is large enough to /// encode any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes two bytes to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 2]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, Some(2)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { C::encode_utf8(self, dst) } /// Encodes this character as UTF-16 into the provided `u16` buffer, and /// then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length 2 is large enough to encode /// any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes one `u16` to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf16(&mut b); /// /// assert_eq!(result, Some(1)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 0]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { C::encode_utf16(self, dst) } /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphabetic(self) -> bool { match self { 'a'... 'z' | 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_lowercase(self) -> bool { match self { 'a'... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_uppercase(self) -> bool { match self { 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_whitespace(self) -> bool { match self { '' | '\x09'... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_control(self) -> bool { general_category::Cc(self) } /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_numeric(self) -> bool { match self { '0'... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// lowercase equivalent of the character. If no conversion is possible then /// the input character is returned. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_lowercase(self) -> ToLowercase { ToLowercase(Some(conversions::to_lower(self))) } /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint to its uppercase equivalent according to the /// Unicode database [1]. The additional [`SpecialCasing.txt`] is not yet /// considered here, but the iterator returned will soon support this form /// of case folding. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// uppercase equivalent of the character. If no conversion is possible then /// the input character is returned. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_uppercase(self) -> ToUppercase { ToUppercase(Some(conversions::to_upper(self))) } /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[deprecated(reason = "use the crates.io `unicode-width` library instead", since = "1.0.0")] #[unstable(feature = "unicode", reason = "needs expert opinion. is_cjk flag stands out as ugly")] pub fn width(self, is_cjk: bool) -> Option<usize> { charwidth::width(self, is_cjk) } }
random_line_split
char.rs
// Copyright 2012-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. //! Character manipulation (`char` type, Unicode Scalar Value) //! //! This module provides the `CharExt` trait, as well as its //! implementation for the primitive `char` type, in order to allow //! basic character manipulation. //! //! A `char` actually represents a //! *[Unicode Scalar //! Value](http://www.unicode.org/glossary/#unicode_scalar_value)*, as it can //! contain any Unicode code point except high-surrogate and low-surrogate code //! points. //! //! As such, only values in the ranges \[0x0,0xD7FF\] and \[0xE000,0x10FFFF\] //! (inclusive) are allowed. A `char` can always be safely cast to a `u32`; //! however the converse is not always true due to the above range limits //! and, as such, should be performed via the `from_u32` function. #![stable(feature = "rust1", since = "1.0.0")] #![doc(primitive = "char")] use core::char::CharExt as C; use core::option::Option::{self, Some}; use core::iter::Iterator; use tables::{derived_property, property, general_category, conversions, charwidth}; // stable reexports pub use core::char::{MAX, from_u32, from_digit, EscapeUnicode, EscapeDefault}; // unstable reexports #[allow(deprecated)] pub use normalize::{decompose_canonical, decompose_compatible, compose}; #[allow(deprecated)] pub use tables::normalization::canonical_combining_class; pub use tables::UNICODE_VERSION; /// An iterator over the lowercase mapping of a given character, returned from /// the [`to_lowercase` method](../primitive.char.html#method.to_lowercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToLowercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToLowercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } /// An iterator over the uppercase mapping of a given character, returned from /// the [`to_uppercase` method](../primitive.char.html#method.to_uppercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToUppercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToUppercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } #[stable(feature = "rust1", since = "1.0.0")] #[lang = "char"] impl char { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert!(c.is_digit(10)); /// /// assert!('f'.is_digit(16)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_digit(self, radix: u32) -> bool { C::is_digit(self, radix) } /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert_eq!(c.to_digit(10), Some(1)); /// /// assert_eq!('f'.to_digit(16), Some(15)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn
(self, radix: u32) -> Option<u32> { C::to_digit(self, radix) } /// Returns an iterator that yields the hexadecimal Unicode escape of a /// character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. /// /// # Examples /// /// ``` /// for i in '❀'.escape_unicode() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// u /// { /// 2 /// 7 /// 6 /// 4 /// } /// ``` /// /// Collecting into a `String`: /// /// ``` /// let heart: String = '❀'.escape_unicode().collect(); /// /// assert_eq!(heart, r"\u{2764}"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_unicode(self) -> EscapeUnicode { C::escape_unicode(self) } /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. /// /// # Examples /// /// ``` /// for i in '"'.escape_default() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// " /// ``` /// /// Collecting into a `String`: /// /// ``` /// let quote: String = '"'.escape_default().collect(); /// /// assert_eq!(quote, "\\\""); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_default(self) -> EscapeDefault { C::escape_default(self) } /// Returns the number of bytes this character would need if encoded in /// UTF-8. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf8(); /// /// assert_eq!(n, 2); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf8(self) -> usize { C::len_utf8(self) } /// Returns the number of 16-bit code units this character would need if /// encoded in UTF-16. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf16(); /// /// assert_eq!(n, 1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf16(self) -> usize { C::len_utf16(self) } /// Encodes this character as UTF-8 into the provided byte buffer, and then /// returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length four is large enough to /// encode any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes two bytes to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 2]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, Some(2)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { C::encode_utf8(self, dst) } /// Encodes this character as UTF-16 into the provided `u16` buffer, and /// then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length 2 is large enough to encode /// any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes one `u16` to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf16(&mut b); /// /// assert_eq!(result, Some(1)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 0]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { C::encode_utf16(self, dst) } /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphabetic(self) -> bool { match self { 'a'... 'z' | 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_lowercase(self) -> bool { match self { 'a'... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_uppercase(self) -> bool { match self { 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_whitespace(self) -> bool { match self { '' | '\x09'... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_control(self) -> bool { general_category::Cc(self) } /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_numeric(self) -> bool { match self { '0'... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// lowercase equivalent of the character. If no conversion is possible then /// the input character is returned. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_lowercase(self) -> ToLowercase { ToLowercase(Some(conversions::to_lower(self))) } /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint to its uppercase equivalent according to the /// Unicode database [1]. The additional [`SpecialCasing.txt`] is not yet /// considered here, but the iterator returned will soon support this form /// of case folding. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// uppercase equivalent of the character. If no conversion is possible then /// the input character is returned. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_uppercase(self) -> ToUppercase { ToUppercase(Some(conversions::to_upper(self))) } /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[deprecated(reason = "use the crates.io `unicode-width` library instead", since = "1.0.0")] #[unstable(feature = "unicode", reason = "needs expert opinion. is_cjk flag stands out as ugly")] pub fn width(self, is_cjk: bool) -> Option<usize> { charwidth::width(self, is_cjk) } }
to_digit
identifier_name
char.rs
// Copyright 2012-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. //! Character manipulation (`char` type, Unicode Scalar Value) //! //! This module provides the `CharExt` trait, as well as its //! implementation for the primitive `char` type, in order to allow //! basic character manipulation. //! //! A `char` actually represents a //! *[Unicode Scalar //! Value](http://www.unicode.org/glossary/#unicode_scalar_value)*, as it can //! contain any Unicode code point except high-surrogate and low-surrogate code //! points. //! //! As such, only values in the ranges \[0x0,0xD7FF\] and \[0xE000,0x10FFFF\] //! (inclusive) are allowed. A `char` can always be safely cast to a `u32`; //! however the converse is not always true due to the above range limits //! and, as such, should be performed via the `from_u32` function. #![stable(feature = "rust1", since = "1.0.0")] #![doc(primitive = "char")] use core::char::CharExt as C; use core::option::Option::{self, Some}; use core::iter::Iterator; use tables::{derived_property, property, general_category, conversions, charwidth}; // stable reexports pub use core::char::{MAX, from_u32, from_digit, EscapeUnicode, EscapeDefault}; // unstable reexports #[allow(deprecated)] pub use normalize::{decompose_canonical, decompose_compatible, compose}; #[allow(deprecated)] pub use tables::normalization::canonical_combining_class; pub use tables::UNICODE_VERSION; /// An iterator over the lowercase mapping of a given character, returned from /// the [`to_lowercase` method](../primitive.char.html#method.to_lowercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToLowercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToLowercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } /// An iterator over the uppercase mapping of a given character, returned from /// the [`to_uppercase` method](../primitive.char.html#method.to_uppercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToUppercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToUppercase { type Item = char; fn next(&mut self) -> Option<char>
} #[stable(feature = "rust1", since = "1.0.0")] #[lang = "char"] impl char { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert!(c.is_digit(10)); /// /// assert!('f'.is_digit(16)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_digit(self, radix: u32) -> bool { C::is_digit(self, radix) } /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert_eq!(c.to_digit(10), Some(1)); /// /// assert_eq!('f'.to_digit(16), Some(15)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn to_digit(self, radix: u32) -> Option<u32> { C::to_digit(self, radix) } /// Returns an iterator that yields the hexadecimal Unicode escape of a /// character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. /// /// # Examples /// /// ``` /// for i in '❀'.escape_unicode() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// u /// { /// 2 /// 7 /// 6 /// 4 /// } /// ``` /// /// Collecting into a `String`: /// /// ``` /// let heart: String = '❀'.escape_unicode().collect(); /// /// assert_eq!(heart, r"\u{2764}"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_unicode(self) -> EscapeUnicode { C::escape_unicode(self) } /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. /// /// # Examples /// /// ``` /// for i in '"'.escape_default() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// " /// ``` /// /// Collecting into a `String`: /// /// ``` /// let quote: String = '"'.escape_default().collect(); /// /// assert_eq!(quote, "\\\""); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_default(self) -> EscapeDefault { C::escape_default(self) } /// Returns the number of bytes this character would need if encoded in /// UTF-8. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf8(); /// /// assert_eq!(n, 2); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf8(self) -> usize { C::len_utf8(self) } /// Returns the number of 16-bit code units this character would need if /// encoded in UTF-16. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf16(); /// /// assert_eq!(n, 1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf16(self) -> usize { C::len_utf16(self) } /// Encodes this character as UTF-8 into the provided byte buffer, and then /// returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length four is large enough to /// encode any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes two bytes to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 2]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, Some(2)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { C::encode_utf8(self, dst) } /// Encodes this character as UTF-16 into the provided `u16` buffer, and /// then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length 2 is large enough to encode /// any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes one `u16` to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf16(&mut b); /// /// assert_eq!(result, Some(1)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 0]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { C::encode_utf16(self, dst) } /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphabetic(self) -> bool { match self { 'a'... 'z' | 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_lowercase(self) -> bool { match self { 'a'... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_uppercase(self) -> bool { match self { 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_whitespace(self) -> bool { match self { '' | '\x09'... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_control(self) -> bool { general_category::Cc(self) } /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_numeric(self) -> bool { match self { '0'... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// lowercase equivalent of the character. If no conversion is possible then /// the input character is returned. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_lowercase(self) -> ToLowercase { ToLowercase(Some(conversions::to_lower(self))) } /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint to its uppercase equivalent according to the /// Unicode database [1]. The additional [`SpecialCasing.txt`] is not yet /// considered here, but the iterator returned will soon support this form /// of case folding. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// uppercase equivalent of the character. If no conversion is possible then /// the input character is returned. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_uppercase(self) -> ToUppercase { ToUppercase(Some(conversions::to_upper(self))) } /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[deprecated(reason = "use the crates.io `unicode-width` library instead", since = "1.0.0")] #[unstable(feature = "unicode", reason = "needs expert opinion. is_cjk flag stands out as ugly")] pub fn width(self, is_cjk: bool) -> Option<usize> { charwidth::width(self, is_cjk) } }
{ self.0.take() }
identifier_body
lib.rs
extern crate k2hash; extern crate k2hash_sys; use k2hash::K2Hash; fn build_wrapped_k2hash() -> Result<K2Hash, std::io::Error>
#[test] fn test_new() { let result = build_wrapped_k2hash(); result.unwrap(); assert!(true); } #[test] fn test_set_str() { let k2hash = build_wrapped_k2hash().unwrap(); let key = "test_set_str"; let val = "val"; let result = k2hash.set_str(key.to_string(), val.to_string()); result.unwrap(); assert!(true); } #[test] fn test_get_str() { let k2hash = build_wrapped_k2hash().unwrap(); let key = "test_get_str"; let val = "val"; k2hash.set_str(key.to_string(), val.to_string()).unwrap(); let actual = k2hash.get_str(key.to_string()).unwrap(); assert_eq!(actual, val); }
{ let path = std::path::Path::new("/tmp/tmp.k2hash"); K2Hash::new(path, false, true, true, k2hash::DEFAULT_MASK_BITCOUNT, k2hash::DEFAULT_COLLISION_MASK_BITCOUNT, k2hash::DEFAULT_MAX_ELEMENT_CNT, k2hash::MIN_PAGE_SIZE ) }
identifier_body
lib.rs
extern crate k2hash; extern crate k2hash_sys; use k2hash::K2Hash; fn build_wrapped_k2hash() -> Result<K2Hash, std::io::Error> { let path = std::path::Path::new("/tmp/tmp.k2hash"); K2Hash::new(path, false, true, true, k2hash::DEFAULT_MASK_BITCOUNT, k2hash::DEFAULT_COLLISION_MASK_BITCOUNT, k2hash::DEFAULT_MAX_ELEMENT_CNT, k2hash::MIN_PAGE_SIZE ) } #[test] fn
() { let result = build_wrapped_k2hash(); result.unwrap(); assert!(true); } #[test] fn test_set_str() { let k2hash = build_wrapped_k2hash().unwrap(); let key = "test_set_str"; let val = "val"; let result = k2hash.set_str(key.to_string(), val.to_string()); result.unwrap(); assert!(true); } #[test] fn test_get_str() { let k2hash = build_wrapped_k2hash().unwrap(); let key = "test_get_str"; let val = "val"; k2hash.set_str(key.to_string(), val.to_string()).unwrap(); let actual = k2hash.get_str(key.to_string()).unwrap(); assert_eq!(actual, val); }
test_new
identifier_name
lib.rs
extern crate k2hash; extern crate k2hash_sys; use k2hash::K2Hash; fn build_wrapped_k2hash() -> Result<K2Hash, std::io::Error> { let path = std::path::Path::new("/tmp/tmp.k2hash"); K2Hash::new(path, false, true, true, k2hash::DEFAULT_MASK_BITCOUNT, k2hash::DEFAULT_COLLISION_MASK_BITCOUNT, k2hash::DEFAULT_MAX_ELEMENT_CNT, k2hash::MIN_PAGE_SIZE ) } #[test] fn test_new() { let result = build_wrapped_k2hash();
} #[test] fn test_set_str() { let k2hash = build_wrapped_k2hash().unwrap(); let key = "test_set_str"; let val = "val"; let result = k2hash.set_str(key.to_string(), val.to_string()); result.unwrap(); assert!(true); } #[test] fn test_get_str() { let k2hash = build_wrapped_k2hash().unwrap(); let key = "test_get_str"; let val = "val"; k2hash.set_str(key.to_string(), val.to_string()).unwrap(); let actual = k2hash.get_str(key.to_string()).unwrap(); assert_eq!(actual, val); }
result.unwrap(); assert!(true);
random_line_split
exponential.rs
extern crate rand; use crate::distribs::distribution::*; use std::cell::Cell; #[allow(dead_code)] pub struct Exponential { lambda: f64, } impl Exponential { pub fn new(rate: f64) -> Exponential { Exponential { lambda: rate } } } impl Distribution<f64> for Exponential { //Using the Inverse Transfom Sampling method (https://en.wikipedia.org/wiki/Inverse_transform_sampling) fn sample(&self) -> RandomVariable<f64> { let prob = rand::random::<f64>(); let factor = -self.lambda.recip(); RandomVariable { value: Cell::new(factor * (1.0f64 - prob).ln()) } } fn mu(&self) -> f64 { self.lambda.recip() } fn sigma(&self) -> f64 { self.lambda.recip().powi(2) } fn pdf(&self, x: f64) -> f64 { self.lambda * (-self.lambda * x).exp() } fn
(&self, x: f64) -> f64 { 1.0f64 - (-self.lambda * x).exp() } }
cdf
identifier_name
exponential.rs
extern crate rand; use crate::distribs::distribution::*; use std::cell::Cell; #[allow(dead_code)] pub struct Exponential { lambda: f64, } impl Exponential { pub fn new(rate: f64) -> Exponential { Exponential { lambda: rate } } } impl Distribution<f64> for Exponential { //Using the Inverse Transfom Sampling method (https://en.wikipedia.org/wiki/Inverse_transform_sampling) fn sample(&self) -> RandomVariable<f64> { let prob = rand::random::<f64>(); let factor = -self.lambda.recip(); RandomVariable { value: Cell::new(factor * (1.0f64 - prob).ln()) } } fn mu(&self) -> f64 { self.lambda.recip() }
} fn pdf(&self, x: f64) -> f64 { self.lambda * (-self.lambda * x).exp() } fn cdf(&self, x: f64) -> f64 { 1.0f64 - (-self.lambda * x).exp() } }
fn sigma(&self) -> f64 { self.lambda.recip().powi(2)
random_line_split
exponential.rs
extern crate rand; use crate::distribs::distribution::*; use std::cell::Cell; #[allow(dead_code)] pub struct Exponential { lambda: f64, } impl Exponential { pub fn new(rate: f64) -> Exponential { Exponential { lambda: rate } } } impl Distribution<f64> for Exponential { //Using the Inverse Transfom Sampling method (https://en.wikipedia.org/wiki/Inverse_transform_sampling) fn sample(&self) -> RandomVariable<f64> { let prob = rand::random::<f64>(); let factor = -self.lambda.recip(); RandomVariable { value: Cell::new(factor * (1.0f64 - prob).ln()) } } fn mu(&self) -> f64
fn sigma(&self) -> f64 { self.lambda.recip().powi(2) } fn pdf(&self, x: f64) -> f64 { self.lambda * (-self.lambda * x).exp() } fn cdf(&self, x: f64) -> f64 { 1.0f64 - (-self.lambda * x).exp() } }
{ self.lambda.recip() }
identifier_body
validator.rs
// Copyright 2015 Β© Samuel Dolt <[email protected]> // // This file is part of orion_backend. // // Orion_backend 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. // // Orion_backend 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 orion_backend. If not, see <http://www.gnu.org/licenses/>. use chrono::DateTime; pub trait OrionLoggerValidator { fn is_rfc3339_timestamp(&self) -> bool; } impl OrionLoggerValidator for String { fn i
&self) -> bool { match DateTime::parse_from_rfc3339(&self) { Ok(_) => true, Err(_) => false, } } }
s_rfc3339_timestamp(
identifier_name
validator.rs
// Copyright 2015 Β© Samuel Dolt <[email protected]> // // This file is part of orion_backend. // // Orion_backend 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. // // Orion_backend 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 orion_backend. If not, see <http://www.gnu.org/licenses/>. use chrono::DateTime; pub trait OrionLoggerValidator { fn is_rfc3339_timestamp(&self) -> bool; } impl OrionLoggerValidator for String { fn is_rfc3339_timestamp(&self) -> bool {
}
match DateTime::parse_from_rfc3339(&self) { Ok(_) => true, Err(_) => false, } }
identifier_body
validator.rs
// Copyright 2015 Β© Samuel Dolt <[email protected]> // // This file is part of orion_backend. // // Orion_backend 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. // // Orion_backend 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 orion_backend. If not, see <http://www.gnu.org/licenses/>. use chrono::DateTime; pub trait OrionLoggerValidator { fn is_rfc3339_timestamp(&self) -> bool; } impl OrionLoggerValidator for String {
} } }
fn is_rfc3339_timestamp(&self) -> bool { match DateTime::parse_from_rfc3339(&self) { Ok(_) => true, Err(_) => false,
random_line_split
optional_comma_in_match_arm.rs
// run-pass #![allow(unused_unsafe)] // ignore-pretty issue #37199 #![allow(while_true)] fn main()
6 => { () } 7 => unsafe { () } _ => () } let r: &i32 = &x; match r { // Absence of comma should not cause confusion between a pattern // and a bitwise and. &1 => if true { () } else { () } &2 => (), _ =>() } }
{ let x = 1; match x { 1 => loop { break; }, 2 => while true { break; }, 3 => if true { () }, 4 => if true { () } else { () }, 5 => match () { () => () }, 6 => { () }, 7 => unsafe { () }, _ => (), } match x { 1 => loop { break; } 2 => while true { break; } 3 => if true { () } 4 => if true { () } else { () } 5 => match () { () => () }
identifier_body
optional_comma_in_match_arm.rs
// run-pass #![allow(unused_unsafe)] // ignore-pretty issue #37199 #![allow(while_true)] fn main() { let x = 1; match x { 1 => loop { break; }, 2 => while true { break; }, 3 => if true { () }, 4 => if true { () } else { () }, 5 => match () { () => () }, 6 => { () }, 7 => unsafe { () },
2 => while true { break; } 3 => if true { () } 4 => if true { () } else { () } 5 => match () { () => () } 6 => { () } 7 => unsafe { () } _ => () } let r: &i32 = &x; match r { // Absence of comma should not cause confusion between a pattern // and a bitwise and. &1 => if true { () } else { () } &2 => (), _ =>() } }
_ => (), } match x { 1 => loop { break; }
random_line_split
optional_comma_in_match_arm.rs
// run-pass #![allow(unused_unsafe)] // ignore-pretty issue #37199 #![allow(while_true)] fn
() { let x = 1; match x { 1 => loop { break; }, 2 => while true { break; }, 3 => if true { () }, 4 => if true { () } else { () }, 5 => match () { () => () }, 6 => { () }, 7 => unsafe { () }, _ => (), } match x { 1 => loop { break; } 2 => while true { break; } 3 => if true { () } 4 => if true { () } else { () } 5 => match () { () => () } 6 => { () } 7 => unsafe { () } _ => () } let r: &i32 = &x; match r { // Absence of comma should not cause confusion between a pattern // and a bitwise and. &1 => if true { () } else { () } &2 => (), _ =>() } }
main
identifier_name
restore-topology.rs
use futures_lite::stream::StreamExt; use lapin::{options::*, topology::*, BasicProperties, Connection, ConnectionProperties, Result}; use tracing::info; fn main() -> Result<()> { if std::env::var("RUST_LOG").is_err()
tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); let topology_str = std::fs::read_to_string("examples/topology.json").unwrap(); let topology = serde_json::from_str::<TopologyDefinition>(&topology_str).unwrap(); async_global_executor::block_on(async { let conn = Connection::connect(&addr, ConnectionProperties::default()).await?; info!("CONNECTED"); let topology = conn.restore(topology).await?; let trash_queue = topology.queue(0); let channel_a = topology.channel(0); // Can be used as Channel thanks to Deref let channel_b = topology.channel(1).into_inner(); // Get the actual inner Channel let tmp_queue = channel_a.queue(0); let mut consumer = channel_a.consumer(0); info!(?trash_queue,?tmp_queue, "Declared queues"); channel_b .basic_publish( "", "trash-queue", BasicPublishOptions::default(), b"test payload".to_vec(), BasicProperties::default(), ) .await? .await?; let delivery = consumer.next().await; assert_eq!(b"test payload".to_vec(), delivery.unwrap()?.data); channel_a .basic_cancel(consumer.tag().as_str(), BasicCancelOptions::default()) .await?; Ok(()) }) }
{ std::env::set_var("RUST_LOG", "info"); }
conditional_block
restore-topology.rs
use futures_lite::stream::StreamExt; use lapin::{options::*, topology::*, BasicProperties, Connection, ConnectionProperties, Result}; use tracing::info; fn main() -> Result<()>
let channel_b = topology.channel(1).into_inner(); // Get the actual inner Channel let tmp_queue = channel_a.queue(0); let mut consumer = channel_a.consumer(0); info!(?trash_queue,?tmp_queue, "Declared queues"); channel_b .basic_publish( "", "trash-queue", BasicPublishOptions::default(), b"test payload".to_vec(), BasicProperties::default(), ) .await? .await?; let delivery = consumer.next().await; assert_eq!(b"test payload".to_vec(), delivery.unwrap()?.data); channel_a .basic_cancel(consumer.tag().as_str(), BasicCancelOptions::default()) .await?; Ok(()) }) }
{ if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "info"); } tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); let topology_str = std::fs::read_to_string("examples/topology.json").unwrap(); let topology = serde_json::from_str::<TopologyDefinition>(&topology_str).unwrap(); async_global_executor::block_on(async { let conn = Connection::connect(&addr, ConnectionProperties::default()).await?; info!("CONNECTED"); let topology = conn.restore(topology).await?; let trash_queue = topology.queue(0); let channel_a = topology.channel(0); // Can be used as Channel thanks to Deref
identifier_body
restore-topology.rs
use futures_lite::stream::StreamExt; use lapin::{options::*, topology::*, BasicProperties, Connection, ConnectionProperties, Result};
fn main() -> Result<()> { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "info"); } tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); let topology_str = std::fs::read_to_string("examples/topology.json").unwrap(); let topology = serde_json::from_str::<TopologyDefinition>(&topology_str).unwrap(); async_global_executor::block_on(async { let conn = Connection::connect(&addr, ConnectionProperties::default()).await?; info!("CONNECTED"); let topology = conn.restore(topology).await?; let trash_queue = topology.queue(0); let channel_a = topology.channel(0); // Can be used as Channel thanks to Deref let channel_b = topology.channel(1).into_inner(); // Get the actual inner Channel let tmp_queue = channel_a.queue(0); let mut consumer = channel_a.consumer(0); info!(?trash_queue,?tmp_queue, "Declared queues"); channel_b .basic_publish( "", "trash-queue", BasicPublishOptions::default(), b"test payload".to_vec(), BasicProperties::default(), ) .await? .await?; let delivery = consumer.next().await; assert_eq!(b"test payload".to_vec(), delivery.unwrap()?.data); channel_a .basic_cancel(consumer.tag().as_str(), BasicCancelOptions::default()) .await?; Ok(()) }) }
use tracing::info;
random_line_split
restore-topology.rs
use futures_lite::stream::StreamExt; use lapin::{options::*, topology::*, BasicProperties, Connection, ConnectionProperties, Result}; use tracing::info; fn
() -> Result<()> { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "info"); } tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); let topology_str = std::fs::read_to_string("examples/topology.json").unwrap(); let topology = serde_json::from_str::<TopologyDefinition>(&topology_str).unwrap(); async_global_executor::block_on(async { let conn = Connection::connect(&addr, ConnectionProperties::default()).await?; info!("CONNECTED"); let topology = conn.restore(topology).await?; let trash_queue = topology.queue(0); let channel_a = topology.channel(0); // Can be used as Channel thanks to Deref let channel_b = topology.channel(1).into_inner(); // Get the actual inner Channel let tmp_queue = channel_a.queue(0); let mut consumer = channel_a.consumer(0); info!(?trash_queue,?tmp_queue, "Declared queues"); channel_b .basic_publish( "", "trash-queue", BasicPublishOptions::default(), b"test payload".to_vec(), BasicProperties::default(), ) .await? .await?; let delivery = consumer.next().await; assert_eq!(b"test payload".to_vec(), delivery.unwrap()?.data); channel_a .basic_cancel(consumer.tag().as_str(), BasicCancelOptions::default()) .await?; Ok(()) }) }
main
identifier_name
mod.rs
mod approach; mod character; mod friend; mod context; mod chat; mod authorized; mod player_status; mod error; use super::{Session, GameState, AccountData, SocialInformations, SocialState};
use protocol::messages::queues::*; use protocol::messages::game::basic::TextInformationMessage; use protocol::enums::text_information_type; use std::io::{self, Result}; use std::sync::atomic::Ordering; use shared::{self, database}; use diesel::*; use server::SERVER; use character::Character; use std::mem; use std::collections::HashMap; use shared::database::schema::{accounts, social_relations}; impl shared::session::Session<ChunkImpl> for Session { fn new(base: shared::session::SessionBase) -> Self { let mut buf = ProtocolRequired { required_version: 1658, current_version: 1658, }.unwrap(); HelloGameMessage.unwrap_with_buf(&mut buf); write!(SERVER, base.token, buf); Session { base: base, account: None, state: GameState::None, last_sales_chat_request: 0, last_seek_chat_request: 0, friends_cache: HashMap::new(), ignored_cache: HashMap::new(), } } fn handle<'a>(&mut self, chunk: Ref<'a>, id: i16, mut data: io::Cursor<Vec<u8>>) -> Result<()> { use protocol::messages::game::friend::{ FriendsGetListMessage, FriendSetWarnOnConnectionMessage, FriendSetWarnOnLevelGainMessage, IgnoredGetListMessage, FriendAddRequestMessage, FriendDeleteRequestMessage, IgnoredAddRequestMessage, IgnoredDeleteRequestMessage, }; use protocol::messages::game::character::status::PlayerStatusUpdateRequestMessage; use protocol::messages::game::chat::{ ChatClientMultiMessage, ChatClientMultiWithObjectMessage, ChatClientPrivateMessage, ChatClientPrivateWithObjectMessage, }; use protocol::messages::game::chat::channel::ChannelEnablingMessage; use protocol::messages::game::chat::smiley::{ ChatSmileyRequestMessage, MoodSmileyRequestMessage, }; use protocol::messages::game::character::choice::{ CharactersListRequestMessage, CharacterSelectionMessage, }; use protocol::messages::game::character::creation::{ CharacterCreationRequestMessage, }; use protocol::messages::authorized::{ AdminQuietCommandMessage, }; use protocol::messages::game::context::{ GameContextCreateRequestMessage, GameMapMovementRequestMessage, GameMapMovementCancelMessage, GameMapMovementConfirmMessage, }; use protocol::messages::game::context::roleplay::{ MapInformationsRequestMessage, ChangeMapMessage, }; handle!(self, chunk, id, data) } fn close<'a>(mut self, mut chunk: Ref<'a>) { let account = mem::replace(&mut self.account, None); if let Some(account) = account { SERVER.with(|s| database::execute(&s.auth_db, move |conn| { if let Err(err) = Session::save_auth(conn, account) { error!("error while saving session to auth db: {:?}", err); } })); } let state = mem::replace(&mut self.state, GameState::None); if let GameState::InContext(ch) = state { let map_id = ch.map_id; let ch = chunk.maps .get_mut(&ch.map_id).unwrap() .remove_actor(ch.id).unwrap() .into_character(); SERVER.with(|s| database::execute(&s.db, move |conn| { if let Err(err) = self.base.save_logs(conn, ch.minimal().account_id()) { error!("error while saving logs: {:?}", err); } if let Err(err) = self.save_game(conn, ch, map_id) { error!("error while saving session to game db: {:?}", err); } })); } } } impl Session { pub fn update_queue(&self) { let (global_queue_size, global_queue_counter) = match self.state { GameState::TicketQueue(..) => { use self::approach::{QUEUE_COUNTER, QUEUE_SIZE}; (QUEUE_COUNTER.load(Ordering::Relaxed), QUEUE_SIZE.load(Ordering::Relaxed)) } GameState::GameQueue(..) => { use self::character::{QUEUE_COUNTER, QUEUE_SIZE}; (QUEUE_COUNTER.load(Ordering::Relaxed), QUEUE_SIZE.load(Ordering::Relaxed)) } _ => return (), }; let (former_queue_size, former_queue_counter) = match self.state { GameState::TicketQueue(qs, qc) | GameState::GameQueue(qs, qc) => (qs, qc), _ => unreachable!(), }; let mut pos = former_queue_size - (global_queue_counter - former_queue_counter); if pos < 0 { pos = 0; } let buf = QueueStatusMessage { position: pos as i16, total: global_queue_size as i16, }.unwrap(); write!(SERVER, self.base.token, buf); } pub fn update_social(&mut self, ch: &CharacterMinimal, social: Option<&SocialInformations>, ty: SocialUpdateType) { let account = match self.account.as_ref() { Some(account) => account, None => return, }; let account_id = ch.account_id(); if account.social.has_relation_with(account_id, SocialState::Friend) { let _ = self.friends_cache.insert( account_id, ch.as_relation_infos(account.id, social, SocialState::Friend).as_friend() ); match ty { SocialUpdateType::Online if account.social.warn_on_connection => { let buf = TextInformationMessage { msg_type: text_information_type::MESSAGE, msg_id: VarShort(143), parameters: vec![ch.name().to_string(), ch.account_nickname().to_string(), account_id.to_string()], }.unwrap(); write!(SERVER, self.base.token, buf); }, SocialUpdateType::WithLevel(_) if account.social.warn_on_level_gain => { // TODO }, _ => (), } } if account.social.has_relation_with(account_id, SocialState::Ignored) { let _ = self.ignored_cache.insert( account_id, ch.as_relation_infos(account.id, social, SocialState::Ignored).as_ignored() ); } } } #[changeset_for(accounts)] struct UpdateSqlAccount { already_logged: Option<i16>, last_server: Option<i16>, channels: Option<Vec<i16>>, } #[derive(Queryable)] #[changeset_for(social_relations)] struct SqlRelations { friends: Vec<i32>, ignored: Vec<i32>, warn_on_connection: bool, warn_on_level_gain: bool, } impl Session { fn save_auth(conn: &Connection, account: AccountData) -> QueryResult<()> { try!(conn.transaction(move || { let _ = try!( update( accounts::table.filter(accounts::id.eq(&account.id)) ).set(&UpdateSqlAccount { already_logged: Some(0), last_server: None, channels: Some(account.channels.into_iter().map(|c| c as i16).collect()), }).execute(conn) ); let _ = try!( update( social_relations::table.filter(social_relations::id.eq(&account.id)) ).set(&SqlRelations { friends: account.social.friends.into_iter().collect(), ignored: account.social.ignored.into_iter().collect(), warn_on_connection: account.social.warn_on_connection, warn_on_level_gain: account.social.warn_on_level_gain, }).execute(conn) ); Ok(()) })); Ok(()) } fn save_game(&self, conn: &Connection, ch: Character, map: i32) -> QueryResult<()> { try!(conn.transaction(|| { ch.save(conn, map) })); Ok(()) } }
use super::chunk::{ChunkImpl, Ref, SocialUpdateType}; use character::CharacterMinimal; use protocol::{Protocol, VarShort}; use protocol::messages::handshake::*; use protocol::messages::game::approach::*;
random_line_split
mod.rs
mod approach; mod character; mod friend; mod context; mod chat; mod authorized; mod player_status; mod error; use super::{Session, GameState, AccountData, SocialInformations, SocialState}; use super::chunk::{ChunkImpl, Ref, SocialUpdateType}; use character::CharacterMinimal; use protocol::{Protocol, VarShort}; use protocol::messages::handshake::*; use protocol::messages::game::approach::*; use protocol::messages::queues::*; use protocol::messages::game::basic::TextInformationMessage; use protocol::enums::text_information_type; use std::io::{self, Result}; use std::sync::atomic::Ordering; use shared::{self, database}; use diesel::*; use server::SERVER; use character::Character; use std::mem; use std::collections::HashMap; use shared::database::schema::{accounts, social_relations}; impl shared::session::Session<ChunkImpl> for Session { fn new(base: shared::session::SessionBase) -> Self { let mut buf = ProtocolRequired { required_version: 1658, current_version: 1658, }.unwrap(); HelloGameMessage.unwrap_with_buf(&mut buf); write!(SERVER, base.token, buf); Session { base: base, account: None, state: GameState::None, last_sales_chat_request: 0, last_seek_chat_request: 0, friends_cache: HashMap::new(), ignored_cache: HashMap::new(), } } fn handle<'a>(&mut self, chunk: Ref<'a>, id: i16, mut data: io::Cursor<Vec<u8>>) -> Result<()> { use protocol::messages::game::friend::{ FriendsGetListMessage, FriendSetWarnOnConnectionMessage, FriendSetWarnOnLevelGainMessage, IgnoredGetListMessage, FriendAddRequestMessage, FriendDeleteRequestMessage, IgnoredAddRequestMessage, IgnoredDeleteRequestMessage, }; use protocol::messages::game::character::status::PlayerStatusUpdateRequestMessage; use protocol::messages::game::chat::{ ChatClientMultiMessage, ChatClientMultiWithObjectMessage, ChatClientPrivateMessage, ChatClientPrivateWithObjectMessage, }; use protocol::messages::game::chat::channel::ChannelEnablingMessage; use protocol::messages::game::chat::smiley::{ ChatSmileyRequestMessage, MoodSmileyRequestMessage, }; use protocol::messages::game::character::choice::{ CharactersListRequestMessage, CharacterSelectionMessage, }; use protocol::messages::game::character::creation::{ CharacterCreationRequestMessage, }; use protocol::messages::authorized::{ AdminQuietCommandMessage, }; use protocol::messages::game::context::{ GameContextCreateRequestMessage, GameMapMovementRequestMessage, GameMapMovementCancelMessage, GameMapMovementConfirmMessage, }; use protocol::messages::game::context::roleplay::{ MapInformationsRequestMessage, ChangeMapMessage, }; handle!(self, chunk, id, data) } fn close<'a>(mut self, mut chunk: Ref<'a>) { let account = mem::replace(&mut self.account, None); if let Some(account) = account { SERVER.with(|s| database::execute(&s.auth_db, move |conn| { if let Err(err) = Session::save_auth(conn, account) { error!("error while saving session to auth db: {:?}", err); } })); } let state = mem::replace(&mut self.state, GameState::None); if let GameState::InContext(ch) = state { let map_id = ch.map_id; let ch = chunk.maps .get_mut(&ch.map_id).unwrap() .remove_actor(ch.id).unwrap() .into_character(); SERVER.with(|s| database::execute(&s.db, move |conn| { if let Err(err) = self.base.save_logs(conn, ch.minimal().account_id()) { error!("error while saving logs: {:?}", err); } if let Err(err) = self.save_game(conn, ch, map_id) { error!("error while saving session to game db: {:?}", err); } })); } } } impl Session { pub fn update_queue(&self) { let (global_queue_size, global_queue_counter) = match self.state { GameState::TicketQueue(..) => { use self::approach::{QUEUE_COUNTER, QUEUE_SIZE}; (QUEUE_COUNTER.load(Ordering::Relaxed), QUEUE_SIZE.load(Ordering::Relaxed)) } GameState::GameQueue(..) => { use self::character::{QUEUE_COUNTER, QUEUE_SIZE}; (QUEUE_COUNTER.load(Ordering::Relaxed), QUEUE_SIZE.load(Ordering::Relaxed)) } _ => return (), }; let (former_queue_size, former_queue_counter) = match self.state { GameState::TicketQueue(qs, qc) | GameState::GameQueue(qs, qc) => (qs, qc), _ => unreachable!(), }; let mut pos = former_queue_size - (global_queue_counter - former_queue_counter); if pos < 0 { pos = 0; } let buf = QueueStatusMessage { position: pos as i16, total: global_queue_size as i16, }.unwrap(); write!(SERVER, self.base.token, buf); } pub fn update_social(&mut self, ch: &CharacterMinimal, social: Option<&SocialInformations>, ty: SocialUpdateType) { let account = match self.account.as_ref() { Some(account) => account, None => return, }; let account_id = ch.account_id(); if account.social.has_relation_with(account_id, SocialState::Friend) { let _ = self.friends_cache.insert( account_id, ch.as_relation_infos(account.id, social, SocialState::Friend).as_friend() ); match ty { SocialUpdateType::Online if account.social.warn_on_connection => { let buf = TextInformationMessage { msg_type: text_information_type::MESSAGE, msg_id: VarShort(143), parameters: vec![ch.name().to_string(), ch.account_nickname().to_string(), account_id.to_string()], }.unwrap(); write!(SERVER, self.base.token, buf); }, SocialUpdateType::WithLevel(_) if account.social.warn_on_level_gain => { // TODO }, _ => (), } } if account.social.has_relation_with(account_id, SocialState::Ignored) { let _ = self.ignored_cache.insert( account_id, ch.as_relation_infos(account.id, social, SocialState::Ignored).as_ignored() ); } } } #[changeset_for(accounts)] struct UpdateSqlAccount { already_logged: Option<i16>, last_server: Option<i16>, channels: Option<Vec<i16>>, } #[derive(Queryable)] #[changeset_for(social_relations)] struct SqlRelations { friends: Vec<i32>, ignored: Vec<i32>, warn_on_connection: bool, warn_on_level_gain: bool, } impl Session { fn save_auth(conn: &Connection, account: AccountData) -> QueryResult<()> { try!(conn.transaction(move || { let _ = try!( update( accounts::table.filter(accounts::id.eq(&account.id)) ).set(&UpdateSqlAccount { already_logged: Some(0), last_server: None, channels: Some(account.channels.into_iter().map(|c| c as i16).collect()), }).execute(conn) ); let _ = try!( update( social_relations::table.filter(social_relations::id.eq(&account.id)) ).set(&SqlRelations { friends: account.social.friends.into_iter().collect(), ignored: account.social.ignored.into_iter().collect(), warn_on_connection: account.social.warn_on_connection, warn_on_level_gain: account.social.warn_on_level_gain, }).execute(conn) ); Ok(()) })); Ok(()) } fn
(&self, conn: &Connection, ch: Character, map: i32) -> QueryResult<()> { try!(conn.transaction(|| { ch.save(conn, map) })); Ok(()) } }
save_game
identifier_name
mod.rs
mod approach; mod character; mod friend; mod context; mod chat; mod authorized; mod player_status; mod error; use super::{Session, GameState, AccountData, SocialInformations, SocialState}; use super::chunk::{ChunkImpl, Ref, SocialUpdateType}; use character::CharacterMinimal; use protocol::{Protocol, VarShort}; use protocol::messages::handshake::*; use protocol::messages::game::approach::*; use protocol::messages::queues::*; use protocol::messages::game::basic::TextInformationMessage; use protocol::enums::text_information_type; use std::io::{self, Result}; use std::sync::atomic::Ordering; use shared::{self, database}; use diesel::*; use server::SERVER; use character::Character; use std::mem; use std::collections::HashMap; use shared::database::schema::{accounts, social_relations}; impl shared::session::Session<ChunkImpl> for Session { fn new(base: shared::session::SessionBase) -> Self { let mut buf = ProtocolRequired { required_version: 1658, current_version: 1658, }.unwrap(); HelloGameMessage.unwrap_with_buf(&mut buf); write!(SERVER, base.token, buf); Session { base: base, account: None, state: GameState::None, last_sales_chat_request: 0, last_seek_chat_request: 0, friends_cache: HashMap::new(), ignored_cache: HashMap::new(), } } fn handle<'a>(&mut self, chunk: Ref<'a>, id: i16, mut data: io::Cursor<Vec<u8>>) -> Result<()> { use protocol::messages::game::friend::{ FriendsGetListMessage, FriendSetWarnOnConnectionMessage, FriendSetWarnOnLevelGainMessage, IgnoredGetListMessage, FriendAddRequestMessage, FriendDeleteRequestMessage, IgnoredAddRequestMessage, IgnoredDeleteRequestMessage, }; use protocol::messages::game::character::status::PlayerStatusUpdateRequestMessage; use protocol::messages::game::chat::{ ChatClientMultiMessage, ChatClientMultiWithObjectMessage, ChatClientPrivateMessage, ChatClientPrivateWithObjectMessage, }; use protocol::messages::game::chat::channel::ChannelEnablingMessage; use protocol::messages::game::chat::smiley::{ ChatSmileyRequestMessage, MoodSmileyRequestMessage, }; use protocol::messages::game::character::choice::{ CharactersListRequestMessage, CharacterSelectionMessage, }; use protocol::messages::game::character::creation::{ CharacterCreationRequestMessage, }; use protocol::messages::authorized::{ AdminQuietCommandMessage, }; use protocol::messages::game::context::{ GameContextCreateRequestMessage, GameMapMovementRequestMessage, GameMapMovementCancelMessage, GameMapMovementConfirmMessage, }; use protocol::messages::game::context::roleplay::{ MapInformationsRequestMessage, ChangeMapMessage, }; handle!(self, chunk, id, data) } fn close<'a>(mut self, mut chunk: Ref<'a>) { let account = mem::replace(&mut self.account, None); if let Some(account) = account { SERVER.with(|s| database::execute(&s.auth_db, move |conn| { if let Err(err) = Session::save_auth(conn, account) { error!("error while saving session to auth db: {:?}", err); } })); } let state = mem::replace(&mut self.state, GameState::None); if let GameState::InContext(ch) = state { let map_id = ch.map_id; let ch = chunk.maps .get_mut(&ch.map_id).unwrap() .remove_actor(ch.id).unwrap() .into_character(); SERVER.with(|s| database::execute(&s.db, move |conn| { if let Err(err) = self.base.save_logs(conn, ch.minimal().account_id()) { error!("error while saving logs: {:?}", err); } if let Err(err) = self.save_game(conn, ch, map_id) { error!("error while saving session to game db: {:?}", err); } })); } } } impl Session { pub fn update_queue(&self) { let (global_queue_size, global_queue_counter) = match self.state { GameState::TicketQueue(..) => { use self::approach::{QUEUE_COUNTER, QUEUE_SIZE}; (QUEUE_COUNTER.load(Ordering::Relaxed), QUEUE_SIZE.load(Ordering::Relaxed)) } GameState::GameQueue(..) => { use self::character::{QUEUE_COUNTER, QUEUE_SIZE}; (QUEUE_COUNTER.load(Ordering::Relaxed), QUEUE_SIZE.load(Ordering::Relaxed)) } _ => return (), }; let (former_queue_size, former_queue_counter) = match self.state { GameState::TicketQueue(qs, qc) | GameState::GameQueue(qs, qc) => (qs, qc), _ => unreachable!(), }; let mut pos = former_queue_size - (global_queue_counter - former_queue_counter); if pos < 0 { pos = 0; } let buf = QueueStatusMessage { position: pos as i16, total: global_queue_size as i16, }.unwrap(); write!(SERVER, self.base.token, buf); } pub fn update_social(&mut self, ch: &CharacterMinimal, social: Option<&SocialInformations>, ty: SocialUpdateType) { let account = match self.account.as_ref() { Some(account) => account, None => return, }; let account_id = ch.account_id(); if account.social.has_relation_with(account_id, SocialState::Friend) { let _ = self.friends_cache.insert( account_id, ch.as_relation_infos(account.id, social, SocialState::Friend).as_friend() ); match ty { SocialUpdateType::Online if account.social.warn_on_connection => { let buf = TextInformationMessage { msg_type: text_information_type::MESSAGE, msg_id: VarShort(143), parameters: vec![ch.name().to_string(), ch.account_nickname().to_string(), account_id.to_string()], }.unwrap(); write!(SERVER, self.base.token, buf); }, SocialUpdateType::WithLevel(_) if account.social.warn_on_level_gain => { // TODO }, _ => (), } } if account.social.has_relation_with(account_id, SocialState::Ignored) { let _ = self.ignored_cache.insert( account_id, ch.as_relation_infos(account.id, social, SocialState::Ignored).as_ignored() ); } } } #[changeset_for(accounts)] struct UpdateSqlAccount { already_logged: Option<i16>, last_server: Option<i16>, channels: Option<Vec<i16>>, } #[derive(Queryable)] #[changeset_for(social_relations)] struct SqlRelations { friends: Vec<i32>, ignored: Vec<i32>, warn_on_connection: bool, warn_on_level_gain: bool, } impl Session { fn save_auth(conn: &Connection, account: AccountData) -> QueryResult<()> { try!(conn.transaction(move || { let _ = try!( update( accounts::table.filter(accounts::id.eq(&account.id)) ).set(&UpdateSqlAccount { already_logged: Some(0), last_server: None, channels: Some(account.channels.into_iter().map(|c| c as i16).collect()), }).execute(conn) ); let _ = try!( update( social_relations::table.filter(social_relations::id.eq(&account.id)) ).set(&SqlRelations { friends: account.social.friends.into_iter().collect(), ignored: account.social.ignored.into_iter().collect(), warn_on_connection: account.social.warn_on_connection, warn_on_level_gain: account.social.warn_on_level_gain, }).execute(conn) ); Ok(()) })); Ok(()) } fn save_game(&self, conn: &Connection, ch: Character, map: i32) -> QueryResult<()>
}
{ try!(conn.transaction(|| { ch.save(conn, map) })); Ok(()) }
identifier_body
mod.rs
mod approach; mod character; mod friend; mod context; mod chat; mod authorized; mod player_status; mod error; use super::{Session, GameState, AccountData, SocialInformations, SocialState}; use super::chunk::{ChunkImpl, Ref, SocialUpdateType}; use character::CharacterMinimal; use protocol::{Protocol, VarShort}; use protocol::messages::handshake::*; use protocol::messages::game::approach::*; use protocol::messages::queues::*; use protocol::messages::game::basic::TextInformationMessage; use protocol::enums::text_information_type; use std::io::{self, Result}; use std::sync::atomic::Ordering; use shared::{self, database}; use diesel::*; use server::SERVER; use character::Character; use std::mem; use std::collections::HashMap; use shared::database::schema::{accounts, social_relations}; impl shared::session::Session<ChunkImpl> for Session { fn new(base: shared::session::SessionBase) -> Self { let mut buf = ProtocolRequired { required_version: 1658, current_version: 1658, }.unwrap(); HelloGameMessage.unwrap_with_buf(&mut buf); write!(SERVER, base.token, buf); Session { base: base, account: None, state: GameState::None, last_sales_chat_request: 0, last_seek_chat_request: 0, friends_cache: HashMap::new(), ignored_cache: HashMap::new(), } } fn handle<'a>(&mut self, chunk: Ref<'a>, id: i16, mut data: io::Cursor<Vec<u8>>) -> Result<()> { use protocol::messages::game::friend::{ FriendsGetListMessage, FriendSetWarnOnConnectionMessage, FriendSetWarnOnLevelGainMessage, IgnoredGetListMessage, FriendAddRequestMessage, FriendDeleteRequestMessage, IgnoredAddRequestMessage, IgnoredDeleteRequestMessage, }; use protocol::messages::game::character::status::PlayerStatusUpdateRequestMessage; use protocol::messages::game::chat::{ ChatClientMultiMessage, ChatClientMultiWithObjectMessage, ChatClientPrivateMessage, ChatClientPrivateWithObjectMessage, }; use protocol::messages::game::chat::channel::ChannelEnablingMessage; use protocol::messages::game::chat::smiley::{ ChatSmileyRequestMessage, MoodSmileyRequestMessage, }; use protocol::messages::game::character::choice::{ CharactersListRequestMessage, CharacterSelectionMessage, }; use protocol::messages::game::character::creation::{ CharacterCreationRequestMessage, }; use protocol::messages::authorized::{ AdminQuietCommandMessage, }; use protocol::messages::game::context::{ GameContextCreateRequestMessage, GameMapMovementRequestMessage, GameMapMovementCancelMessage, GameMapMovementConfirmMessage, }; use protocol::messages::game::context::roleplay::{ MapInformationsRequestMessage, ChangeMapMessage, }; handle!(self, chunk, id, data) } fn close<'a>(mut self, mut chunk: Ref<'a>) { let account = mem::replace(&mut self.account, None); if let Some(account) = account
let state = mem::replace(&mut self.state, GameState::None); if let GameState::InContext(ch) = state { let map_id = ch.map_id; let ch = chunk.maps .get_mut(&ch.map_id).unwrap() .remove_actor(ch.id).unwrap() .into_character(); SERVER.with(|s| database::execute(&s.db, move |conn| { if let Err(err) = self.base.save_logs(conn, ch.minimal().account_id()) { error!("error while saving logs: {:?}", err); } if let Err(err) = self.save_game(conn, ch, map_id) { error!("error while saving session to game db: {:?}", err); } })); } } } impl Session { pub fn update_queue(&self) { let (global_queue_size, global_queue_counter) = match self.state { GameState::TicketQueue(..) => { use self::approach::{QUEUE_COUNTER, QUEUE_SIZE}; (QUEUE_COUNTER.load(Ordering::Relaxed), QUEUE_SIZE.load(Ordering::Relaxed)) } GameState::GameQueue(..) => { use self::character::{QUEUE_COUNTER, QUEUE_SIZE}; (QUEUE_COUNTER.load(Ordering::Relaxed), QUEUE_SIZE.load(Ordering::Relaxed)) } _ => return (), }; let (former_queue_size, former_queue_counter) = match self.state { GameState::TicketQueue(qs, qc) | GameState::GameQueue(qs, qc) => (qs, qc), _ => unreachable!(), }; let mut pos = former_queue_size - (global_queue_counter - former_queue_counter); if pos < 0 { pos = 0; } let buf = QueueStatusMessage { position: pos as i16, total: global_queue_size as i16, }.unwrap(); write!(SERVER, self.base.token, buf); } pub fn update_social(&mut self, ch: &CharacterMinimal, social: Option<&SocialInformations>, ty: SocialUpdateType) { let account = match self.account.as_ref() { Some(account) => account, None => return, }; let account_id = ch.account_id(); if account.social.has_relation_with(account_id, SocialState::Friend) { let _ = self.friends_cache.insert( account_id, ch.as_relation_infos(account.id, social, SocialState::Friend).as_friend() ); match ty { SocialUpdateType::Online if account.social.warn_on_connection => { let buf = TextInformationMessage { msg_type: text_information_type::MESSAGE, msg_id: VarShort(143), parameters: vec![ch.name().to_string(), ch.account_nickname().to_string(), account_id.to_string()], }.unwrap(); write!(SERVER, self.base.token, buf); }, SocialUpdateType::WithLevel(_) if account.social.warn_on_level_gain => { // TODO }, _ => (), } } if account.social.has_relation_with(account_id, SocialState::Ignored) { let _ = self.ignored_cache.insert( account_id, ch.as_relation_infos(account.id, social, SocialState::Ignored).as_ignored() ); } } } #[changeset_for(accounts)] struct UpdateSqlAccount { already_logged: Option<i16>, last_server: Option<i16>, channels: Option<Vec<i16>>, } #[derive(Queryable)] #[changeset_for(social_relations)] struct SqlRelations { friends: Vec<i32>, ignored: Vec<i32>, warn_on_connection: bool, warn_on_level_gain: bool, } impl Session { fn save_auth(conn: &Connection, account: AccountData) -> QueryResult<()> { try!(conn.transaction(move || { let _ = try!( update( accounts::table.filter(accounts::id.eq(&account.id)) ).set(&UpdateSqlAccount { already_logged: Some(0), last_server: None, channels: Some(account.channels.into_iter().map(|c| c as i16).collect()), }).execute(conn) ); let _ = try!( update( social_relations::table.filter(social_relations::id.eq(&account.id)) ).set(&SqlRelations { friends: account.social.friends.into_iter().collect(), ignored: account.social.ignored.into_iter().collect(), warn_on_connection: account.social.warn_on_connection, warn_on_level_gain: account.social.warn_on_level_gain, }).execute(conn) ); Ok(()) })); Ok(()) } fn save_game(&self, conn: &Connection, ch: Character, map: i32) -> QueryResult<()> { try!(conn.transaction(|| { ch.save(conn, map) })); Ok(()) } }
{ SERVER.with(|s| database::execute(&s.auth_db, move |conn| { if let Err(err) = Session::save_auth(conn, account) { error!("error while saving session to auth db: {:?}", err); } })); }
conditional_block
compiled.rs
modified, or distributed // except according to those terms. #![allow(non_uppercase_statics)] //! ncurses-compatible compiled terminfo format parsing (term(5)) use collections::HashMap; use std::io; use std::str; use super::super::TermInfo; // These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable. pub static boolfnames: &'static[&'static str] = &'static["auto_left_margin", "auto_right_margin", "no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type", "hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above", "memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok", "dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff", "prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region", "can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch", "cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin", "cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling", "no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs", "return_does_clr_eol"]; pub static boolnames: &'static[&'static str] = &'static["bw", "am", "xsb", "xhp", "xenl", "eo", "gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon", "nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy", "xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"]; pub static numfnames: &'static[&'static str] = &'static[ "columns", "init_tabs", "lines", "lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal", "width_status_line", "num_labels", "label_height", "label_width", "max_attributes", "maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity", "dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size", "micro_line_size", "number_of_pins", "output_res_char", "output_res_line", "output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons", "bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay", "new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"]; pub static numnames: &'static[&'static str] = &'static[ "cols", "it", "lines", "lm", "xmc", "pb", "vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv", "spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs", "btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"]; pub static stringfnames: &'static[&'static str] = &'static[ "back_tab", "bell", "carriage_return", "change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos", "column_address", "command_character", "cursor_address", "cursor_down", "cursor_home", "cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right", "cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line", "dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode", "enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode", "enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode", "enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode", "exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode", "exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string", "init_2string", "init_3string", "init_file", "insert_character", "insert_line", "insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl", "key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3", "key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il", "key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab", "key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3", "lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline", "pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index", "parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor", "pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char", "reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor", "row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab", "set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1", "key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm", "key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character", "xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close", "key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find", "key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options", "key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace", "key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel", "key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send", "key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft", "key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint", "key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend", "key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16", "key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24", "key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32", "key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40", "key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48", "key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56", "key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol", "clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock", "display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone", "quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair", "orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground", "set_background", "change_char_pitch", "change_line_pitch", "change_res_horz", "change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality", "enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality", "enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode", "enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode", "exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode", "exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right", "micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro", "parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin", "set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin", "set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image", "stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr", "zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse", "set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init", "set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin", "set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return", "color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band", "set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode", "enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape", "alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode", "enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes", "set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs", "other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner", "acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline", "acs_plus", "memory_lock", "memory_unlock", "box_chars_1"]; pub static stringnames: &'static[&'static str] = &'static[ "cbt", "_", "cr", "csr", "tbc", "clear", "_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1", "ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc", "dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc", "rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip", "kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_", "khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_", "_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey", "pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind", "ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p", "rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln", "rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp", "kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl", "krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_", "kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT", "kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf", "setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq", "snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm", "rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub", "mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd", "rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm", "setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb", "birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch", "rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm", "ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2", "OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu", "box1"]; /// Parse a compiled terminfo entry, using long capability names if `longnames` is true pub fn
(file: &mut io::Reader, longnames: bool) -> Result<Box<TermInfo>, ~str> { macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ) let bnames; let snames; let nnames; if longnames { bnames = boolfnames; snames = stringfnames; nnames = numfnames; } else { bnames = boolnames; snames = stringnames; nnames = numnames; } // Check magic number let magic = try!(file.read_le_u16()); if magic!= 0x011A { return Err(format!("invalid magic number: expected {:x} but found {:x}", 0x011A, magic as uint)); } let names_bytes = try!(file.read_le_i16()) as int; let bools_bytes = try!(file.read_le_i16()) as int; let numbers_count = try!(file.read_le_i16()) as int; let string_offsets_count = try!(file.read_le_i16()) as int; let string_table_bytes = try!(file.read_le_i16()) as int; assert!(names_bytes > 0); if (bools_bytes as uint) > boolnames.len() { return Err("incompatible file: more booleans than expected".to_owned()); } if (numbers_count as uint) > numnames.len() { return Err("incompatible file: more numbers than expected".to_owned()); } if (string_offsets_count as uint) > stringnames.len() { return Err("incompatible file: more string offsets than expected".to_owned()); } // don't read NUL let bytes = try!(file.read_exact(names_bytes as uint - 1)); let names_str = match str::from_utf8(bytes.as_slice()) { Some(s) => s.to_owned(), None => return Err("input not utf-8".to_owned()), }; let term_names: Vec<~str> = names_str.split('|').map(|s| s.to_owned()).collect(); try!(file.read_byte()); // consume NUL let mut bools_map = HashMap::new(); if bools_bytes!= 0 { for i in range(0, bools_bytes) { let b = try!(file.read_byte()); if b == 1 { bools_map.insert(bnames[i as uint].to_owned(), true); } } } if (bools_bytes + names_bytes) % 2 == 1 { try!(file.read_byte()); // compensate for padding } let mut numbers_map = HashMap::new(); if numbers_count!= 0 { for i in range(0, numbers_count) { let n = try!(file.read_le_u16()); if n!= 0xFFFF { numbers_map.insert(nnames[i as uint].to_owned(), n); } } } let mut string_map = HashMap::new(); if string_offsets_count!= 0 { let mut string_offsets = Vec::with_capacity(10); for _ in range(0, string_offsets_count) { string_offsets.push(try!(file.read_le_u16())); } let string_table = try!(file.read_exact(string_table_bytes as uint)); if string_table.len()!= string_table_bytes as uint { return Err("error: hit EOF before end of string table".to_owned()); } for (i, v) in string_offsets.iter().enumerate() { let offset = *v; if offset == 0xFFFF { // non-entry continue; } let name = if snames[i] == "_" { stringfnames[i] } else { snames[i] }; if offset == 0xFFFE { // undocumented: FFFE indicates cap@, which means the capability is not present // unsure if the handling for this is correct string_map.insert(name.to_owned(), Vec::new()); continue; } // Find the offset of the NUL we want to go to let nulpos = string_table.slice(offset as uint, string_table_bytes as uint) .iter().position(|&b| b == 0); match nulpos { Some(len) => { string_map.insert(name.to_owned(), Vec::from_slice( string_table.slice(offset as uint, offset as uint + len))) }, None => { return Err("invalid file: missing NUL in string_table".to_owned()); } }; } } // And that's all there is to it Ok(box TermInfo { names: term_names, bools: bools_map, numbers: numbers_map, strings: string_map }) } /// Create a dummy TermInfo struct for msys terminals pub fn msys_terminfo() -> Box<TermInfo> { let mut strings = HashMap::new(); strings.insert("sgr0".to_owned(), Vec::from_slice(bytes!("\x1b[0m"))); strings.insert("bold".to_owned(), Vec::from_slice(bytes!("\x1b[1m"))); strings.insert("setaf".to_owned(), Vec::from_slice(bytes!("\x1b[3%p1%dm"))); strings.insert("setab".to_owned(), Vec::from_slice(bytes!("\x1b[4%p1%dm"))); box TermInfo { names: vec!("cygwin".to_owned()), // msys is a fork of an older cygwin version bools: HashMap::new(), numbers: HashMap::new(), strings: strings } } #[cfg(test)] mod test { use super::{boolnames, boolfnames, numnames, numfnames
parse
identifier_name
compiled.rs
, modified, or distributed // except according to those terms. #![allow(non_uppercase_statics)] //! ncurses-compatible compiled terminfo format parsing (term(5)) use collections::HashMap; use std::io; use std::str; use super::super::TermInfo; // These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable. pub static boolfnames: &'static[&'static str] = &'static["auto_left_margin", "auto_right_margin", "no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type", "hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above", "memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok", "dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff", "prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region", "can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch", "cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin", "cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling", "no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs", "return_does_clr_eol"]; pub static boolnames: &'static[&'static str] = &'static["bw", "am", "xsb", "xhp", "xenl", "eo", "gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon", "nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy", "xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"]; pub static numfnames: &'static[&'static str] = &'static[ "columns", "init_tabs", "lines", "lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal", "width_status_line", "num_labels", "label_height", "label_width", "max_attributes", "maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity", "dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size", "micro_line_size", "number_of_pins", "output_res_char", "output_res_line", "output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons", "bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay", "new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"]; pub static numnames: &'static[&'static str] = &'static[ "cols", "it", "lines", "lm", "xmc", "pb", "vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv", "spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs", "btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"]; pub static stringfnames: &'static[&'static str] = &'static[ "back_tab", "bell", "carriage_return", "change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos", "column_address", "command_character", "cursor_address", "cursor_down", "cursor_home", "cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right", "cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line", "dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode", "enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode", "enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode", "enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode", "exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode", "exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string", "init_2string", "init_3string", "init_file", "insert_character", "insert_line", "insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl", "key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3", "key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il", "key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab", "key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3", "lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline", "pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index", "parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor", "pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char", "reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor", "row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab", "set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1", "key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm", "key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character", "xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close", "key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find", "key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options", "key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace", "key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel", "key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send", "key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft", "key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint", "key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend", "key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16", "key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24", "key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32", "key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40", "key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48", "key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56", "key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol", "clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock", "display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone", "quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair", "orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground", "set_background", "change_char_pitch", "change_line_pitch", "change_res_horz", "change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality", "enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality", "enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode", "enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode", "exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode", "exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right", "micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro", "parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin", "set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin", "set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image", "stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr", "zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse", "set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init", "set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin", "set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return", "color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band", "set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode", "enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape", "alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode", "enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes", "set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs", "other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner", "acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline", "acs_plus", "memory_lock", "memory_unlock", "box_chars_1"]; pub static stringnames: &'static[&'static str] = &'static[ "cbt", "_", "cr", "csr", "tbc", "clear", "_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1", "ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc", "dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc", "rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip", "kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_", "khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_", "_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey", "pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind", "ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p", "rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln", "rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp", "kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl", "krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_", "kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT", "kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf", "setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq", "snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm", "rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub", "mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd", "rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm", "setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb", "birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch", "rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm", "ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2", "OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu", "box1"]; /// Parse a compiled terminfo entry, using long capability names if `longnames` is true pub fn parse(file: &mut io::Reader, longnames: bool) -> Result<Box<TermInfo>, ~str> { macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ) let bnames; let snames; let nnames; if longnames { bnames = boolfnames; snames = stringfnames; nnames = numfnames; } else { bnames = boolnames; snames = stringnames; nnames = numnames; } // Check magic number let magic = try!(file.read_le_u16()); if magic!= 0x011A { return Err(format!("invalid magic number: expected {:x} but found {:x}", 0x011A, magic as uint)); } let names_bytes = try!(file.read_le_i16()) as int; let bools_bytes = try!(file.read_le_i16()) as int; let numbers_count = try!(file.read_le_i16()) as int; let string_offsets_count = try!(file.read_le_i16()) as int; let string_table_bytes = try!(file.read_le_i16()) as int; assert!(names_bytes > 0); if (bools_bytes as uint) > boolnames.len() { return Err("incompatible file: more booleans than expected".to_owned()); } if (numbers_count as uint) > numnames.len() { return Err("incompatible file: more numbers than expected".to_owned()); } if (string_offsets_count as uint) > stringnames.len() { return Err("incompatible file: more string offsets than expected".to_owned()); } // don't read NUL let bytes = try!(file.read_exact(names_bytes as uint - 1)); let names_str = match str::from_utf8(bytes.as_slice()) { Some(s) => s.to_owned(), None => return Err("input not utf-8".to_owned()), }; let term_names: Vec<~str> = names_str.split('|').map(|s| s.to_owned()).collect(); try!(file.read_byte()); // consume NUL let mut bools_map = HashMap::new(); if bools_bytes!= 0 { for i in range(0, bools_bytes) { let b = try!(file.read_byte()); if b == 1 { bools_map.insert(bnames[i as uint].to_owned(), true); } } } if (bools_bytes + names_bytes) % 2 == 1 { try!(file.read_byte()); // compensate for padding } let mut numbers_map = HashMap::new(); if numbers_count!= 0 { for i in range(0, numbers_count) { let n = try!(file.read_le_u16()); if n!= 0xFFFF { numbers_map.insert(nnames[i as uint].to_owned(), n); } } } let mut string_map = HashMap::new(); if string_offsets_count!= 0 { let mut string_offsets = Vec::with_capacity(10); for _ in range(0, string_offsets_count) { string_offsets.push(try!(file.read_le_u16())); } let string_table = try!(file.read_exact(string_table_bytes as uint)); if string_table.len()!= string_table_bytes as uint { return Err("error: hit EOF before end of string table".to_owned()); } for (i, v) in string_offsets.iter().enumerate() { let offset = *v; if offset == 0xFFFF { // non-entry continue; } let name = if snames[i] == "_" { stringfnames[i] } else { snames[i] }; if offset == 0xFFFE { // undocumented: FFFE indicates cap@, which means the capability is not present // unsure if the handling for this is correct string_map.insert(name.to_owned(), Vec::new()); continue; } // Find the offset of the NUL we want to go to let nulpos = string_table.slice(offset as uint, string_table_bytes as uint) .iter().position(|&b| b == 0); match nulpos { Some(len) => { string_map.insert(name.to_owned(), Vec::from_slice( string_table.slice(offset as uint, offset as uint + len))) }, None => { return Err("invalid file: missing NUL in string_table".to_owned()); } }; } } // And that's all there is to it Ok(box TermInfo { names: term_names, bools: bools_map, numbers: numbers_map, strings: string_map }) }
strings.insert("setaf".to_owned(), Vec::from_slice(bytes!("\x1b[3%p1%dm"))); strings.insert("setab".to_owned(), Vec::from_slice(bytes!("\x1b[4%p1%dm"))); box TermInfo { names: vec!("cygwin".to_owned()), // msys is a fork of an older cygwin version bools: HashMap::new(), numbers: HashMap::new(), strings: strings } } #[cfg(test)] mod test { use super::{boolnames, boolfnames, numnames, numfnames, string
/// Create a dummy TermInfo struct for msys terminals pub fn msys_terminfo() -> Box<TermInfo> { let mut strings = HashMap::new(); strings.insert("sgr0".to_owned(), Vec::from_slice(bytes!("\x1b[0m"))); strings.insert("bold".to_owned(), Vec::from_slice(bytes!("\x1b[1m")));
random_line_split
compiled.rs
_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff", "prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region", "can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch", "cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin", "cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling", "no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs", "return_does_clr_eol"]; pub static boolnames: &'static[&'static str] = &'static["bw", "am", "xsb", "xhp", "xenl", "eo", "gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon", "nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy", "xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"]; pub static numfnames: &'static[&'static str] = &'static[ "columns", "init_tabs", "lines", "lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal", "width_status_line", "num_labels", "label_height", "label_width", "max_attributes", "maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity", "dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size", "micro_line_size", "number_of_pins", "output_res_char", "output_res_line", "output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons", "bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay", "new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"]; pub static numnames: &'static[&'static str] = &'static[ "cols", "it", "lines", "lm", "xmc", "pb", "vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv", "spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs", "btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"]; pub static stringfnames: &'static[&'static str] = &'static[ "back_tab", "bell", "carriage_return", "change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos", "column_address", "command_character", "cursor_address", "cursor_down", "cursor_home", "cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right", "cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line", "dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode", "enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode", "enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode", "enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode", "exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode", "exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string", "init_2string", "init_3string", "init_file", "insert_character", "insert_line", "insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl", "key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3", "key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il", "key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab", "key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3", "lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline", "pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index", "parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor", "pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char", "reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor", "row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab", "set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1", "key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm", "key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character", "xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close", "key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find", "key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options", "key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace", "key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel", "key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send", "key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft", "key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint", "key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend", "key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16", "key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24", "key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32", "key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40", "key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48", "key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56", "key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol", "clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock", "display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone", "quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair", "orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground", "set_background", "change_char_pitch", "change_line_pitch", "change_res_horz", "change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality", "enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality", "enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode", "enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode", "exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode", "exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right", "micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro", "parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin", "set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin", "set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image", "stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr", "zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse", "set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init", "set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin", "set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return", "color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band", "set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode", "enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape", "alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode", "enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes", "set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs", "other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner", "acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline", "acs_plus", "memory_lock", "memory_unlock", "box_chars_1"]; pub static stringnames: &'static[&'static str] = &'static[ "cbt", "_", "cr", "csr", "tbc", "clear", "_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1", "ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc", "dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc", "rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip", "kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_", "khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_", "_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey", "pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind", "ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p", "rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln", "rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp", "kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl", "krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_", "kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT", "kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf", "setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq", "snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm", "rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub", "mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd", "rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm", "setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb", "birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch", "rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm", "ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2", "OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu", "box1"]; /// Parse a compiled terminfo entry, using long capability names if `longnames` is true pub fn parse(file: &mut io::Reader, longnames: bool) -> Result<Box<TermInfo>, ~str> { macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ) let bnames; let snames; let nnames; if longnames { bnames = boolfnames; snames = stringfnames; nnames = numfnames; } else { bnames = boolnames; snames = stringnames; nnames = numnames; } // Check magic number let magic = try!(file.read_le_u16()); if magic!= 0x011A { return Err(format!("invalid magic number: expected {:x} but found {:x}", 0x011A, magic as uint)); } let names_bytes = try!(file.read_le_i16()) as int; let bools_bytes = try!(file.read_le_i16()) as int; let numbers_count = try!(file.read_le_i16()) as int; let string_offsets_count = try!(file.read_le_i16()) as int; let string_table_bytes = try!(file.read_le_i16()) as int; assert!(names_bytes > 0); if (bools_bytes as uint) > boolnames.len() { return Err("incompatible file: more booleans than expected".to_owned()); } if (numbers_count as uint) > numnames.len() { return Err("incompatible file: more numbers than expected".to_owned()); } if (string_offsets_count as uint) > stringnames.len() { return Err("incompatible file: more string offsets than expected".to_owned()); } // don't read NUL let bytes = try!(file.read_exact(names_bytes as uint - 1)); let names_str = match str::from_utf8(bytes.as_slice()) { Some(s) => s.to_owned(), None => return Err("input not utf-8".to_owned()), }; let term_names: Vec<~str> = names_str.split('|').map(|s| s.to_owned()).collect(); try!(file.read_byte()); // consume NUL let mut bools_map = HashMap::new(); if bools_bytes!= 0 { for i in range(0, bools_bytes) { let b = try!(file.read_byte()); if b == 1 { bools_map.insert(bnames[i as uint].to_owned(), true); } } } if (bools_bytes + names_bytes) % 2 == 1 { try!(file.read_byte()); // compensate for padding } let mut numbers_map = HashMap::new(); if numbers_count!= 0 { for i in range(0, numbers_count) { let n = try!(file.read_le_u16()); if n!= 0xFFFF { numbers_map.insert(nnames[i as uint].to_owned(), n); } } } let mut string_map = HashMap::new(); if string_offsets_count!= 0 { let mut string_offsets = Vec::with_capacity(10); for _ in range(0, string_offsets_count) { string_offsets.push(try!(file.read_le_u16())); } let string_table = try!(file.read_exact(string_table_bytes as uint)); if string_table.len()!= string_table_bytes as uint { return Err("error: hit EOF before end of string table".to_owned()); } for (i, v) in string_offsets.iter().enumerate() { let offset = *v; if offset == 0xFFFF { // non-entry continue; } let name = if snames[i] == "_" { stringfnames[i] } else { snames[i] }; if offset == 0xFFFE { // undocumented: FFFE indicates cap@, which means the capability is not present // unsure if the handling for this is correct string_map.insert(name.to_owned(), Vec::new()); continue; } // Find the offset of the NUL we want to go to let nulpos = string_table.slice(offset as uint, string_table_bytes as uint) .iter().position(|&b| b == 0); match nulpos { Some(len) => { string_map.insert(name.to_owned(), Vec::from_slice( string_table.slice(offset as uint, offset as uint + len))) }, None => { return Err("invalid file: missing NUL in string_table".to_owned()); } }; } } // And that's all there is to it Ok(box TermInfo { names: term_names, bools: bools_map, numbers: numbers_map, strings: string_map }) } /// Create a dummy TermInfo struct for msys terminals pub fn msys_terminfo() -> Box<TermInfo> { let mut strings = HashMap::new(); strings.insert("sgr0".to_owned(), Vec::from_slice(bytes!("\x1b[0m"))); strings.insert("bold".to_owned(), Vec::from_slice(bytes!("\x1b[1m"))); strings.insert("setaf".to_owned(), Vec::from_slice(bytes!("\x1b[3%p1%dm"))); strings.insert("setab".to_owned(), Vec::from_slice(bytes!("\x1b[4%p1%dm"))); box TermInfo { names: vec!("cygwin".to_owned()), // msys is a fork of an older cygwin version bools: HashMap::new(), numbers: HashMap::new(), strings: strings } } #[cfg(test)] mod test { use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames}; #[test] fn test_veclens() { assert_eq!(boolfnames.len(), boolnames.len()); assert_eq!(numfnames.len(), numnames.len()); assert_eq!(stringfnames.len(), stringnames.len()); } #[test] #[ignore(reason = "no ncurses on buildbots, needs a bundled terminfo file to test against")] fn test_parse()
{ // FIXME #6870: Distribute a compiled file in src/tests and test there // parse(io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false); }
identifier_body
compiled.rs
modified, or distributed // except according to those terms. #![allow(non_uppercase_statics)] //! ncurses-compatible compiled terminfo format parsing (term(5)) use collections::HashMap; use std::io; use std::str; use super::super::TermInfo; // These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable. pub static boolfnames: &'static[&'static str] = &'static["auto_left_margin", "auto_right_margin", "no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type", "hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above", "memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok", "dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff", "prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region", "can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch", "cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin", "cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling", "no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs", "return_does_clr_eol"]; pub static boolnames: &'static[&'static str] = &'static["bw", "am", "xsb", "xhp", "xenl", "eo", "gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon", "nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy", "xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"]; pub static numfnames: &'static[&'static str] = &'static[ "columns", "init_tabs", "lines", "lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal", "width_status_line", "num_labels", "label_height", "label_width", "max_attributes", "maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity", "dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size", "micro_line_size", "number_of_pins", "output_res_char", "output_res_line", "output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons", "bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay", "new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"]; pub static numnames: &'static[&'static str] = &'static[ "cols", "it", "lines", "lm", "xmc", "pb", "vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv", "spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs", "btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"]; pub static stringfnames: &'static[&'static str] = &'static[ "back_tab", "bell", "carriage_return", "change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos", "column_address", "command_character", "cursor_address", "cursor_down", "cursor_home", "cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right", "cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line", "dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode", "enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode", "enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode", "enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode", "exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode", "exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string", "init_2string", "init_3string", "init_file", "insert_character", "insert_line", "insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl", "key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3", "key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il", "key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab", "key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3", "lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline", "pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index", "parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor", "pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char", "reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor", "row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab", "set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1", "key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm", "key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character", "xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close", "key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find", "key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options", "key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace", "key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel", "key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send", "key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft", "key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint", "key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend", "key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16", "key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24", "key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32", "key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40", "key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48", "key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56", "key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol", "clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock", "display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone", "quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair", "orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground", "set_background", "change_char_pitch", "change_line_pitch", "change_res_horz", "change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality", "enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality", "enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode", "enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode", "exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode", "exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right", "micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro", "parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin", "set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin", "set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image", "stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr", "zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse", "set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init", "set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin", "set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return", "color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band", "set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode", "enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape", "alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode", "enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes", "set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs", "other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner", "acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline", "acs_plus", "memory_lock", "memory_unlock", "box_chars_1"]; pub static stringnames: &'static[&'static str] = &'static[ "cbt", "_", "cr", "csr", "tbc", "clear", "_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1", "ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc", "dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc", "rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip", "kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_", "khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_", "_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey", "pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind", "ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p", "rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln", "rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp", "kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl", "krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_", "kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT", "kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf", "setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq", "snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm", "rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub", "mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd", "rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm", "setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb", "birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch", "rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm", "ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2", "OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu", "box1"]; /// Parse a compiled terminfo entry, using long capability names if `longnames` is true pub fn parse(file: &mut io::Reader, longnames: bool) -> Result<Box<TermInfo>, ~str> { macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ) let bnames; let snames; let nnames; if longnames { bnames = boolfnames; snames = stringfnames; nnames = numfnames; } else { bnames = boolnames; snames = stringnames; nnames = numnames; } // Check magic number let magic = try!(file.read_le_u16()); if magic!= 0x011A { return Err(format!("invalid magic number: expected {:x} but found {:x}", 0x011A, magic as uint)); } let names_bytes = try!(file.read_le_i16()) as int; let bools_bytes = try!(file.read_le_i16()) as int; let numbers_count = try!(file.read_le_i16()) as int; let string_offsets_count = try!(file.read_le_i16()) as int; let string_table_bytes = try!(file.read_le_i16()) as int; assert!(names_bytes > 0); if (bools_bytes as uint) > boolnames.len() { return Err("incompatible file: more booleans than expected".to_owned()); } if (numbers_count as uint) > numnames.len() { return Err("incompatible file: more numbers than expected".to_owned()); } if (string_offsets_count as uint) > stringnames.len() { return Err("incompatible file: more string offsets than expected".to_owned()); } // don't read NUL let bytes = try!(file.read_exact(names_bytes as uint - 1)); let names_str = match str::from_utf8(bytes.as_slice()) { Some(s) => s.to_owned(), None => return Err("input not utf-8".to_owned()), }; let term_names: Vec<~str> = names_str.split('|').map(|s| s.to_owned()).collect(); try!(file.read_byte()); // consume NUL let mut bools_map = HashMap::new(); if bools_bytes!= 0 { for i in range(0, bools_bytes) { let b = try!(file.read_byte()); if b == 1 { bools_map.insert(bnames[i as uint].to_owned(), true); } } } if (bools_bytes + names_bytes) % 2 == 1 { try!(file.read_byte()); // compensate for padding } let mut numbers_map = HashMap::new(); if numbers_count!= 0 { for i in range(0, numbers_count) { let n = try!(file.read_le_u16()); if n!= 0xFFFF { numbers_map.insert(nnames[i as uint].to_owned(), n); } } } let mut string_map = HashMap::new(); if string_offsets_count!= 0 { let mut string_offsets = Vec::with_capacity(10); for _ in range(0, string_offsets_count) { string_offsets.push(try!(file.read_le_u16())); } let string_table = try!(file.read_exact(string_table_bytes as uint)); if string_table.len()!= string_table_bytes as uint { return Err("error: hit EOF before end of string table".to_owned()); } for (i, v) in string_offsets.iter().enumerate() { let offset = *v; if offset == 0xFFFF { // non-entry continue; } let name = if snames[i] == "_" { stringfnames[i] } else { snames[i] }; if offset == 0xFFFE { // undocumented: FFFE indicates cap@, which means the capability is not present // unsure if the handling for this is correct string_map.insert(name.to_owned(), Vec::new()); continue; } // Find the offset of the NUL we want to go to let nulpos = string_table.slice(offset as uint, string_table_bytes as uint) .iter().position(|&b| b == 0); match nulpos { Some(len) =>
, None => { return Err("invalid file: missing NUL in string_table".to_owned()); } }; } } // And that's all there is to it Ok(box TermInfo { names: term_names, bools: bools_map, numbers: numbers_map, strings: string_map }) } /// Create a dummy TermInfo struct for msys terminals pub fn msys_terminfo() -> Box<TermInfo> { let mut strings = HashMap::new(); strings.insert("sgr0".to_owned(), Vec::from_slice(bytes!("\x1b[0m"))); strings.insert("bold".to_owned(), Vec::from_slice(bytes!("\x1b[1m"))); strings.insert("setaf".to_owned(), Vec::from_slice(bytes!("\x1b[3%p1%dm"))); strings.insert("setab".to_owned(), Vec::from_slice(bytes!("\x1b[4%p1%dm"))); box TermInfo { names: vec!("cygwin".to_owned()), // msys is a fork of an older cygwin version bools: HashMap::new(), numbers: HashMap::new(), strings: strings } } #[cfg(test)] mod test { use super::{boolnames, boolfnames, numnames, numf
{ string_map.insert(name.to_owned(), Vec::from_slice( string_table.slice(offset as uint, offset as uint + len))) }
conditional_block
vtable_recursive_sig.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] pub struct Base__bindgen_vtable { pub Base_AsDerived: unsafe extern "C" fn(this: *mut Base) -> *mut Derived, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Base { pub vtable_: *const Base__bindgen_vtable, } #[test] fn bindgen_test_layout_Base() { assert_eq!( ::std::mem::size_of::<Base>(), 8usize, concat!("Size of: ", stringify!(Base)) ); assert_eq!( ::std::mem::align_of::<Base>(), 8usize, concat!("Alignment of ", stringify!(Base)) ); } impl Default for Base { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } } extern "C" { #[link_name = "\u{1}_ZN4Base9AsDerivedEv"] pub fn Base_AsDerived(this: *mut ::std::os::raw::c_void) -> *mut Derived; } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Derived { pub _base: Base, } #[test] fn
() { assert_eq!( ::std::mem::size_of::<Derived>(), 8usize, concat!("Size of: ", stringify!(Derived)) ); assert_eq!( ::std::mem::align_of::<Derived>(), 8usize, concat!("Alignment of ", stringify!(Derived)) ); } impl Default for Derived { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } }
bindgen_test_layout_Derived
identifier_name
vtable_recursive_sig.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] pub struct Base__bindgen_vtable { pub Base_AsDerived: unsafe extern "C" fn(this: *mut Base) -> *mut Derived, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Base { pub vtable_: *const Base__bindgen_vtable, } #[test] fn bindgen_test_layout_Base() { assert_eq!( ::std::mem::size_of::<Base>(), 8usize, concat!("Size of: ", stringify!(Base)) ); assert_eq!( ::std::mem::align_of::<Base>(), 8usize, concat!("Alignment of ", stringify!(Base)) ); } impl Default for Base { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } } extern "C" { #[link_name = "\u{1}_ZN4Base9AsDerivedEv"] pub fn Base_AsDerived(this: *mut ::std::os::raw::c_void) -> *mut Derived; } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Derived { pub _base: Base, } #[test] fn bindgen_test_layout_Derived() { assert_eq!( ::std::mem::size_of::<Derived>(), 8usize, concat!("Size of: ", stringify!(Derived)) ); assert_eq!( ::std::mem::align_of::<Derived>(), 8usize, concat!("Alignment of ", stringify!(Derived)) ); } impl Default for Derived { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } }
random_line_split
mod.rs
#![cfg(target_os = "android")] extern crate android_glue; use libc; use std::ffi::{CString}; use std::sync::mpsc::{Receiver, channel}; use {CreationError, Event, MouseCursor}; use CreationError::OsError; use events::ElementState::{Pressed, Released}; use events::{Touch, TouchPhase}; use std::collections::VecDeque; use Api; use ContextError; use CursorState; use GlAttributes; use GlContext; use GlRequest; use PixelFormat; use PixelFormatRequirements; use WindowAttributes; use native_monitor::NativeMonitorId; use api::egl; use api::egl::Context as EglContext; pub struct Window { context: EglContext, event_rx: Receiver<android_glue::Event>, } #[derive(Clone)] pub struct MonitorId; mod ffi; #[inline] pub fn get_available_monitors() -> VecDeque<MonitorId> { let mut rb = VecDeque::new(); rb.push_back(MonitorId); rb } #[inline] pub fn get_primary_monitor() -> MonitorId { MonitorId } impl MonitorId { #[inline] pub fn get_name(&self) -> Option<String> { Some("Primary".to_string()) } #[inline] pub fn get_native_identifier(&self) -> NativeMonitorId { NativeMonitorId::Unavailable } #[inline] pub fn get_dimensions(&self) -> (u32, u32) { unimplemented!() } } pub struct PollEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for PollEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event>
} pub struct WaitEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for WaitEventsIterator<'a> { type Item = Event; #[inline] fn next(&mut self) -> Option<Event> { loop { // calling poll_events() if let Some(ev) = self.window.poll_events().next() { return Some(ev); } // TODO: Implement a proper way of sleeping on the event queue // timer::sleep(Duration::milliseconds(16)); } } } impl Window { pub fn new(win_attribs: &WindowAttributes, pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&Window>) -> Result<Window, CreationError> { use std::{mem, ptr}; let opengl = opengl.clone().map_sharing(|w| &w.context); let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null() { return Err(OsError(format!("Android's native window is null"))); } let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl, egl::NativeDisplay::Android) .and_then(|p| p.finish(native_window as *const _))); let (tx, rx) = channel(); android_glue::add_sender(tx); android_glue::set_multitouch(win_attribs.multitouch); Ok(Window { context: context, event_rx: rx, }) } #[inline] pub fn is_closed(&self) -> bool { false } #[inline] pub fn set_title(&self, _: &str) { } #[inline] pub fn show(&self) { } #[inline] pub fn hide(&self) { } #[inline] pub fn get_position(&self) -> Option<(i32, i32)> { None } #[inline] pub fn set_position(&self, _x: i32, _y: i32) { } #[inline] pub fn get_inner_size(&self) -> Option<(u32, u32)> { let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null() { None } else { Some(( unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32, unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32 )) } } #[inline] pub fn get_outer_size(&self) -> Option<(u32, u32)> { self.get_inner_size() } #[inline] pub fn set_inner_size(&self, _x: u32, _y: u32) { } #[inline] pub fn create_window_proxy(&self) -> WindowProxy { WindowProxy } #[inline] pub fn poll_events(&self) -> PollEventsIterator { PollEventsIterator { window: self } } #[inline] pub fn wait_events(&self) -> WaitEventsIterator { WaitEventsIterator { window: self } } #[inline] pub fn platform_display(&self) -> *mut libc::c_void { unimplemented!(); } #[inline] pub fn platform_window(&self) -> *mut libc::c_void { unimplemented!() } #[inline] pub fn get_pixel_format(&self) -> PixelFormat { unimplemented!(); } #[inline] pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) { } #[inline] pub fn set_cursor(&self, _: MouseCursor) { } #[inline] pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> { Ok(()) } #[inline] pub fn hidpi_factor(&self) -> f32 { 1.0 } #[inline] pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> { unimplemented!(); } } unsafe impl Send for Window {} unsafe impl Sync for Window {} impl GlContext for Window { #[inline] unsafe fn make_current(&self) -> Result<(), ContextError> { self.context.make_current() } #[inline] fn is_current(&self) -> bool { self.context.is_current() } #[inline] fn get_proc_address(&self, addr: &str) -> *const () { self.context.get_proc_address(addr) } #[inline] fn swap_buffers(&self) -> Result<(), ContextError> { self.context.swap_buffers() } #[inline] fn get_api(&self) -> Api { self.context.get_api() } #[inline] fn get_pixel_format(&self) -> PixelFormat { self.context.get_pixel_format() } } #[derive(Clone)] pub struct WindowProxy; impl WindowProxy { #[inline] pub fn wakeup_event_loop(&self) { unimplemented!() } } pub struct HeadlessContext(EglContext); impl HeadlessContext { /// See the docs in the crate root file. pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&HeadlessContext>) -> Result<HeadlessContext, CreationError> { let opengl = opengl.clone().map_sharing(|c| &c.0); let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl, egl::NativeDisplay::Android)); let context = try!(context.finish_pbuffer(dimensions)); // TODO: Ok(HeadlessContext(context)) } } unsafe impl Send for HeadlessContext {} unsafe impl Sync for HeadlessContext {} impl GlContext for HeadlessContext { #[inline] unsafe fn make_current(&self) -> Result<(), ContextError> { self.0.make_current() } #[inline] fn is_current(&self) -> bool { self.0.is_current() } #[inline] fn get_proc_address(&self, addr: &str) -> *const () { self.0.get_proc_address(addr) } #[inline] fn swap_buffers(&self) -> Result<(), ContextError> { self.0.swap_buffers() } #[inline] fn get_api(&self) -> Api { self.0.get_api() } #[inline] fn get_pixel_format(&self) -> PixelFormat { self.0.get_pixel_format() } }
{ match self.window.event_rx.try_recv() { Ok(android_glue::Event::EventMotion(motion)) => { Some(Event::Touch(Touch { phase: match motion.action { android_glue::MotionAction::Down => TouchPhase::Started, android_glue::MotionAction::Move => TouchPhase::Moved, android_glue::MotionAction::Up => TouchPhase::Ended, android_glue::MotionAction::Cancel => TouchPhase::Cancelled, }, location: (motion.x as f64, motion.y as f64), id: motion.pointer_id as u64, })) } _ => { None } } }
identifier_body
mod.rs
#![cfg(target_os = "android")] extern crate android_glue; use libc; use std::ffi::{CString}; use std::sync::mpsc::{Receiver, channel}; use {CreationError, Event, MouseCursor}; use CreationError::OsError; use events::ElementState::{Pressed, Released}; use events::{Touch, TouchPhase}; use std::collections::VecDeque; use Api; use ContextError; use CursorState; use GlAttributes; use GlContext; use GlRequest; use PixelFormat; use PixelFormatRequirements; use WindowAttributes; use native_monitor::NativeMonitorId; use api::egl; use api::egl::Context as EglContext; pub struct Window { context: EglContext, event_rx: Receiver<android_glue::Event>, } #[derive(Clone)] pub struct MonitorId; mod ffi; #[inline] pub fn get_available_monitors() -> VecDeque<MonitorId> { let mut rb = VecDeque::new(); rb.push_back(MonitorId); rb } #[inline] pub fn get_primary_monitor() -> MonitorId { MonitorId } impl MonitorId { #[inline] pub fn get_name(&self) -> Option<String> { Some("Primary".to_string()) } #[inline] pub fn get_native_identifier(&self) -> NativeMonitorId { NativeMonitorId::Unavailable } #[inline] pub fn get_dimensions(&self) -> (u32, u32) { unimplemented!() } } pub struct PollEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for PollEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { match self.window.event_rx.try_recv() { Ok(android_glue::Event::EventMotion(motion)) => { Some(Event::Touch(Touch { phase: match motion.action { android_glue::MotionAction::Down => TouchPhase::Started, android_glue::MotionAction::Move => TouchPhase::Moved, android_glue::MotionAction::Up => TouchPhase::Ended, android_glue::MotionAction::Cancel => TouchPhase::Cancelled, }, location: (motion.x as f64, motion.y as f64), id: motion.pointer_id as u64, })) } _ => { None } } } } pub struct WaitEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for WaitEventsIterator<'a> { type Item = Event; #[inline] fn next(&mut self) -> Option<Event> { loop { // calling poll_events() if let Some(ev) = self.window.poll_events().next() { return Some(ev); } // TODO: Implement a proper way of sleeping on the event queue // timer::sleep(Duration::milliseconds(16)); } } } impl Window { pub fn new(win_attribs: &WindowAttributes, pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&Window>) -> Result<Window, CreationError> { use std::{mem, ptr}; let opengl = opengl.clone().map_sharing(|w| &w.context); let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null()
let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl, egl::NativeDisplay::Android) .and_then(|p| p.finish(native_window as *const _))); let (tx, rx) = channel(); android_glue::add_sender(tx); android_glue::set_multitouch(win_attribs.multitouch); Ok(Window { context: context, event_rx: rx, }) } #[inline] pub fn is_closed(&self) -> bool { false } #[inline] pub fn set_title(&self, _: &str) { } #[inline] pub fn show(&self) { } #[inline] pub fn hide(&self) { } #[inline] pub fn get_position(&self) -> Option<(i32, i32)> { None } #[inline] pub fn set_position(&self, _x: i32, _y: i32) { } #[inline] pub fn get_inner_size(&self) -> Option<(u32, u32)> { let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null() { None } else { Some(( unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32, unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32 )) } } #[inline] pub fn get_outer_size(&self) -> Option<(u32, u32)> { self.get_inner_size() } #[inline] pub fn set_inner_size(&self, _x: u32, _y: u32) { } #[inline] pub fn create_window_proxy(&self) -> WindowProxy { WindowProxy } #[inline] pub fn poll_events(&self) -> PollEventsIterator { PollEventsIterator { window: self } } #[inline] pub fn wait_events(&self) -> WaitEventsIterator { WaitEventsIterator { window: self } } #[inline] pub fn platform_display(&self) -> *mut libc::c_void { unimplemented!(); } #[inline] pub fn platform_window(&self) -> *mut libc::c_void { unimplemented!() } #[inline] pub fn get_pixel_format(&self) -> PixelFormat { unimplemented!(); } #[inline] pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) { } #[inline] pub fn set_cursor(&self, _: MouseCursor) { } #[inline] pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> { Ok(()) } #[inline] pub fn hidpi_factor(&self) -> f32 { 1.0 } #[inline] pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> { unimplemented!(); } } unsafe impl Send for Window {} unsafe impl Sync for Window {} impl GlContext for Window { #[inline] unsafe fn make_current(&self) -> Result<(), ContextError> { self.context.make_current() } #[inline] fn is_current(&self) -> bool { self.context.is_current() } #[inline] fn get_proc_address(&self, addr: &str) -> *const () { self.context.get_proc_address(addr) } #[inline] fn swap_buffers(&self) -> Result<(), ContextError> { self.context.swap_buffers() } #[inline] fn get_api(&self) -> Api { self.context.get_api() } #[inline] fn get_pixel_format(&self) -> PixelFormat { self.context.get_pixel_format() } } #[derive(Clone)] pub struct WindowProxy; impl WindowProxy { #[inline] pub fn wakeup_event_loop(&self) { unimplemented!() } } pub struct HeadlessContext(EglContext); impl HeadlessContext { /// See the docs in the crate root file. pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&HeadlessContext>) -> Result<HeadlessContext, CreationError> { let opengl = opengl.clone().map_sharing(|c| &c.0); let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl, egl::NativeDisplay::Android)); let context = try!(context.finish_pbuffer(dimensions)); // TODO: Ok(HeadlessContext(context)) } } unsafe impl Send for HeadlessContext {} unsafe impl Sync for HeadlessContext {} impl GlContext for HeadlessContext { #[inline] unsafe fn make_current(&self) -> Result<(), ContextError> { self.0.make_current() } #[inline] fn is_current(&self) -> bool { self.0.is_current() } #[inline] fn get_proc_address(&self, addr: &str) -> *const () { self.0.get_proc_address(addr) } #[inline] fn swap_buffers(&self) -> Result<(), ContextError> { self.0.swap_buffers() } #[inline] fn get_api(&self) -> Api { self.0.get_api() } #[inline] fn get_pixel_format(&self) -> PixelFormat { self.0.get_pixel_format() } }
{ return Err(OsError(format!("Android's native window is null"))); }
conditional_block
mod.rs
#![cfg(target_os = "android")] extern crate android_glue; use libc; use std::ffi::{CString}; use std::sync::mpsc::{Receiver, channel}; use {CreationError, Event, MouseCursor}; use CreationError::OsError; use events::ElementState::{Pressed, Released}; use events::{Touch, TouchPhase}; use std::collections::VecDeque; use Api; use ContextError; use CursorState; use GlAttributes; use GlContext; use GlRequest; use PixelFormat; use PixelFormatRequirements; use WindowAttributes; use native_monitor::NativeMonitorId; use api::egl; use api::egl::Context as EglContext; pub struct Window { context: EglContext, event_rx: Receiver<android_glue::Event>, } #[derive(Clone)] pub struct MonitorId; mod ffi; #[inline] pub fn get_available_monitors() -> VecDeque<MonitorId> { let mut rb = VecDeque::new(); rb.push_back(MonitorId); rb } #[inline] pub fn get_primary_monitor() -> MonitorId { MonitorId } impl MonitorId { #[inline] pub fn get_name(&self) -> Option<String> { Some("Primary".to_string()) } #[inline] pub fn get_native_identifier(&self) -> NativeMonitorId { NativeMonitorId::Unavailable } #[inline] pub fn get_dimensions(&self) -> (u32, u32) { unimplemented!() } } pub struct PollEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for PollEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { match self.window.event_rx.try_recv() { Ok(android_glue::Event::EventMotion(motion)) => { Some(Event::Touch(Touch { phase: match motion.action { android_glue::MotionAction::Down => TouchPhase::Started, android_glue::MotionAction::Move => TouchPhase::Moved, android_glue::MotionAction::Up => TouchPhase::Ended, android_glue::MotionAction::Cancel => TouchPhase::Cancelled, }, location: (motion.x as f64, motion.y as f64), id: motion.pointer_id as u64, })) } _ => { None } } } } pub struct WaitEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for WaitEventsIterator<'a> { type Item = Event; #[inline] fn next(&mut self) -> Option<Event> { loop { // calling poll_events() if let Some(ev) = self.window.poll_events().next() { return Some(ev); } // TODO: Implement a proper way of sleeping on the event queue // timer::sleep(Duration::milliseconds(16)); } } } impl Window { pub fn new(win_attribs: &WindowAttributes, pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&Window>) -> Result<Window, CreationError> { use std::{mem, ptr}; let opengl = opengl.clone().map_sharing(|w| &w.context); let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null() { return Err(OsError(format!("Android's native window is null"))); } let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl, egl::NativeDisplay::Android) .and_then(|p| p.finish(native_window as *const _))); let (tx, rx) = channel(); android_glue::add_sender(tx); android_glue::set_multitouch(win_attribs.multitouch); Ok(Window { context: context, event_rx: rx, }) } #[inline] pub fn is_closed(&self) -> bool { false } #[inline] pub fn set_title(&self, _: &str) { } #[inline] pub fn show(&self) { } #[inline] pub fn hide(&self) { } #[inline] pub fn get_position(&self) -> Option<(i32, i32)> { None } #[inline] pub fn set_position(&self, _x: i32, _y: i32) { } #[inline] pub fn get_inner_size(&self) -> Option<(u32, u32)> { let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null() { None } else { Some(( unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32, unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32 )) } } #[inline] pub fn get_outer_size(&self) -> Option<(u32, u32)> { self.get_inner_size() } #[inline] pub fn set_inner_size(&self, _x: u32, _y: u32) { } #[inline] pub fn create_window_proxy(&self) -> WindowProxy { WindowProxy } #[inline] pub fn poll_events(&self) -> PollEventsIterator { PollEventsIterator { window: self } } #[inline] pub fn wait_events(&self) -> WaitEventsIterator { WaitEventsIterator { window: self } } #[inline] pub fn platform_display(&self) -> *mut libc::c_void { unimplemented!(); } #[inline] pub fn platform_window(&self) -> *mut libc::c_void { unimplemented!() } #[inline] pub fn get_pixel_format(&self) -> PixelFormat { unimplemented!(); } #[inline] pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) { } #[inline] pub fn set_cursor(&self, _: MouseCursor) { } #[inline] pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> { Ok(()) } #[inline] pub fn hidpi_factor(&self) -> f32 { 1.0 } #[inline] pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> { unimplemented!(); } } unsafe impl Send for Window {} unsafe impl Sync for Window {} impl GlContext for Window { #[inline] unsafe fn make_current(&self) -> Result<(), ContextError> { self.context.make_current() } #[inline] fn is_current(&self) -> bool { self.context.is_current() } #[inline] fn get_proc_address(&self, addr: &str) -> *const () { self.context.get_proc_address(addr) } #[inline] fn swap_buffers(&self) -> Result<(), ContextError> { self.context.swap_buffers() } #[inline] fn get_api(&self) -> Api { self.context.get_api() } #[inline] fn get_pixel_format(&self) -> PixelFormat { self.context.get_pixel_format() } } #[derive(Clone)] pub struct WindowProxy; impl WindowProxy { #[inline] pub fn wakeup_event_loop(&self) { unimplemented!() } } pub struct HeadlessContext(EglContext); impl HeadlessContext { /// See the docs in the crate root file. pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&HeadlessContext>) -> Result<HeadlessContext, CreationError> { let opengl = opengl.clone().map_sharing(|c| &c.0); let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl, egl::NativeDisplay::Android)); let context = try!(context.finish_pbuffer(dimensions)); // TODO: Ok(HeadlessContext(context)) } } unsafe impl Send for HeadlessContext {} unsafe impl Sync for HeadlessContext {} impl GlContext for HeadlessContext { #[inline] unsafe fn make_current(&self) -> Result<(), ContextError> { self.0.make_current() } #[inline] fn is_current(&self) -> bool { self.0.is_current() } #[inline] fn get_proc_address(&self, addr: &str) -> *const () { self.0.get_proc_address(addr) } #[inline] fn swap_buffers(&self) -> Result<(), ContextError> { self.0.swap_buffers() } #[inline] fn get_api(&self) -> Api { self.0.get_api() } #[inline] fn get_pixel_format(&self) -> PixelFormat { self.0.get_pixel_format() }
}
random_line_split
mod.rs
#![cfg(target_os = "android")] extern crate android_glue; use libc; use std::ffi::{CString}; use std::sync::mpsc::{Receiver, channel}; use {CreationError, Event, MouseCursor}; use CreationError::OsError; use events::ElementState::{Pressed, Released}; use events::{Touch, TouchPhase}; use std::collections::VecDeque; use Api; use ContextError; use CursorState; use GlAttributes; use GlContext; use GlRequest; use PixelFormat; use PixelFormatRequirements; use WindowAttributes; use native_monitor::NativeMonitorId; use api::egl; use api::egl::Context as EglContext; pub struct Window { context: EglContext, event_rx: Receiver<android_glue::Event>, } #[derive(Clone)] pub struct MonitorId; mod ffi; #[inline] pub fn get_available_monitors() -> VecDeque<MonitorId> { let mut rb = VecDeque::new(); rb.push_back(MonitorId); rb } #[inline] pub fn get_primary_monitor() -> MonitorId { MonitorId } impl MonitorId { #[inline] pub fn get_name(&self) -> Option<String> { Some("Primary".to_string()) } #[inline] pub fn get_native_identifier(&self) -> NativeMonitorId { NativeMonitorId::Unavailable } #[inline] pub fn get_dimensions(&self) -> (u32, u32) { unimplemented!() } } pub struct PollEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for PollEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { match self.window.event_rx.try_recv() { Ok(android_glue::Event::EventMotion(motion)) => { Some(Event::Touch(Touch { phase: match motion.action { android_glue::MotionAction::Down => TouchPhase::Started, android_glue::MotionAction::Move => TouchPhase::Moved, android_glue::MotionAction::Up => TouchPhase::Ended, android_glue::MotionAction::Cancel => TouchPhase::Cancelled, }, location: (motion.x as f64, motion.y as f64), id: motion.pointer_id as u64, })) } _ => { None } } } } pub struct WaitEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for WaitEventsIterator<'a> { type Item = Event; #[inline] fn next(&mut self) -> Option<Event> { loop { // calling poll_events() if let Some(ev) = self.window.poll_events().next() { return Some(ev); } // TODO: Implement a proper way of sleeping on the event queue // timer::sleep(Duration::milliseconds(16)); } } } impl Window { pub fn new(win_attribs: &WindowAttributes, pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&Window>) -> Result<Window, CreationError> { use std::{mem, ptr}; let opengl = opengl.clone().map_sharing(|w| &w.context); let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null() { return Err(OsError(format!("Android's native window is null"))); } let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl, egl::NativeDisplay::Android) .and_then(|p| p.finish(native_window as *const _))); let (tx, rx) = channel(); android_glue::add_sender(tx); android_glue::set_multitouch(win_attribs.multitouch); Ok(Window { context: context, event_rx: rx, }) } #[inline] pub fn is_closed(&self) -> bool { false } #[inline] pub fn set_title(&self, _: &str) { } #[inline] pub fn show(&self) { } #[inline] pub fn hide(&self) { } #[inline] pub fn get_position(&self) -> Option<(i32, i32)> { None } #[inline] pub fn set_position(&self, _x: i32, _y: i32) { } #[inline] pub fn get_inner_size(&self) -> Option<(u32, u32)> { let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null() { None } else { Some(( unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32, unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32 )) } } #[inline] pub fn get_outer_size(&self) -> Option<(u32, u32)> { self.get_inner_size() } #[inline] pub fn set_inner_size(&self, _x: u32, _y: u32) { } #[inline] pub fn create_window_proxy(&self) -> WindowProxy { WindowProxy } #[inline] pub fn poll_events(&self) -> PollEventsIterator { PollEventsIterator { window: self } } #[inline] pub fn wait_events(&self) -> WaitEventsIterator { WaitEventsIterator { window: self } } #[inline] pub fn platform_display(&self) -> *mut libc::c_void { unimplemented!(); } #[inline] pub fn platform_window(&self) -> *mut libc::c_void { unimplemented!() } #[inline] pub fn get_pixel_format(&self) -> PixelFormat { unimplemented!(); } #[inline] pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) { } #[inline] pub fn set_cursor(&self, _: MouseCursor) { } #[inline] pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> { Ok(()) } #[inline] pub fn hidpi_factor(&self) -> f32 { 1.0 } #[inline] pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> { unimplemented!(); } } unsafe impl Send for Window {} unsafe impl Sync for Window {} impl GlContext for Window { #[inline] unsafe fn make_current(&self) -> Result<(), ContextError> { self.context.make_current() } #[inline] fn is_current(&self) -> bool { self.context.is_current() } #[inline] fn get_proc_address(&self, addr: &str) -> *const () { self.context.get_proc_address(addr) } #[inline] fn swap_buffers(&self) -> Result<(), ContextError> { self.context.swap_buffers() } #[inline] fn get_api(&self) -> Api { self.context.get_api() } #[inline] fn
(&self) -> PixelFormat { self.context.get_pixel_format() } } #[derive(Clone)] pub struct WindowProxy; impl WindowProxy { #[inline] pub fn wakeup_event_loop(&self) { unimplemented!() } } pub struct HeadlessContext(EglContext); impl HeadlessContext { /// See the docs in the crate root file. pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&HeadlessContext>) -> Result<HeadlessContext, CreationError> { let opengl = opengl.clone().map_sharing(|c| &c.0); let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl, egl::NativeDisplay::Android)); let context = try!(context.finish_pbuffer(dimensions)); // TODO: Ok(HeadlessContext(context)) } } unsafe impl Send for HeadlessContext {} unsafe impl Sync for HeadlessContext {} impl GlContext for HeadlessContext { #[inline] unsafe fn make_current(&self) -> Result<(), ContextError> { self.0.make_current() } #[inline] fn is_current(&self) -> bool { self.0.is_current() } #[inline] fn get_proc_address(&self, addr: &str) -> *const () { self.0.get_proc_address(addr) } #[inline] fn swap_buffers(&self) -> Result<(), ContextError> { self.0.swap_buffers() } #[inline] fn get_api(&self) -> Api { self.0.get_api() } #[inline] fn get_pixel_format(&self) -> PixelFormat { self.0.get_pixel_format() } }
get_pixel_format
identifier_name
element_section.rs
/* Copyright 2018 Mozilla Foundation * * 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. */ use super::{ BinaryReader, BinaryReaderError, InitExpr, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, Type, }; #[derive(Debug, Copy, Clone)] pub struct Element<'a> { pub kind: ElementKind<'a>, pub items: ElementItems<'a>, } #[derive(Debug, Copy, Clone)] pub enum ElementKind<'a> { Passive(Type), Active { table_index: u32, init_expr: InitExpr<'a>, }, } #[derive(Debug, Copy, Clone)] pub struct ElementItems<'a> { offset: usize, data: &'a [u8], } impl<'a> ElementItems<'a> { pub fn get_items_reader<'b>(&self) -> Result<ElementItemsReader<'b>> where 'a: 'b, { ElementItemsReader::new(self.data, self.offset) } } pub struct ElementItemsReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementItemsReader<'a> { pub fn new(data: &[u8], offset: usize) -> Result<ElementItemsReader> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementItemsReader { reader, count }) } pub fn original_position(&self) -> usize { self.reader.original_position() } pub fn get_count(&self) -> u32 { self.count } pub fn
(&mut self) -> Result<u32> { self.reader.read_var_u32() } } impl<'a> IntoIterator for ElementItemsReader<'a> { type Item = Result<u32>; type IntoIter = ElementItemsIterator<'a>; fn into_iter(self) -> Self::IntoIter { let count = self.count; ElementItemsIterator { reader: self, left: count, err: false, } } } pub struct ElementItemsIterator<'a> { reader: ElementItemsReader<'a>, left: u32, err: bool, } impl<'a> Iterator for ElementItemsIterator<'a> { type Item = Result<u32>; fn next(&mut self) -> Option<Self::Item> { if self.err || self.left == 0 { return None; } let result = self.reader.read(); self.err = result.is_err(); self.left -= 1; Some(result) } fn size_hint(&self) -> (usize, Option<usize>) { let count = self.reader.get_count() as usize; (count, Some(count)) } } pub struct ElementSectionReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementSectionReader<'a> { pub fn new(data: &'a [u8], offset: usize) -> Result<ElementSectionReader<'a>> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementSectionReader { reader, count }) } pub fn original_position(&self) -> usize { self.reader.original_position() } pub fn get_count(&self) -> u32 { self.count } /// Reads content of the element section. /// /// # Examples /// ``` /// # let data: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, /// # 0x01, 0x4, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, /// # 0x05, 0x03, 0x01, 0x00, 0x02, /// # 0x09, 0x07, 0x01, 0x00, 0x41, 0x00, 0x0B, 0x01, 0x00, /// # 0x0a, 0x05, 0x01, 0x03, 0x00, 0x01, 0x0b]; /// use wasmparser::{ModuleReader, ElementKind}; ///use wasmparser::Result; /// let mut reader = ModuleReader::new(data).expect("module reader"); /// let section = reader.read().expect("type section"); /// let section = reader.read().expect("function section"); /// let section = reader.read().expect("table section"); /// let section = reader.read().expect("element section"); /// let mut element_reader = section.get_element_section_reader().expect("element section reader"); /// for _ in 0..element_reader.get_count() { /// let element = element_reader.read().expect("element"); /// println!("Element: {:?}", element); /// if let ElementKind::Active { init_expr,.. } = element.kind { /// let mut init_expr_reader = init_expr.get_binary_reader(); /// let op = init_expr_reader.read_operator().expect("op"); /// println!("Init const: {:?}", op); /// } /// let mut items_reader = element.items.get_items_reader().expect("items reader"); /// for _ in 0..items_reader.get_count() { /// let item = items_reader.read().expect("item"); /// println!(" Item: {}", item); /// } /// } /// ``` pub fn read<'b>(&mut self) -> Result<Element<'b>> where 'a: 'b, { let flags = self.reader.read_var_u32()?; let kind = if flags == 1 { let ty = self.reader.read_type()?; ElementKind::Passive(ty) } else { let table_index = match flags { 0 => 0, 2 => self.reader.read_var_u32()?, _ => { return Err(BinaryReaderError { message: "invalid flags byte in element segment", offset: self.reader.original_position() - 1, }); } }; let init_expr = { let expr_offset = self.reader.position; self.reader.skip_init_expr()?; let data = &self.reader.buffer[expr_offset..self.reader.position]; InitExpr::new(data, self.reader.original_offset + expr_offset) }; ElementKind::Active { table_index, init_expr, } }; let data_start = self.reader.position; let items_count = self.reader.read_var_u32()?; for _ in 0..items_count { self.reader.skip_var_32()?; } let data_end = self.reader.position; let items = ElementItems { offset: self.reader.original_offset + data_start, data: &self.reader.buffer[data_start..data_end], }; Ok(Element { kind, items }) } } impl<'a> SectionReader for ElementSectionReader<'a> { type Item = Element<'a>; fn read(&mut self) -> Result<Self::Item> { ElementSectionReader::read(self) } fn eof(&self) -> bool { self.reader.eof() } fn original_position(&self) -> usize { ElementSectionReader::original_position(self) } } impl<'a> SectionWithLimitedItems for ElementSectionReader<'a> { fn get_count(&self) -> u32 { ElementSectionReader::get_count(self) } } impl<'a> IntoIterator for ElementSectionReader<'a> { type Item = Result<Element<'a>>; type IntoIter = SectionIteratorLimited<ElementSectionReader<'a>>; fn into_iter(self) -> Self::IntoIter { SectionIteratorLimited::new(self) } }
read
identifier_name
element_section.rs
/* Copyright 2018 Mozilla Foundation * * 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. */ use super::{ BinaryReader, BinaryReaderError, InitExpr, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, Type, }; #[derive(Debug, Copy, Clone)] pub struct Element<'a> { pub kind: ElementKind<'a>, pub items: ElementItems<'a>, } #[derive(Debug, Copy, Clone)] pub enum ElementKind<'a> { Passive(Type), Active { table_index: u32, init_expr: InitExpr<'a>, }, } #[derive(Debug, Copy, Clone)] pub struct ElementItems<'a> { offset: usize, data: &'a [u8], } impl<'a> ElementItems<'a> { pub fn get_items_reader<'b>(&self) -> Result<ElementItemsReader<'b>> where 'a: 'b, { ElementItemsReader::new(self.data, self.offset) } } pub struct ElementItemsReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementItemsReader<'a> { pub fn new(data: &[u8], offset: usize) -> Result<ElementItemsReader> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementItemsReader { reader, count }) } pub fn original_position(&self) -> usize { self.reader.original_position() } pub fn get_count(&self) -> u32 { self.count } pub fn read(&mut self) -> Result<u32> { self.reader.read_var_u32() } } impl<'a> IntoIterator for ElementItemsReader<'a> { type Item = Result<u32>; type IntoIter = ElementItemsIterator<'a>; fn into_iter(self) -> Self::IntoIter { let count = self.count; ElementItemsIterator { reader: self, left: count, err: false, } } } pub struct ElementItemsIterator<'a> { reader: ElementItemsReader<'a>, left: u32, err: bool, } impl<'a> Iterator for ElementItemsIterator<'a> { type Item = Result<u32>; fn next(&mut self) -> Option<Self::Item> { if self.err || self.left == 0 { return None; } let result = self.reader.read(); self.err = result.is_err(); self.left -= 1; Some(result) } fn size_hint(&self) -> (usize, Option<usize>) { let count = self.reader.get_count() as usize; (count, Some(count)) } } pub struct ElementSectionReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementSectionReader<'a> { pub fn new(data: &'a [u8], offset: usize) -> Result<ElementSectionReader<'a>> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementSectionReader { reader, count }) } pub fn original_position(&self) -> usize { self.reader.original_position() } pub fn get_count(&self) -> u32 { self.count } /// Reads content of the element section. /// /// # Examples /// ``` /// # let data: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, /// # 0x01, 0x4, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, /// # 0x05, 0x03, 0x01, 0x00, 0x02, /// # 0x09, 0x07, 0x01, 0x00, 0x41, 0x00, 0x0B, 0x01, 0x00, /// # 0x0a, 0x05, 0x01, 0x03, 0x00, 0x01, 0x0b]; /// use wasmparser::{ModuleReader, ElementKind}; ///use wasmparser::Result; /// let mut reader = ModuleReader::new(data).expect("module reader"); /// let section = reader.read().expect("type section"); /// let section = reader.read().expect("function section"); /// let section = reader.read().expect("table section"); /// let section = reader.read().expect("element section"); /// let mut element_reader = section.get_element_section_reader().expect("element section reader"); /// for _ in 0..element_reader.get_count() { /// let element = element_reader.read().expect("element"); /// println!("Element: {:?}", element); /// if let ElementKind::Active { init_expr,.. } = element.kind { /// let mut init_expr_reader = init_expr.get_binary_reader(); /// let op = init_expr_reader.read_operator().expect("op"); /// println!("Init const: {:?}", op); /// } /// let mut items_reader = element.items.get_items_reader().expect("items reader"); /// for _ in 0..items_reader.get_count() { /// let item = items_reader.read().expect("item"); /// println!(" Item: {}", item); /// } /// } /// ``` pub fn read<'b>(&mut self) -> Result<Element<'b>> where 'a: 'b, { let flags = self.reader.read_var_u32()?; let kind = if flags == 1 { let ty = self.reader.read_type()?; ElementKind::Passive(ty) } else { let table_index = match flags { 0 => 0, 2 => self.reader.read_var_u32()?, _ =>
}; let init_expr = { let expr_offset = self.reader.position; self.reader.skip_init_expr()?; let data = &self.reader.buffer[expr_offset..self.reader.position]; InitExpr::new(data, self.reader.original_offset + expr_offset) }; ElementKind::Active { table_index, init_expr, } }; let data_start = self.reader.position; let items_count = self.reader.read_var_u32()?; for _ in 0..items_count { self.reader.skip_var_32()?; } let data_end = self.reader.position; let items = ElementItems { offset: self.reader.original_offset + data_start, data: &self.reader.buffer[data_start..data_end], }; Ok(Element { kind, items }) } } impl<'a> SectionReader for ElementSectionReader<'a> { type Item = Element<'a>; fn read(&mut self) -> Result<Self::Item> { ElementSectionReader::read(self) } fn eof(&self) -> bool { self.reader.eof() } fn original_position(&self) -> usize { ElementSectionReader::original_position(self) } } impl<'a> SectionWithLimitedItems for ElementSectionReader<'a> { fn get_count(&self) -> u32 { ElementSectionReader::get_count(self) } } impl<'a> IntoIterator for ElementSectionReader<'a> { type Item = Result<Element<'a>>; type IntoIter = SectionIteratorLimited<ElementSectionReader<'a>>; fn into_iter(self) -> Self::IntoIter { SectionIteratorLimited::new(self) } }
{ return Err(BinaryReaderError { message: "invalid flags byte in element segment", offset: self.reader.original_position() - 1, }); }
conditional_block
element_section.rs
/* Copyright 2018 Mozilla Foundation * * 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. */ use super::{ BinaryReader, BinaryReaderError, InitExpr, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, Type, }; #[derive(Debug, Copy, Clone)] pub struct Element<'a> { pub kind: ElementKind<'a>, pub items: ElementItems<'a>, } #[derive(Debug, Copy, Clone)] pub enum ElementKind<'a> { Passive(Type), Active { table_index: u32, init_expr: InitExpr<'a>, }, } #[derive(Debug, Copy, Clone)] pub struct ElementItems<'a> { offset: usize, data: &'a [u8], } impl<'a> ElementItems<'a> { pub fn get_items_reader<'b>(&self) -> Result<ElementItemsReader<'b>> where 'a: 'b, { ElementItemsReader::new(self.data, self.offset) } } pub struct ElementItemsReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementItemsReader<'a> { pub fn new(data: &[u8], offset: usize) -> Result<ElementItemsReader> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementItemsReader { reader, count }) } pub fn original_position(&self) -> usize { self.reader.original_position() } pub fn get_count(&self) -> u32 { self.count } pub fn read(&mut self) -> Result<u32> { self.reader.read_var_u32() } } impl<'a> IntoIterator for ElementItemsReader<'a> { type Item = Result<u32>; type IntoIter = ElementItemsIterator<'a>; fn into_iter(self) -> Self::IntoIter { let count = self.count; ElementItemsIterator { reader: self, left: count, err: false, } } } pub struct ElementItemsIterator<'a> { reader: ElementItemsReader<'a>, left: u32, err: bool, } impl<'a> Iterator for ElementItemsIterator<'a> { type Item = Result<u32>; fn next(&mut self) -> Option<Self::Item> { if self.err || self.left == 0 { return None; } let result = self.reader.read(); self.err = result.is_err(); self.left -= 1; Some(result) } fn size_hint(&self) -> (usize, Option<usize>) { let count = self.reader.get_count() as usize; (count, Some(count)) } } pub struct ElementSectionReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementSectionReader<'a> { pub fn new(data: &'a [u8], offset: usize) -> Result<ElementSectionReader<'a>> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementSectionReader { reader, count }) } pub fn original_position(&self) -> usize { self.reader.original_position() } pub fn get_count(&self) -> u32 { self.count } /// Reads content of the element section. /// /// # Examples /// ``` /// # let data: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, /// # 0x01, 0x4, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, /// # 0x05, 0x03, 0x01, 0x00, 0x02, /// # 0x09, 0x07, 0x01, 0x00, 0x41, 0x00, 0x0B, 0x01, 0x00, /// # 0x0a, 0x05, 0x01, 0x03, 0x00, 0x01, 0x0b]; /// use wasmparser::{ModuleReader, ElementKind}; ///use wasmparser::Result; /// let mut reader = ModuleReader::new(data).expect("module reader"); /// let section = reader.read().expect("type section"); /// let section = reader.read().expect("function section"); /// let section = reader.read().expect("table section"); /// let section = reader.read().expect("element section"); /// let mut element_reader = section.get_element_section_reader().expect("element section reader"); /// for _ in 0..element_reader.get_count() { /// let element = element_reader.read().expect("element"); /// println!("Element: {:?}", element); /// if let ElementKind::Active { init_expr,.. } = element.kind { /// let mut init_expr_reader = init_expr.get_binary_reader(); /// let op = init_expr_reader.read_operator().expect("op"); /// println!("Init const: {:?}", op); /// } /// let mut items_reader = element.items.get_items_reader().expect("items reader"); /// for _ in 0..items_reader.get_count() { /// let item = items_reader.read().expect("item"); /// println!(" Item: {}", item); /// } /// } /// ``` pub fn read<'b>(&mut self) -> Result<Element<'b>> where 'a: 'b, { let flags = self.reader.read_var_u32()?; let kind = if flags == 1 { let ty = self.reader.read_type()?; ElementKind::Passive(ty) } else { let table_index = match flags { 0 => 0, 2 => self.reader.read_var_u32()?, _ => { return Err(BinaryReaderError { message: "invalid flags byte in element segment", offset: self.reader.original_position() - 1, }); } }; let init_expr = { let expr_offset = self.reader.position; self.reader.skip_init_expr()?; let data = &self.reader.buffer[expr_offset..self.reader.position]; InitExpr::new(data, self.reader.original_offset + expr_offset) }; ElementKind::Active { table_index, init_expr, } }; let data_start = self.reader.position; let items_count = self.reader.read_var_u32()?; for _ in 0..items_count { self.reader.skip_var_32()?; } let data_end = self.reader.position; let items = ElementItems { offset: self.reader.original_offset + data_start, data: &self.reader.buffer[data_start..data_end], }; Ok(Element { kind, items }) } } impl<'a> SectionReader for ElementSectionReader<'a> { type Item = Element<'a>; fn read(&mut self) -> Result<Self::Item> { ElementSectionReader::read(self) } fn eof(&self) -> bool { self.reader.eof() } fn original_position(&self) -> usize { ElementSectionReader::original_position(self) } } impl<'a> SectionWithLimitedItems for ElementSectionReader<'a> { fn get_count(&self) -> u32
} impl<'a> IntoIterator for ElementSectionReader<'a> { type Item = Result<Element<'a>>; type IntoIter = SectionIteratorLimited<ElementSectionReader<'a>>; fn into_iter(self) -> Self::IntoIter { SectionIteratorLimited::new(self) } }
{ ElementSectionReader::get_count(self) }
identifier_body
element_section.rs
/* Copyright 2018 Mozilla Foundation * * 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. */ use super::{ BinaryReader, BinaryReaderError, InitExpr, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, Type, }; #[derive(Debug, Copy, Clone)] pub struct Element<'a> { pub kind: ElementKind<'a>, pub items: ElementItems<'a>, } #[derive(Debug, Copy, Clone)] pub enum ElementKind<'a> { Passive(Type), Active { table_index: u32, init_expr: InitExpr<'a>, }, } #[derive(Debug, Copy, Clone)] pub struct ElementItems<'a> { offset: usize, data: &'a [u8], } impl<'a> ElementItems<'a> { pub fn get_items_reader<'b>(&self) -> Result<ElementItemsReader<'b>> where 'a: 'b, { ElementItemsReader::new(self.data, self.offset) } } pub struct ElementItemsReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementItemsReader<'a> { pub fn new(data: &[u8], offset: usize) -> Result<ElementItemsReader> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementItemsReader { reader, count }) } pub fn original_position(&self) -> usize { self.reader.original_position() } pub fn get_count(&self) -> u32 { self.count } pub fn read(&mut self) -> Result<u32> { self.reader.read_var_u32() } } impl<'a> IntoIterator for ElementItemsReader<'a> { type Item = Result<u32>; type IntoIter = ElementItemsIterator<'a>; fn into_iter(self) -> Self::IntoIter { let count = self.count; ElementItemsIterator { reader: self, left: count, err: false, } } } pub struct ElementItemsIterator<'a> { reader: ElementItemsReader<'a>, left: u32, err: bool, } impl<'a> Iterator for ElementItemsIterator<'a> { type Item = Result<u32>; fn next(&mut self) -> Option<Self::Item> { if self.err || self.left == 0 { return None; } let result = self.reader.read(); self.err = result.is_err(); self.left -= 1; Some(result) } fn size_hint(&self) -> (usize, Option<usize>) { let count = self.reader.get_count() as usize; (count, Some(count)) } } pub struct ElementSectionReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementSectionReader<'a> { pub fn new(data: &'a [u8], offset: usize) -> Result<ElementSectionReader<'a>> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementSectionReader { reader, count }) }
pub fn get_count(&self) -> u32 { self.count } /// Reads content of the element section. /// /// # Examples /// ``` /// # let data: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, /// # 0x01, 0x4, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, /// # 0x05, 0x03, 0x01, 0x00, 0x02, /// # 0x09, 0x07, 0x01, 0x00, 0x41, 0x00, 0x0B, 0x01, 0x00, /// # 0x0a, 0x05, 0x01, 0x03, 0x00, 0x01, 0x0b]; /// use wasmparser::{ModuleReader, ElementKind}; ///use wasmparser::Result; /// let mut reader = ModuleReader::new(data).expect("module reader"); /// let section = reader.read().expect("type section"); /// let section = reader.read().expect("function section"); /// let section = reader.read().expect("table section"); /// let section = reader.read().expect("element section"); /// let mut element_reader = section.get_element_section_reader().expect("element section reader"); /// for _ in 0..element_reader.get_count() { /// let element = element_reader.read().expect("element"); /// println!("Element: {:?}", element); /// if let ElementKind::Active { init_expr,.. } = element.kind { /// let mut init_expr_reader = init_expr.get_binary_reader(); /// let op = init_expr_reader.read_operator().expect("op"); /// println!("Init const: {:?}", op); /// } /// let mut items_reader = element.items.get_items_reader().expect("items reader"); /// for _ in 0..items_reader.get_count() { /// let item = items_reader.read().expect("item"); /// println!(" Item: {}", item); /// } /// } /// ``` pub fn read<'b>(&mut self) -> Result<Element<'b>> where 'a: 'b, { let flags = self.reader.read_var_u32()?; let kind = if flags == 1 { let ty = self.reader.read_type()?; ElementKind::Passive(ty) } else { let table_index = match flags { 0 => 0, 2 => self.reader.read_var_u32()?, _ => { return Err(BinaryReaderError { message: "invalid flags byte in element segment", offset: self.reader.original_position() - 1, }); } }; let init_expr = { let expr_offset = self.reader.position; self.reader.skip_init_expr()?; let data = &self.reader.buffer[expr_offset..self.reader.position]; InitExpr::new(data, self.reader.original_offset + expr_offset) }; ElementKind::Active { table_index, init_expr, } }; let data_start = self.reader.position; let items_count = self.reader.read_var_u32()?; for _ in 0..items_count { self.reader.skip_var_32()?; } let data_end = self.reader.position; let items = ElementItems { offset: self.reader.original_offset + data_start, data: &self.reader.buffer[data_start..data_end], }; Ok(Element { kind, items }) } } impl<'a> SectionReader for ElementSectionReader<'a> { type Item = Element<'a>; fn read(&mut self) -> Result<Self::Item> { ElementSectionReader::read(self) } fn eof(&self) -> bool { self.reader.eof() } fn original_position(&self) -> usize { ElementSectionReader::original_position(self) } } impl<'a> SectionWithLimitedItems for ElementSectionReader<'a> { fn get_count(&self) -> u32 { ElementSectionReader::get_count(self) } } impl<'a> IntoIterator for ElementSectionReader<'a> { type Item = Result<Element<'a>>; type IntoIter = SectionIteratorLimited<ElementSectionReader<'a>>; fn into_iter(self) -> Self::IntoIter { SectionIteratorLimited::new(self) } }
pub fn original_position(&self) -> usize { self.reader.original_position() }
random_line_split
cat.rs
use std::str; use std::collections::HashMap; use std::io::File; use std::os; #[allow(unstable)] fn main() { let mut options = HashMap::new(); let args = os::args(); let mut files = Vec::new(); for x in range(1us, args.len()) { let s_slice: &str = args[x].as_slice(); if!s_slice.starts_with("-") { files.push(args[x].clone()); } else {
} } for x in files.iter() { let mut file = match File::open(&Path::new(x.as_bytes())) { Err(why) => panic!("{}", why), Ok(file) => file, }; let file_data = match file.read_to_end() { Ok(data) => data, Err(why) => panic!("{}", why), }; let readable_str = match str::from_utf8(file_data.as_slice()) { Err(why) => panic!("{}", why), Ok(c) => c, }; for character in readable_str.chars() { print!("{}",match character { '\n' => match options.contains_key(&("E")){ true => "$\n".to_string(), false => "\n".to_string(), }, _ => character.to_string(), }); } } }
let chars_to_trim: &[char] = &['-']; options.insert(s_slice.trim_matches(chars_to_trim), true);
random_line_split
cat.rs
use std::str; use std::collections::HashMap; use std::io::File; use std::os; #[allow(unstable)] fn
() { let mut options = HashMap::new(); let args = os::args(); let mut files = Vec::new(); for x in range(1us, args.len()) { let s_slice: &str = args[x].as_slice(); if!s_slice.starts_with("-") { files.push(args[x].clone()); } else { let chars_to_trim: &[char] = &['-']; options.insert(s_slice.trim_matches(chars_to_trim), true); } } for x in files.iter() { let mut file = match File::open(&Path::new(x.as_bytes())) { Err(why) => panic!("{}", why), Ok(file) => file, }; let file_data = match file.read_to_end() { Ok(data) => data, Err(why) => panic!("{}", why), }; let readable_str = match str::from_utf8(file_data.as_slice()) { Err(why) => panic!("{}", why), Ok(c) => c, }; for character in readable_str.chars() { print!("{}",match character { '\n' => match options.contains_key(&("E")){ true => "$\n".to_string(), false => "\n".to_string(), }, _ => character.to_string(), }); } } }
main
identifier_name
cat.rs
use std::str; use std::collections::HashMap; use std::io::File; use std::os; #[allow(unstable)] fn main()
Err(why) => panic!("{}", why), }; let readable_str = match str::from_utf8(file_data.as_slice()) { Err(why) => panic!("{}", why), Ok(c) => c, }; for character in readable_str.chars() { print!("{}",match character { '\n' => match options.contains_key(&("E")){ true => "$\n".to_string(), false => "\n".to_string(), }, _ => character.to_string(), }); } } }
{ let mut options = HashMap::new(); let args = os::args(); let mut files = Vec::new(); for x in range(1us, args.len()) { let s_slice: &str = args[x].as_slice(); if !s_slice.starts_with("-") { files.push(args[x].clone()); } else { let chars_to_trim: &[char] = &['-']; options.insert(s_slice.trim_matches(chars_to_trim), true); } } for x in files.iter() { let mut file = match File::open(&Path::new(x.as_bytes())) { Err(why) => panic!("{}", why), Ok(file) => file, }; let file_data = match file.read_to_end() { Ok(data) => data,
identifier_body
tcp-stress.rs
// run-pass // ignore-android needs extra network permissions // ignore-emscripten no threads or sockets support // ignore-netbsd system ulimit (Too many open files) // ignore-openbsd system ulimit (Too many open files) use std::io::prelude::*; use std::net::{TcpListener, TcpStream}; use std::process; use std::sync::mpsc::channel; use std::time::Duration; use std::thread::{self, Builder}; const TARGET_CNT: usize = 200;
process::exit(1); }); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); thread::spawn(move || -> () { loop { let mut stream = match listener.accept() { Ok(stream) => stream.0, Err(_) => continue, }; let _ = stream.read(&mut [0]); let _ = stream.write(&[2]); } }); let (tx, rx) = channel(); let mut spawned_cnt = 0; for _ in 0..TARGET_CNT { let tx = tx.clone(); let res = Builder::new().stack_size(64 * 1024).spawn(move|| { match TcpStream::connect(addr) { Ok(mut stream) => { let _ = stream.write(&[1]); let _ = stream.read(&mut [0]); }, Err(..) => {} } tx.send(()).unwrap(); }); if let Ok(_) = res { spawned_cnt += 1; }; } // Wait for all clients to exit, but don't wait for the server to exit. The // server just runs infinitely. drop(tx); for _ in 0..spawned_cnt { rx.recv().unwrap(); } assert_eq!(spawned_cnt, TARGET_CNT); process::exit(0); }
fn main() { // This test has a chance to time out, try to not let it time out thread::spawn(move|| -> () { thread::sleep(Duration::from_secs(30));
random_line_split
tcp-stress.rs
// run-pass // ignore-android needs extra network permissions // ignore-emscripten no threads or sockets support // ignore-netbsd system ulimit (Too many open files) // ignore-openbsd system ulimit (Too many open files) use std::io::prelude::*; use std::net::{TcpListener, TcpStream}; use std::process; use std::sync::mpsc::channel; use std::time::Duration; use std::thread::{self, Builder}; const TARGET_CNT: usize = 200; fn main()
let (tx, rx) = channel(); let mut spawned_cnt = 0; for _ in 0..TARGET_CNT { let tx = tx.clone(); let res = Builder::new().stack_size(64 * 1024).spawn(move|| { match TcpStream::connect(addr) { Ok(mut stream) => { let _ = stream.write(&[1]); let _ = stream.read(&mut [0]); }, Err(..) => {} } tx.send(()).unwrap(); }); if let Ok(_) = res { spawned_cnt += 1; }; } // Wait for all clients to exit, but don't wait for the server to exit. The // server just runs infinitely. drop(tx); for _ in 0..spawned_cnt { rx.recv().unwrap(); } assert_eq!(spawned_cnt, TARGET_CNT); process::exit(0); }
{ // This test has a chance to time out, try to not let it time out thread::spawn(move|| -> () { thread::sleep(Duration::from_secs(30)); process::exit(1); }); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); thread::spawn(move || -> () { loop { let mut stream = match listener.accept() { Ok(stream) => stream.0, Err(_) => continue, }; let _ = stream.read(&mut [0]); let _ = stream.write(&[2]); } });
identifier_body
tcp-stress.rs
// run-pass // ignore-android needs extra network permissions // ignore-emscripten no threads or sockets support // ignore-netbsd system ulimit (Too many open files) // ignore-openbsd system ulimit (Too many open files) use std::io::prelude::*; use std::net::{TcpListener, TcpStream}; use std::process; use std::sync::mpsc::channel; use std::time::Duration; use std::thread::{self, Builder}; const TARGET_CNT: usize = 200; fn main() { // This test has a chance to time out, try to not let it time out thread::spawn(move|| -> () { thread::sleep(Duration::from_secs(30)); process::exit(1); }); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); thread::spawn(move || -> () { loop { let mut stream = match listener.accept() { Ok(stream) => stream.0, Err(_) => continue, }; let _ = stream.read(&mut [0]); let _ = stream.write(&[2]); } }); let (tx, rx) = channel(); let mut spawned_cnt = 0; for _ in 0..TARGET_CNT { let tx = tx.clone(); let res = Builder::new().stack_size(64 * 1024).spawn(move|| { match TcpStream::connect(addr) { Ok(mut stream) =>
, Err(..) => {} } tx.send(()).unwrap(); }); if let Ok(_) = res { spawned_cnt += 1; }; } // Wait for all clients to exit, but don't wait for the server to exit. The // server just runs infinitely. drop(tx); for _ in 0..spawned_cnt { rx.recv().unwrap(); } assert_eq!(spawned_cnt, TARGET_CNT); process::exit(0); }
{ let _ = stream.write(&[1]); let _ = stream.read(&mut [0]); }
conditional_block
tcp-stress.rs
// run-pass // ignore-android needs extra network permissions // ignore-emscripten no threads or sockets support // ignore-netbsd system ulimit (Too many open files) // ignore-openbsd system ulimit (Too many open files) use std::io::prelude::*; use std::net::{TcpListener, TcpStream}; use std::process; use std::sync::mpsc::channel; use std::time::Duration; use std::thread::{self, Builder}; const TARGET_CNT: usize = 200; fn
() { // This test has a chance to time out, try to not let it time out thread::spawn(move|| -> () { thread::sleep(Duration::from_secs(30)); process::exit(1); }); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); thread::spawn(move || -> () { loop { let mut stream = match listener.accept() { Ok(stream) => stream.0, Err(_) => continue, }; let _ = stream.read(&mut [0]); let _ = stream.write(&[2]); } }); let (tx, rx) = channel(); let mut spawned_cnt = 0; for _ in 0..TARGET_CNT { let tx = tx.clone(); let res = Builder::new().stack_size(64 * 1024).spawn(move|| { match TcpStream::connect(addr) { Ok(mut stream) => { let _ = stream.write(&[1]); let _ = stream.read(&mut [0]); }, Err(..) => {} } tx.send(()).unwrap(); }); if let Ok(_) = res { spawned_cnt += 1; }; } // Wait for all clients to exit, but don't wait for the server to exit. The // server just runs infinitely. drop(tx); for _ in 0..spawned_cnt { rx.recv().unwrap(); } assert_eq!(spawned_cnt, TARGET_CNT); process::exit(0); }
main
identifier_name
issue-13304.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. // ignore-aarch64 use std::env; use std::io::prelude::*; use std::io; use std::process::{Command, Stdio}; use std::str; fn main() { let args: Vec<String> = env::args().collect(); if args.len() > 1 && args[1] == "child" { child(); } else { parent(); } } fn parent() { let args: Vec<String> = env::args().collect(); let mut p = Command::new(&args[0]).arg("child") .stdout(Stdio::capture()) .stdin(Stdio::capture()) .spawn().unwrap(); p.stdin.as_mut().unwrap().write_all(b"test1\ntest2\ntest3").unwrap(); let out = p.wait_with_output().unwrap(); assert!(out.status.success()); let s = str::from_utf8(&out.stdout).unwrap(); assert_eq!(s, "test1\ntest2\ntest3\n"); } fn child() { let mut stdin = io::stdin(); for line in stdin.lock().lines() { println!("{}", line.unwrap()); }
}
random_line_split
issue-13304.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. // ignore-aarch64 use std::env; use std::io::prelude::*; use std::io; use std::process::{Command, Stdio}; use std::str; fn
() { let args: Vec<String> = env::args().collect(); if args.len() > 1 && args[1] == "child" { child(); } else { parent(); } } fn parent() { let args: Vec<String> = env::args().collect(); let mut p = Command::new(&args[0]).arg("child") .stdout(Stdio::capture()) .stdin(Stdio::capture()) .spawn().unwrap(); p.stdin.as_mut().unwrap().write_all(b"test1\ntest2\ntest3").unwrap(); let out = p.wait_with_output().unwrap(); assert!(out.status.success()); let s = str::from_utf8(&out.stdout).unwrap(); assert_eq!(s, "test1\ntest2\ntest3\n"); } fn child() { let mut stdin = io::stdin(); for line in stdin.lock().lines() { println!("{}", line.unwrap()); } }
main
identifier_name
issue-13304.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. // ignore-aarch64 use std::env; use std::io::prelude::*; use std::io; use std::process::{Command, Stdio}; use std::str; fn main() { let args: Vec<String> = env::args().collect(); if args.len() > 1 && args[1] == "child" { child(); } else
} fn parent() { let args: Vec<String> = env::args().collect(); let mut p = Command::new(&args[0]).arg("child") .stdout(Stdio::capture()) .stdin(Stdio::capture()) .spawn().unwrap(); p.stdin.as_mut().unwrap().write_all(b"test1\ntest2\ntest3").unwrap(); let out = p.wait_with_output().unwrap(); assert!(out.status.success()); let s = str::from_utf8(&out.stdout).unwrap(); assert_eq!(s, "test1\ntest2\ntest3\n"); } fn child() { let mut stdin = io::stdin(); for line in stdin.lock().lines() { println!("{}", line.unwrap()); } }
{ parent(); }
conditional_block
issue-13304.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. // ignore-aarch64 use std::env; use std::io::prelude::*; use std::io; use std::process::{Command, Stdio}; use std::str; fn main()
fn parent() { let args: Vec<String> = env::args().collect(); let mut p = Command::new(&args[0]).arg("child") .stdout(Stdio::capture()) .stdin(Stdio::capture()) .spawn().unwrap(); p.stdin.as_mut().unwrap().write_all(b"test1\ntest2\ntest3").unwrap(); let out = p.wait_with_output().unwrap(); assert!(out.status.success()); let s = str::from_utf8(&out.stdout).unwrap(); assert_eq!(s, "test1\ntest2\ntest3\n"); } fn child() { let mut stdin = io::stdin(); for line in stdin.lock().lines() { println!("{}", line.unwrap()); } }
{ let args: Vec<String> = env::args().collect(); if args.len() > 1 && args[1] == "child" { child(); } else { parent(); } }
identifier_body
disallow_id_as_alias.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::WithLocation; use errors::validate; use graphql_ir::{ LinkedField, Program, ScalarField, ValidationError, ValidationMessage, ValidationResult, Validator, }; use interner::{Intern, StringKey}; use schema::{FieldID, Schema}; pub fn disallow_id_as_alias<'s>(program: &Program<'s>) -> ValidationResult<()> { let mut validator = DisallowIdAsAlias::new(program); validator.validate_program(program) } struct DisallowIdAsAlias<'s> { program: &'s Program<'s>, id_key: StringKey, } impl<'s> DisallowIdAsAlias<'s> { fn new(program: &'s Program<'s>) -> Self
} impl<'s> Validator for DisallowIdAsAlias<'s> { const NAME: &'static str = "DisallowIdAsAlias"; const VALIDATE_ARGUMENTS: bool = false; const VALIDATE_DIRECTIVES: bool = false; fn validate_linked_field(&mut self, field: &LinkedField) -> ValidationResult<()> { validate!( if let Some(alias) = field.alias { validate_field_alias( self.program.schema(), self.id_key, &alias, field.definition.item, ) } else { Ok(()) }, self.validate_selections(&field.selections) ) } fn validate_scalar_field(&mut self, field: &ScalarField) -> ValidationResult<()> { if let Some(alias) = field.alias { validate_field_alias( self.program.schema(), self.id_key, &alias, field.definition.item, ) } else { Ok(()) } } } fn validate_field_alias<'s>( schema: &'s Schema, id_key: StringKey, alias: &WithLocation<StringKey>, field: FieldID, ) -> ValidationResult<()> { if alias.item == id_key && schema.field(field).name!= id_key { Err(vec![ValidationError::new( ValidationMessage::DisallowIdAsAliasError(), vec![alias.location], )]) } else { Ok(()) } }
{ Self { program, id_key: "id".intern(), } }
identifier_body
disallow_id_as_alias.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::WithLocation; use errors::validate; use graphql_ir::{ LinkedField, Program, ScalarField, ValidationError, ValidationMessage, ValidationResult, Validator, }; use interner::{Intern, StringKey}; use schema::{FieldID, Schema}; pub fn disallow_id_as_alias<'s>(program: &Program<'s>) -> ValidationResult<()> { let mut validator = DisallowIdAsAlias::new(program); validator.validate_program(program) } struct
<'s> { program: &'s Program<'s>, id_key: StringKey, } impl<'s> DisallowIdAsAlias<'s> { fn new(program: &'s Program<'s>) -> Self { Self { program, id_key: "id".intern(), } } } impl<'s> Validator for DisallowIdAsAlias<'s> { const NAME: &'static str = "DisallowIdAsAlias"; const VALIDATE_ARGUMENTS: bool = false; const VALIDATE_DIRECTIVES: bool = false; fn validate_linked_field(&mut self, field: &LinkedField) -> ValidationResult<()> { validate!( if let Some(alias) = field.alias { validate_field_alias( self.program.schema(), self.id_key, &alias, field.definition.item, ) } else { Ok(()) }, self.validate_selections(&field.selections) ) } fn validate_scalar_field(&mut self, field: &ScalarField) -> ValidationResult<()> { if let Some(alias) = field.alias { validate_field_alias( self.program.schema(), self.id_key, &alias, field.definition.item, ) } else { Ok(()) } } } fn validate_field_alias<'s>( schema: &'s Schema, id_key: StringKey, alias: &WithLocation<StringKey>, field: FieldID, ) -> ValidationResult<()> { if alias.item == id_key && schema.field(field).name!= id_key { Err(vec![ValidationError::new( ValidationMessage::DisallowIdAsAliasError(), vec![alias.location], )]) } else { Ok(()) } }
DisallowIdAsAlias
identifier_name
disallow_id_as_alias.rs
/* * Copyright (c) Facebook, Inc. and its affiliates.
use common::WithLocation; use errors::validate; use graphql_ir::{ LinkedField, Program, ScalarField, ValidationError, ValidationMessage, ValidationResult, Validator, }; use interner::{Intern, StringKey}; use schema::{FieldID, Schema}; pub fn disallow_id_as_alias<'s>(program: &Program<'s>) -> ValidationResult<()> { let mut validator = DisallowIdAsAlias::new(program); validator.validate_program(program) } struct DisallowIdAsAlias<'s> { program: &'s Program<'s>, id_key: StringKey, } impl<'s> DisallowIdAsAlias<'s> { fn new(program: &'s Program<'s>) -> Self { Self { program, id_key: "id".intern(), } } } impl<'s> Validator for DisallowIdAsAlias<'s> { const NAME: &'static str = "DisallowIdAsAlias"; const VALIDATE_ARGUMENTS: bool = false; const VALIDATE_DIRECTIVES: bool = false; fn validate_linked_field(&mut self, field: &LinkedField) -> ValidationResult<()> { validate!( if let Some(alias) = field.alias { validate_field_alias( self.program.schema(), self.id_key, &alias, field.definition.item, ) } else { Ok(()) }, self.validate_selections(&field.selections) ) } fn validate_scalar_field(&mut self, field: &ScalarField) -> ValidationResult<()> { if let Some(alias) = field.alias { validate_field_alias( self.program.schema(), self.id_key, &alias, field.definition.item, ) } else { Ok(()) } } } fn validate_field_alias<'s>( schema: &'s Schema, id_key: StringKey, alias: &WithLocation<StringKey>, field: FieldID, ) -> ValidationResult<()> { if alias.item == id_key && schema.field(field).name!= id_key { Err(vec![ValidationError::new( ValidationMessage::DisallowIdAsAliasError(), vec![alias.location], )]) } else { Ok(()) } }
* * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */
random_line_split
disallow_id_as_alias.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::WithLocation; use errors::validate; use graphql_ir::{ LinkedField, Program, ScalarField, ValidationError, ValidationMessage, ValidationResult, Validator, }; use interner::{Intern, StringKey}; use schema::{FieldID, Schema}; pub fn disallow_id_as_alias<'s>(program: &Program<'s>) -> ValidationResult<()> { let mut validator = DisallowIdAsAlias::new(program); validator.validate_program(program) } struct DisallowIdAsAlias<'s> { program: &'s Program<'s>, id_key: StringKey, } impl<'s> DisallowIdAsAlias<'s> { fn new(program: &'s Program<'s>) -> Self { Self { program, id_key: "id".intern(), } } } impl<'s> Validator for DisallowIdAsAlias<'s> { const NAME: &'static str = "DisallowIdAsAlias"; const VALIDATE_ARGUMENTS: bool = false; const VALIDATE_DIRECTIVES: bool = false; fn validate_linked_field(&mut self, field: &LinkedField) -> ValidationResult<()> { validate!( if let Some(alias) = field.alias { validate_field_alias( self.program.schema(), self.id_key, &alias, field.definition.item, ) } else { Ok(()) }, self.validate_selections(&field.selections) ) } fn validate_scalar_field(&mut self, field: &ScalarField) -> ValidationResult<()> { if let Some(alias) = field.alias
else { Ok(()) } } } fn validate_field_alias<'s>( schema: &'s Schema, id_key: StringKey, alias: &WithLocation<StringKey>, field: FieldID, ) -> ValidationResult<()> { if alias.item == id_key && schema.field(field).name!= id_key { Err(vec![ValidationError::new( ValidationMessage::DisallowIdAsAliasError(), vec![alias.location], )]) } else { Ok(()) } }
{ validate_field_alias( self.program.schema(), self.id_key, &alias, field.definition.item, ) }
conditional_block
common.rs
// delila - a desktop version of lila. // // Copyright (C) 2017 Lakin Wecker <[email protected]> // // This program 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. // // This program 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 this program. If not, see <http://www.gnu.org/licenses/>. //------------------------------------------------------------------------------
// General types pub type UByte = u8; pub type UShort = u16; pub type UInt = u32; pub type SInt = i32; // Comparison type pub type Compare = i32; pub const LESS_THAN: Compare = -1; pub const EQUAL_TO: Compare = -1; pub const GREATER_THAN: Compare = -1; // Piece types pub type Piece = i8; // e.g ROOK or WHITE_KING pub type Color = i8; // WHITE or BLACK pub type Square = i8; // e.g. A3 pub type Direction = i8; // e.g. UP_LEFT pub type Rank = i8; // Chess board rank pub type File = i8; // Chess board file pub type LeftDiagonal = i8; // Up-left diagonals pub type RightDiagonal = i8; // Up-right diagonals // Game information types pub type GameNumber = UInt; pub type ELO = UShort; pub type ECO = UShort; // pub type typedef char ecoStringT [6]; /* "A00j1" */ pub const ECO_NONE: ECO = 0; // PIECE TYPES (without color; same value as a white piece) pub const KING: Piece = 1; pub const QUEEN: Piece = 2; pub const ROOK: Piece = 3; pub const BISHOP: Piece = 4; pub const KNIGHT: Piece = 5; pub const PAWN: Piece = 6; // PIECES: // Note that color(x) == ((x & 0x8) >> 3) and type(x) == (x & 0x7) // EMPTY is deliberately nonzero, and END_OF_BOARD is zero, so that // a board can be used as a regular 0-terminated string, provided // that board[NULL_SQUARE] == END_OF_BOARD, as it always should be. pub const EMPTY: Piece = 7; pub const END_OF_BOARD: Piece = 0; pub const WK: Piece = 1; pub const WQ: Piece = 2; pub const WR: Piece = 3; pub const WB: Piece = 4; pub const WN: Piece = 5; pub const WP: Piece = 6; pub const BK: Piece = 9; pub const BQ: Piece = 10; pub const BR: Piece = 11; pub const BB: Piece = 12; pub const BN: Piece = 13; pub const BP: Piece = 14; // Minor piece definitions, used for searching by material only: pub const WM: Piece = 16; pub const BM: Piece = 17;
// Scid common datatypes //------------------------------------------------------------------------------
random_line_split
vlq.rs
//! Implements utilities for dealing with the sourcemap vlq encoding. use crate::errors::{Error, Result}; const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const B64: [i8; 256] = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 - 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ]; /// Parses a VLQ segment into a vector. pub fn parse_vlq_segment(segment: &str) -> Result<Vec<i64>> { let mut rv = vec![]; let mut cur = 0; let mut shift = 0; for c in segment.bytes() { let enc = i64::from(B64[c as usize]); let val = enc & 0b11111; let cont = enc >> 5; cur += val.checked_shl(shift).ok_or(Error::VlqOverflow)?; shift += 5; if cont == 0 { let sign = cur & 1; cur >>= 1; if sign!= 0 { cur = -cur; } rv.push(cur); cur = 0; shift = 0; } } if cur!= 0 || shift!= 0 { Err(Error::VlqLeftover) } else if rv.is_empty() { Err(Error::VlqNoValues) } else { Ok(rv) } } /// Encodes a VLQ segment from a slice. pub fn generate_vlq_segment(nums: &[i64]) -> Result<String> { let mut rv = String::new(); for &num in nums { encode_vlq(&mut rv, num); } Ok(rv) } pub(crate) fn encode_vlq(out: &mut String, num: i64) { let mut num = if num < 0 { ((-num) << 1) + 1 } else { num << 1 }; loop { let mut digit = num & 0b11111; num >>= 5; if num > 0 { digit |= 1 << 5; } out.push(B64_CHARS[digit as usize] as char); if num == 0
} } #[test] fn test_vlq_decode() { let rv = parse_vlq_segment("AAAA").unwrap(); assert_eq!(rv, vec![0, 0, 0, 0]); let rv = parse_vlq_segment("GAAIA").unwrap(); assert_eq!(rv, vec![3, 0, 0, 4, 0]); } #[test] fn test_vlq_encode() { let rv = generate_vlq_segment(&[0, 0, 0, 0]).unwrap(); assert_eq!(rv.as_str(), "AAAA"); let rv = generate_vlq_segment(&[3, 0, 0, 4, 0]).unwrap(); assert_eq!(rv.as_str(), "GAAIA"); } #[test] fn test_overflow() { match parse_vlq_segment("00000000000000") { Err(Error::VlqOverflow) => {} e => { panic!("Unexpeted result: {:?}", e); } } }
{ break; }
conditional_block
vlq.rs
//! Implements utilities for dealing with the sourcemap vlq encoding. use crate::errors::{Error, Result}; const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const B64: [i8; 256] = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 - 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ]; /// Parses a VLQ segment into a vector. pub fn parse_vlq_segment(segment: &str) -> Result<Vec<i64>> { let mut rv = vec![]; let mut cur = 0; let mut shift = 0; for c in segment.bytes() { let enc = i64::from(B64[c as usize]); let val = enc & 0b11111; let cont = enc >> 5; cur += val.checked_shl(shift).ok_or(Error::VlqOverflow)?; shift += 5; if cont == 0 { let sign = cur & 1; cur >>= 1; if sign!= 0 { cur = -cur; } rv.push(cur); cur = 0; shift = 0; } } if cur!= 0 || shift!= 0 { Err(Error::VlqLeftover) } else if rv.is_empty() { Err(Error::VlqNoValues) } else { Ok(rv) } } /// Encodes a VLQ segment from a slice. pub fn generate_vlq_segment(nums: &[i64]) -> Result<String> { let mut rv = String::new(); for &num in nums { encode_vlq(&mut rv, num); } Ok(rv) } pub(crate) fn encode_vlq(out: &mut String, num: i64) { let mut num = if num < 0 { ((-num) << 1) + 1 } else { num << 1 }; loop { let mut digit = num & 0b11111; num >>= 5; if num > 0 { digit |= 1 << 5; } out.push(B64_CHARS[digit as usize] as char); if num == 0 { break; } } } #[test] fn test_vlq_decode()
#[test] fn test_vlq_encode() { let rv = generate_vlq_segment(&[0, 0, 0, 0]).unwrap(); assert_eq!(rv.as_str(), "AAAA"); let rv = generate_vlq_segment(&[3, 0, 0, 4, 0]).unwrap(); assert_eq!(rv.as_str(), "GAAIA"); } #[test] fn test_overflow() { match parse_vlq_segment("00000000000000") { Err(Error::VlqOverflow) => {} e => { panic!("Unexpeted result: {:?}", e); } } }
{ let rv = parse_vlq_segment("AAAA").unwrap(); assert_eq!(rv, vec![0, 0, 0, 0]); let rv = parse_vlq_segment("GAAIA").unwrap(); assert_eq!(rv, vec![3, 0, 0, 4, 0]); }
identifier_body
vlq.rs
//! Implements utilities for dealing with the sourcemap vlq encoding. use crate::errors::{Error, Result}; const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const B64: [i8; 256] = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 - 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ]; /// Parses a VLQ segment into a vector. pub fn parse_vlq_segment(segment: &str) -> Result<Vec<i64>> { let mut rv = vec![]; let mut cur = 0; let mut shift = 0; for c in segment.bytes() { let enc = i64::from(B64[c as usize]); let val = enc & 0b11111; let cont = enc >> 5; cur += val.checked_shl(shift).ok_or(Error::VlqOverflow)?; shift += 5; if cont == 0 { let sign = cur & 1; cur >>= 1; if sign!= 0 { cur = -cur; } rv.push(cur); cur = 0; shift = 0; } } if cur!= 0 || shift!= 0 { Err(Error::VlqLeftover) } else if rv.is_empty() { Err(Error::VlqNoValues) } else { Ok(rv) } } /// Encodes a VLQ segment from a slice. pub fn generate_vlq_segment(nums: &[i64]) -> Result<String> { let mut rv = String::new(); for &num in nums { encode_vlq(&mut rv, num); } Ok(rv) } pub(crate) fn encode_vlq(out: &mut String, num: i64) { let mut num = if num < 0 { ((-num) << 1) + 1 } else { num << 1 }; loop { let mut digit = num & 0b11111; num >>= 5; if num > 0 { digit |= 1 << 5; } out.push(B64_CHARS[digit as usize] as char); if num == 0 { break; } } } #[test] fn test_vlq_decode() { let rv = parse_vlq_segment("AAAA").unwrap(); assert_eq!(rv, vec![0, 0, 0, 0]); let rv = parse_vlq_segment("GAAIA").unwrap(); assert_eq!(rv, vec![3, 0, 0, 4, 0]); } #[test] fn test_vlq_encode() { let rv = generate_vlq_segment(&[0, 0, 0, 0]).unwrap(); assert_eq!(rv.as_str(), "AAAA"); let rv = generate_vlq_segment(&[3, 0, 0, 4, 0]).unwrap(); assert_eq!(rv.as_str(), "GAAIA"); } #[test] fn test_overflow() { match parse_vlq_segment("00000000000000") { Err(Error::VlqOverflow) => {} e => { panic!("Unexpeted result: {:?}", e); } } }
-1, -1, -1,
random_line_split
vlq.rs
//! Implements utilities for dealing with the sourcemap vlq encoding. use crate::errors::{Error, Result}; const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const B64: [i8; 256] = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 - 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ]; /// Parses a VLQ segment into a vector. pub fn parse_vlq_segment(segment: &str) -> Result<Vec<i64>> { let mut rv = vec![]; let mut cur = 0; let mut shift = 0; for c in segment.bytes() { let enc = i64::from(B64[c as usize]); let val = enc & 0b11111; let cont = enc >> 5; cur += val.checked_shl(shift).ok_or(Error::VlqOverflow)?; shift += 5; if cont == 0 { let sign = cur & 1; cur >>= 1; if sign!= 0 { cur = -cur; } rv.push(cur); cur = 0; shift = 0; } } if cur!= 0 || shift!= 0 { Err(Error::VlqLeftover) } else if rv.is_empty() { Err(Error::VlqNoValues) } else { Ok(rv) } } /// Encodes a VLQ segment from a slice. pub fn generate_vlq_segment(nums: &[i64]) -> Result<String> { let mut rv = String::new(); for &num in nums { encode_vlq(&mut rv, num); } Ok(rv) } pub(crate) fn encode_vlq(out: &mut String, num: i64) { let mut num = if num < 0 { ((-num) << 1) + 1 } else { num << 1 }; loop { let mut digit = num & 0b11111; num >>= 5; if num > 0 { digit |= 1 << 5; } out.push(B64_CHARS[digit as usize] as char); if num == 0 { break; } } } #[test] fn test_vlq_decode() { let rv = parse_vlq_segment("AAAA").unwrap(); assert_eq!(rv, vec![0, 0, 0, 0]); let rv = parse_vlq_segment("GAAIA").unwrap(); assert_eq!(rv, vec![3, 0, 0, 4, 0]); } #[test] fn
() { let rv = generate_vlq_segment(&[0, 0, 0, 0]).unwrap(); assert_eq!(rv.as_str(), "AAAA"); let rv = generate_vlq_segment(&[3, 0, 0, 4, 0]).unwrap(); assert_eq!(rv.as_str(), "GAAIA"); } #[test] fn test_overflow() { match parse_vlq_segment("00000000000000") { Err(Error::VlqOverflow) => {} e => { panic!("Unexpeted result: {:?}", e); } } }
test_vlq_encode
identifier_name
item_type.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. //! Item types. use std::fmt; use clean; /// Item type. Corresponds to `clean::ItemEnum` variants. /// /// The search index uses item types encoded as smaller numbers which equal to /// discriminants. JavaScript then is used to decode them into the original value. /// Consequently, every change to this type should be synchronized to /// the `itemTypes` mapping table in `static/main.js`. #[derive(Copy, PartialEq, Clone)] pub enum ItemType { Module = 0, Struct = 1, Enum = 2, Function = 3, Typedef = 4, Static = 5, Trait = 6, Impl = 7, ViewItem = 8, TyMethod = 9, Method = 10, StructField = 11, Variant = 12, // we used to have ForeignFunction and ForeignStatic. they are retired now. Macro = 15, Primitive = 16, AssociatedType = 17, Constant = 18, } impl ItemType { pub fn from_item(item: &clean::Item) -> ItemType { match item.inner { clean::ModuleItem(..) => ItemType::Module, clean::StructItem(..) => ItemType::Struct, clean::EnumItem(..) => ItemType::Enum, clean::FunctionItem(..) => ItemType::Function, clean::TypedefItem(..) => ItemType::Typedef, clean::StaticItem(..) => ItemType::Static, clean::ConstantItem(..) => ItemType::Constant, clean::TraitItem(..) => ItemType::Trait, clean::ImplItem(..) => ItemType::Impl, clean::ViewItemItem(..) => ItemType::ViewItem, clean::TyMethodItem(..) => ItemType::TyMethod, clean::MethodItem(..) => ItemType::Method, clean::StructFieldItem(..) => ItemType::StructField, clean::VariantItem(..) => ItemType::Variant, clean::ForeignFunctionItem(..) => ItemType::Function, // no ForeignFunction clean::ForeignStaticItem(..) => ItemType::Static, // no ForeignStatic clean::MacroItem(..) => ItemType::Macro, clean::PrimitiveItem(..) => ItemType::Primitive, clean::AssociatedTypeItem(..) => ItemType::AssociatedType, } } pub fn from_type_kind(kind: clean::TypeKind) -> ItemType { match kind { clean::TypeStruct => ItemType::Struct, clean::TypeEnum => ItemType::Enum, clean::TypeFunction => ItemType::Function, clean::TypeTrait => ItemType::Trait, clean::TypeModule => ItemType::Module, clean::TypeStatic => ItemType::Static, clean::TypeConst => ItemType::Constant, clean::TypeVariant => ItemType::Variant, clean::TypeTypedef => ItemType::Typedef, } } pub fn to_static_str(&self) -> &'static str
} } impl fmt::String for ItemType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_static_str().fmt(f) } }
{ match *self { ItemType::Module => "mod", ItemType::Struct => "struct", ItemType::Enum => "enum", ItemType::Function => "fn", ItemType::Typedef => "type", ItemType::Static => "static", ItemType::Trait => "trait", ItemType::Impl => "impl", ItemType::ViewItem => "viewitem", ItemType::TyMethod => "tymethod", ItemType::Method => "method", ItemType::StructField => "structfield", ItemType::Variant => "variant", ItemType::Macro => "macro", ItemType::Primitive => "primitive", ItemType::AssociatedType => "associatedtype", ItemType::Constant => "constant", }
identifier_body
item_type.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. //! Item types. use std::fmt; use clean; /// Item type. Corresponds to `clean::ItemEnum` variants. /// /// The search index uses item types encoded as smaller numbers which equal to /// discriminants. JavaScript then is used to decode them into the original value. /// Consequently, every change to this type should be synchronized to /// the `itemTypes` mapping table in `static/main.js`. #[derive(Copy, PartialEq, Clone)] pub enum ItemType { Module = 0, Struct = 1, Enum = 2, Function = 3, Typedef = 4, Static = 5, Trait = 6, Impl = 7, ViewItem = 8, TyMethod = 9, Method = 10, StructField = 11, Variant = 12, // we used to have ForeignFunction and ForeignStatic. they are retired now. Macro = 15, Primitive = 16, AssociatedType = 17, Constant = 18, } impl ItemType { pub fn from_item(item: &clean::Item) -> ItemType { match item.inner { clean::ModuleItem(..) => ItemType::Module, clean::StructItem(..) => ItemType::Struct, clean::EnumItem(..) => ItemType::Enum, clean::FunctionItem(..) => ItemType::Function, clean::TypedefItem(..) => ItemType::Typedef, clean::StaticItem(..) => ItemType::Static, clean::ConstantItem(..) => ItemType::Constant, clean::TraitItem(..) => ItemType::Trait, clean::ImplItem(..) => ItemType::Impl, clean::ViewItemItem(..) => ItemType::ViewItem,
clean::ForeignFunctionItem(..) => ItemType::Function, // no ForeignFunction clean::ForeignStaticItem(..) => ItemType::Static, // no ForeignStatic clean::MacroItem(..) => ItemType::Macro, clean::PrimitiveItem(..) => ItemType::Primitive, clean::AssociatedTypeItem(..) => ItemType::AssociatedType, } } pub fn from_type_kind(kind: clean::TypeKind) -> ItemType { match kind { clean::TypeStruct => ItemType::Struct, clean::TypeEnum => ItemType::Enum, clean::TypeFunction => ItemType::Function, clean::TypeTrait => ItemType::Trait, clean::TypeModule => ItemType::Module, clean::TypeStatic => ItemType::Static, clean::TypeConst => ItemType::Constant, clean::TypeVariant => ItemType::Variant, clean::TypeTypedef => ItemType::Typedef, } } pub fn to_static_str(&self) -> &'static str { match *self { ItemType::Module => "mod", ItemType::Struct => "struct", ItemType::Enum => "enum", ItemType::Function => "fn", ItemType::Typedef => "type", ItemType::Static => "static", ItemType::Trait => "trait", ItemType::Impl => "impl", ItemType::ViewItem => "viewitem", ItemType::TyMethod => "tymethod", ItemType::Method => "method", ItemType::StructField => "structfield", ItemType::Variant => "variant", ItemType::Macro => "macro", ItemType::Primitive => "primitive", ItemType::AssociatedType => "associatedtype", ItemType::Constant => "constant", } } } impl fmt::String for ItemType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_static_str().fmt(f) } }
clean::TyMethodItem(..) => ItemType::TyMethod, clean::MethodItem(..) => ItemType::Method, clean::StructFieldItem(..) => ItemType::StructField, clean::VariantItem(..) => ItemType::Variant,
random_line_split
item_type.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. //! Item types. use std::fmt; use clean; /// Item type. Corresponds to `clean::ItemEnum` variants. /// /// The search index uses item types encoded as smaller numbers which equal to /// discriminants. JavaScript then is used to decode them into the original value. /// Consequently, every change to this type should be synchronized to /// the `itemTypes` mapping table in `static/main.js`. #[derive(Copy, PartialEq, Clone)] pub enum ItemType { Module = 0, Struct = 1, Enum = 2, Function = 3, Typedef = 4, Static = 5, Trait = 6, Impl = 7, ViewItem = 8, TyMethod = 9, Method = 10, StructField = 11, Variant = 12, // we used to have ForeignFunction and ForeignStatic. they are retired now. Macro = 15, Primitive = 16, AssociatedType = 17, Constant = 18, } impl ItemType { pub fn from_item(item: &clean::Item) -> ItemType { match item.inner { clean::ModuleItem(..) => ItemType::Module, clean::StructItem(..) => ItemType::Struct, clean::EnumItem(..) => ItemType::Enum, clean::FunctionItem(..) => ItemType::Function, clean::TypedefItem(..) => ItemType::Typedef, clean::StaticItem(..) => ItemType::Static, clean::ConstantItem(..) => ItemType::Constant, clean::TraitItem(..) => ItemType::Trait, clean::ImplItem(..) => ItemType::Impl, clean::ViewItemItem(..) => ItemType::ViewItem, clean::TyMethodItem(..) => ItemType::TyMethod, clean::MethodItem(..) => ItemType::Method, clean::StructFieldItem(..) => ItemType::StructField, clean::VariantItem(..) => ItemType::Variant, clean::ForeignFunctionItem(..) => ItemType::Function, // no ForeignFunction clean::ForeignStaticItem(..) => ItemType::Static, // no ForeignStatic clean::MacroItem(..) => ItemType::Macro, clean::PrimitiveItem(..) => ItemType::Primitive, clean::AssociatedTypeItem(..) => ItemType::AssociatedType, } } pub fn from_type_kind(kind: clean::TypeKind) -> ItemType { match kind { clean::TypeStruct => ItemType::Struct, clean::TypeEnum => ItemType::Enum, clean::TypeFunction => ItemType::Function, clean::TypeTrait => ItemType::Trait, clean::TypeModule => ItemType::Module, clean::TypeStatic => ItemType::Static, clean::TypeConst => ItemType::Constant, clean::TypeVariant => ItemType::Variant, clean::TypeTypedef => ItemType::Typedef, } } pub fn to_static_str(&self) -> &'static str { match *self { ItemType::Module => "mod", ItemType::Struct => "struct", ItemType::Enum => "enum", ItemType::Function => "fn", ItemType::Typedef => "type", ItemType::Static => "static", ItemType::Trait => "trait", ItemType::Impl => "impl", ItemType::ViewItem => "viewitem", ItemType::TyMethod => "tymethod", ItemType::Method => "method", ItemType::StructField => "structfield", ItemType::Variant => "variant", ItemType::Macro => "macro", ItemType::Primitive => "primitive", ItemType::AssociatedType => "associatedtype", ItemType::Constant => "constant", } } } impl fmt::String for ItemType { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_static_str().fmt(f) } }
fmt
identifier_name
challenge5.rs
use super::challenge2::xor_bytes; pub fn
(data: &Vec<u8>, key: &Vec<u8>) -> Vec<u8> { xor_bytes(data, &key.iter().cloned().cycle().take(data.len()).collect()) } #[cfg(test)] mod test { use super::super::shared::bytes_to_hex_string; use super::encode; #[test] fn test_encode() { let input = b"Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal"; let output = String::from("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"); assert_eq!(bytes_to_hex_string(&encode(&input.to_vec(), &b"ICE".to_vec())), output); } }
encode
identifier_name
challenge5.rs
use super::challenge2::xor_bytes; pub fn encode(data: &Vec<u8>, key: &Vec<u8>) -> Vec<u8>
#[cfg(test)] mod test { use super::super::shared::bytes_to_hex_string; use super::encode; #[test] fn test_encode() { let input = b"Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal"; let output = String::from("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"); assert_eq!(bytes_to_hex_string(&encode(&input.to_vec(), &b"ICE".to_vec())), output); } }
{ xor_bytes(data, &key.iter().cloned().cycle().take(data.len()).collect()) }
identifier_body
challenge5.rs
use super::challenge2::xor_bytes;
#[cfg(test)] mod test { use super::super::shared::bytes_to_hex_string; use super::encode; #[test] fn test_encode() { let input = b"Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal"; let output = String::from("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"); assert_eq!(bytes_to_hex_string(&encode(&input.to_vec(), &b"ICE".to_vec())), output); } }
pub fn encode(data: &Vec<u8>, key: &Vec<u8>) -> Vec<u8> { xor_bytes(data, &key.iter().cloned().cycle().take(data.len()).collect()) }
random_line_split
input_output.rs
//! This module contains code to equate the input/output types appearing //! in the MIR with the expected input/output types from the function //! signature. This requires a bit of processing, as the expected types //! are supplied to us before normalization and may contain opaque //! `impl Trait` instances. In contrast, the input/output types found in //! the MIR (specifically, in the special local variables for the //! `RETURN_PLACE` the MIR arguments) are always fully normalized (and //! contain revealed `impl Trait` values). use crate::type_check::constraint_conversion::ConstraintConversion; use rustc_index::vec::Idx; use rustc_infer::infer::LateBoundRegionConversionTime; use rustc_middle::mir::*; use rustc_middle::ty::Ty; use rustc_span::Span; use rustc_span::DUMMY_SP; use rustc_trait_selection::traits::query::type_op::{self, TypeOp}; use rustc_trait_selection::traits::query::Fallible; use type_op::TypeOpOutput; use crate::universal_regions::UniversalRegions; use super::{Locations, TypeChecker}; impl<'a, 'tcx> TypeChecker<'a, 'tcx> { #[instrument(skip(self, body, universal_regions), level = "debug")] pub(super) fn equate_inputs_and_outputs( &mut self, body: &Body<'tcx>, universal_regions: &UniversalRegions<'tcx>, normalized_inputs_and_output: &[Ty<'tcx>], ) { let (&normalized_output_ty, normalized_input_tys) = normalized_inputs_and_output.split_last().unwrap(); debug!(?normalized_output_ty); debug!(?normalized_input_tys); let mir_def_id = body.source.def_id().expect_local(); // If the user explicitly annotated the input types, extract // those. // // e.g., `|x: FxHashMap<_, &'static u32>|...` let user_provided_sig; if!self.tcx().is_closure(mir_def_id.to_def_id()) { user_provided_sig = None; } else { let typeck_results = self.tcx().typeck(mir_def_id); user_provided_sig = typeck_results.user_provided_sigs.get(&mir_def_id.to_def_id()).map( |user_provided_poly_sig| { // Instantiate the canonicalized variables from // user-provided signature (e.g., the `_` in the code // above) with fresh variables. let poly_sig = self.instantiate_canonical_with_fresh_inference_vars( body.span, &user_provided_poly_sig, ); // Replace the bound items in the fn sig with fresh // variables, so that they represent the view from // "inside" the closure. self.infcx .replace_bound_vars_with_fresh_vars( body.span, LateBoundRegionConversionTime::FnCall, poly_sig, ) .0 }, ); } debug!(?normalized_input_tys,?body.local_decls); // Equate expected input tys with those in the MIR. for (argument_index, &normalized_input_ty) in normalized_input_tys.iter().enumerate() { if argument_index + 1 >= body.local_decls.len() { self.tcx() .sess .delay_span_bug(body.span, "found more normalized_input_ty than local_decls"); break; } // In MIR, argument N is stored in local N+1. let local = Local::new(argument_index + 1); let mir_input_ty = body.local_decls[local].ty; let mir_input_span = body.local_decls[local].source_info.span; self.equate_normalized_input_or_output( normalized_input_ty, mir_input_ty, mir_input_span, ); } if let Some(user_provided_sig) = user_provided_sig { for (argument_index, &user_provided_input_ty) in user_provided_sig.inputs().iter().enumerate() { // In MIR, closures begin an implicit `self`, so // argument N is stored in local N+2. let local = Local::new(argument_index + 2); let mir_input_ty = body.local_decls[local].ty; let mir_input_span = body.local_decls[local].source_info.span; // If the user explicitly annotated the input types, enforce those. let user_provided_input_ty = self.normalize(user_provided_input_ty, Locations::All(mir_input_span)); self.equate_normalized_input_or_output( user_provided_input_ty, mir_input_ty, mir_input_span, ); } } assert!(body.yield_ty().is_some() == universal_regions.yield_ty.is_some()); if let Some(mir_yield_ty) = body.yield_ty() { let ur_yield_ty = universal_regions.yield_ty.unwrap(); let yield_span = body.local_decls[RETURN_PLACE].source_info.span; self.equate_normalized_input_or_output(ur_yield_ty, mir_yield_ty, yield_span); } // Return types are a bit more complex. They may contain opaque `impl Trait` types. let mir_output_ty = body.local_decls[RETURN_PLACE].ty; let output_span = body.local_decls[RETURN_PLACE].source_info.span; if let Err(terr) = self.eq_opaque_type_and_type( mir_output_ty, normalized_output_ty, Locations::All(output_span), ConstraintCategory::BoringNoLocation, ) { span_mirbug!( self, Location::START, "equate_inputs_and_outputs: `{:?}=={:?}` failed with `{:?}`", normalized_output_ty, mir_output_ty, terr ); }; // If the user explicitly annotated the output types, enforce those. // Note that this only happens for closures. if let Some(user_provided_sig) = user_provided_sig { let user_provided_output_ty = user_provided_sig.output(); let user_provided_output_ty = self.normalize(user_provided_output_ty, Locations::All(output_span)); if let Err(err) = self.eq_opaque_type_and_type( mir_output_ty, user_provided_output_ty, Locations::All(output_span), ConstraintCategory::BoringNoLocation, ) { span_mirbug!( self, Location::START, "equate_inputs_and_outputs: `{:?}=={:?}` failed with `{:?}`", mir_output_ty, user_provided_output_ty, err ); } } } #[instrument(skip(self, span), level = "debug")] fn
(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, span: Span) { if let Err(_) = self.eq_types(a, b, Locations::All(span), ConstraintCategory::BoringNoLocation) { // FIXME(jackh726): This is a hack. It's somewhat like // `rustc_traits::normalize_after_erasing_regions`. Ideally, we'd // like to normalize *before* inserting into `local_decls`, but // doing so ends up causing some other trouble. let b = match self.normalize_and_add_constraints(b) { Ok(n) => n, Err(_) => { debug!("equate_inputs_and_outputs: NoSolution"); b } }; // Note: if we have to introduce new placeholders during normalization above, then we won't have // added those universes to the universe info, which we would want in `relate_tys`. if let Err(terr) = self.eq_types(a, b, Locations::All(span), ConstraintCategory::BoringNoLocation) { span_mirbug!( self, Location::START, "equate_normalized_input_or_output: `{:?}=={:?}` failed with `{:?}`", a, b, terr ); } } } pub(crate) fn normalize_and_add_constraints(&mut self, t: Ty<'tcx>) -> Fallible<Ty<'tcx>> { let TypeOpOutput { output: norm_ty, constraints,.. } = self.param_env.and(type_op::normalize::Normalize::new(t)).fully_perform(self.infcx)?; debug!("{:?} normalized to {:?}", t, norm_ty); for data in constraints.into_iter().collect::<Vec<_>>() { ConstraintConversion::new( self.infcx, &self.borrowck_context.universal_regions, &self.region_bound_pairs, Some(self.implicit_region_bound), self.param_env, Locations::All(DUMMY_SP), ConstraintCategory::Internal, &mut self.borrowck_context.constraints, ) .convert_all(&*data); } Ok(norm_ty) } }
equate_normalized_input_or_output
identifier_name
input_output.rs
//! This module contains code to equate the input/output types appearing //! in the MIR with the expected input/output types from the function //! signature. This requires a bit of processing, as the expected types //! are supplied to us before normalization and may contain opaque //! `impl Trait` instances. In contrast, the input/output types found in //! the MIR (specifically, in the special local variables for the //! `RETURN_PLACE` the MIR arguments) are always fully normalized (and //! contain revealed `impl Trait` values). use crate::type_check::constraint_conversion::ConstraintConversion; use rustc_index::vec::Idx; use rustc_infer::infer::LateBoundRegionConversionTime; use rustc_middle::mir::*; use rustc_middle::ty::Ty; use rustc_span::Span; use rustc_span::DUMMY_SP; use rustc_trait_selection::traits::query::type_op::{self, TypeOp}; use rustc_trait_selection::traits::query::Fallible; use type_op::TypeOpOutput; use crate::universal_regions::UniversalRegions; use super::{Locations, TypeChecker}; impl<'a, 'tcx> TypeChecker<'a, 'tcx> { #[instrument(skip(self, body, universal_regions), level = "debug")] pub(super) fn equate_inputs_and_outputs( &mut self, body: &Body<'tcx>, universal_regions: &UniversalRegions<'tcx>, normalized_inputs_and_output: &[Ty<'tcx>], )
// Instantiate the canonicalized variables from // user-provided signature (e.g., the `_` in the code // above) with fresh variables. let poly_sig = self.instantiate_canonical_with_fresh_inference_vars( body.span, &user_provided_poly_sig, ); // Replace the bound items in the fn sig with fresh // variables, so that they represent the view from // "inside" the closure. self.infcx .replace_bound_vars_with_fresh_vars( body.span, LateBoundRegionConversionTime::FnCall, poly_sig, ) .0 }, ); } debug!(?normalized_input_tys,?body.local_decls); // Equate expected input tys with those in the MIR. for (argument_index, &normalized_input_ty) in normalized_input_tys.iter().enumerate() { if argument_index + 1 >= body.local_decls.len() { self.tcx() .sess .delay_span_bug(body.span, "found more normalized_input_ty than local_decls"); break; } // In MIR, argument N is stored in local N+1. let local = Local::new(argument_index + 1); let mir_input_ty = body.local_decls[local].ty; let mir_input_span = body.local_decls[local].source_info.span; self.equate_normalized_input_or_output( normalized_input_ty, mir_input_ty, mir_input_span, ); } if let Some(user_provided_sig) = user_provided_sig { for (argument_index, &user_provided_input_ty) in user_provided_sig.inputs().iter().enumerate() { // In MIR, closures begin an implicit `self`, so // argument N is stored in local N+2. let local = Local::new(argument_index + 2); let mir_input_ty = body.local_decls[local].ty; let mir_input_span = body.local_decls[local].source_info.span; // If the user explicitly annotated the input types, enforce those. let user_provided_input_ty = self.normalize(user_provided_input_ty, Locations::All(mir_input_span)); self.equate_normalized_input_or_output( user_provided_input_ty, mir_input_ty, mir_input_span, ); } } assert!(body.yield_ty().is_some() == universal_regions.yield_ty.is_some()); if let Some(mir_yield_ty) = body.yield_ty() { let ur_yield_ty = universal_regions.yield_ty.unwrap(); let yield_span = body.local_decls[RETURN_PLACE].source_info.span; self.equate_normalized_input_or_output(ur_yield_ty, mir_yield_ty, yield_span); } // Return types are a bit more complex. They may contain opaque `impl Trait` types. let mir_output_ty = body.local_decls[RETURN_PLACE].ty; let output_span = body.local_decls[RETURN_PLACE].source_info.span; if let Err(terr) = self.eq_opaque_type_and_type( mir_output_ty, normalized_output_ty, Locations::All(output_span), ConstraintCategory::BoringNoLocation, ) { span_mirbug!( self, Location::START, "equate_inputs_and_outputs: `{:?}=={:?}` failed with `{:?}`", normalized_output_ty, mir_output_ty, terr ); }; // If the user explicitly annotated the output types, enforce those. // Note that this only happens for closures. if let Some(user_provided_sig) = user_provided_sig { let user_provided_output_ty = user_provided_sig.output(); let user_provided_output_ty = self.normalize(user_provided_output_ty, Locations::All(output_span)); if let Err(err) = self.eq_opaque_type_and_type( mir_output_ty, user_provided_output_ty, Locations::All(output_span), ConstraintCategory::BoringNoLocation, ) { span_mirbug!( self, Location::START, "equate_inputs_and_outputs: `{:?}=={:?}` failed with `{:?}`", mir_output_ty, user_provided_output_ty, err ); } } } #[instrument(skip(self, span), level = "debug")] fn equate_normalized_input_or_output(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, span: Span) { if let Err(_) = self.eq_types(a, b, Locations::All(span), ConstraintCategory::BoringNoLocation) { // FIXME(jackh726): This is a hack. It's somewhat like // `rustc_traits::normalize_after_erasing_regions`. Ideally, we'd // like to normalize *before* inserting into `local_decls`, but // doing so ends up causing some other trouble. let b = match self.normalize_and_add_constraints(b) { Ok(n) => n, Err(_) => { debug!("equate_inputs_and_outputs: NoSolution"); b } }; // Note: if we have to introduce new placeholders during normalization above, then we won't have // added those universes to the universe info, which we would want in `relate_tys`. if let Err(terr) = self.eq_types(a, b, Locations::All(span), ConstraintCategory::BoringNoLocation) { span_mirbug!( self, Location::START, "equate_normalized_input_or_output: `{:?}=={:?}` failed with `{:?}`", a, b, terr ); } } } pub(crate) fn normalize_and_add_constraints(&mut self, t: Ty<'tcx>) -> Fallible<Ty<'tcx>> { let TypeOpOutput { output: norm_ty, constraints,.. } = self.param_env.and(type_op::normalize::Normalize::new(t)).fully_perform(self.infcx)?; debug!("{:?} normalized to {:?}", t, norm_ty); for data in constraints.into_iter().collect::<Vec<_>>() { ConstraintConversion::new( self.infcx, &self.borrowck_context.universal_regions, &self.region_bound_pairs, Some(self.implicit_region_bound), self.param_env, Locations::All(DUMMY_SP), ConstraintCategory::Internal, &mut self.borrowck_context.constraints, ) .convert_all(&*data); } Ok(norm_ty) } }
{ let (&normalized_output_ty, normalized_input_tys) = normalized_inputs_and_output.split_last().unwrap(); debug!(?normalized_output_ty); debug!(?normalized_input_tys); let mir_def_id = body.source.def_id().expect_local(); // If the user explicitly annotated the input types, extract // those. // // e.g., `|x: FxHashMap<_, &'static u32>| ...` let user_provided_sig; if !self.tcx().is_closure(mir_def_id.to_def_id()) { user_provided_sig = None; } else { let typeck_results = self.tcx().typeck(mir_def_id); user_provided_sig = typeck_results.user_provided_sigs.get(&mir_def_id.to_def_id()).map( |user_provided_poly_sig| {
identifier_body
input_output.rs
//! This module contains code to equate the input/output types appearing //! in the MIR with the expected input/output types from the function //! signature. This requires a bit of processing, as the expected types //! are supplied to us before normalization and may contain opaque //! `impl Trait` instances. In contrast, the input/output types found in //! the MIR (specifically, in the special local variables for the //! `RETURN_PLACE` the MIR arguments) are always fully normalized (and //! contain revealed `impl Trait` values). use crate::type_check::constraint_conversion::ConstraintConversion; use rustc_index::vec::Idx; use rustc_infer::infer::LateBoundRegionConversionTime; use rustc_middle::mir::*; use rustc_middle::ty::Ty; use rustc_span::Span; use rustc_span::DUMMY_SP; use rustc_trait_selection::traits::query::type_op::{self, TypeOp}; use rustc_trait_selection::traits::query::Fallible; use type_op::TypeOpOutput; use crate::universal_regions::UniversalRegions; use super::{Locations, TypeChecker}; impl<'a, 'tcx> TypeChecker<'a, 'tcx> { #[instrument(skip(self, body, universal_regions), level = "debug")] pub(super) fn equate_inputs_and_outputs( &mut self, body: &Body<'tcx>, universal_regions: &UniversalRegions<'tcx>, normalized_inputs_and_output: &[Ty<'tcx>], ) { let (&normalized_output_ty, normalized_input_tys) = normalized_inputs_and_output.split_last().unwrap(); debug!(?normalized_output_ty); debug!(?normalized_input_tys); let mir_def_id = body.source.def_id().expect_local(); // If the user explicitly annotated the input types, extract // those. // // e.g., `|x: FxHashMap<_, &'static u32>|...` let user_provided_sig; if!self.tcx().is_closure(mir_def_id.to_def_id()) { user_provided_sig = None; } else { let typeck_results = self.tcx().typeck(mir_def_id); user_provided_sig = typeck_results.user_provided_sigs.get(&mir_def_id.to_def_id()).map( |user_provided_poly_sig| { // Instantiate the canonicalized variables from // user-provided signature (e.g., the `_` in the code // above) with fresh variables. let poly_sig = self.instantiate_canonical_with_fresh_inference_vars( body.span, &user_provided_poly_sig, ); // Replace the bound items in the fn sig with fresh // variables, so that they represent the view from // "inside" the closure. self.infcx .replace_bound_vars_with_fresh_vars( body.span, LateBoundRegionConversionTime::FnCall, poly_sig, ) .0 }, ); } debug!(?normalized_input_tys,?body.local_decls); // Equate expected input tys with those in the MIR. for (argument_index, &normalized_input_ty) in normalized_input_tys.iter().enumerate() { if argument_index + 1 >= body.local_decls.len() { self.tcx() .sess .delay_span_bug(body.span, "found more normalized_input_ty than local_decls"); break; } // In MIR, argument N is stored in local N+1. let local = Local::new(argument_index + 1); let mir_input_ty = body.local_decls[local].ty; let mir_input_span = body.local_decls[local].source_info.span; self.equate_normalized_input_or_output( normalized_input_ty, mir_input_ty, mir_input_span, ); } if let Some(user_provided_sig) = user_provided_sig { for (argument_index, &user_provided_input_ty) in user_provided_sig.inputs().iter().enumerate() { // In MIR, closures begin an implicit `self`, so // argument N is stored in local N+2. let local = Local::new(argument_index + 2); let mir_input_ty = body.local_decls[local].ty; let mir_input_span = body.local_decls[local].source_info.span; // If the user explicitly annotated the input types, enforce those. let user_provided_input_ty = self.normalize(user_provided_input_ty, Locations::All(mir_input_span)); self.equate_normalized_input_or_output( user_provided_input_ty, mir_input_ty, mir_input_span, ); } } assert!(body.yield_ty().is_some() == universal_regions.yield_ty.is_some()); if let Some(mir_yield_ty) = body.yield_ty() { let ur_yield_ty = universal_regions.yield_ty.unwrap(); let yield_span = body.local_decls[RETURN_PLACE].source_info.span; self.equate_normalized_input_or_output(ur_yield_ty, mir_yield_ty, yield_span); } // Return types are a bit more complex. They may contain opaque `impl Trait` types. let mir_output_ty = body.local_decls[RETURN_PLACE].ty; let output_span = body.local_decls[RETURN_PLACE].source_info.span; if let Err(terr) = self.eq_opaque_type_and_type( mir_output_ty, normalized_output_ty, Locations::All(output_span), ConstraintCategory::BoringNoLocation, ) { span_mirbug!( self, Location::START, "equate_inputs_and_outputs: `{:?}=={:?}` failed with `{:?}`", normalized_output_ty, mir_output_ty, terr ); };
let user_provided_output_ty = self.normalize(user_provided_output_ty, Locations::All(output_span)); if let Err(err) = self.eq_opaque_type_and_type( mir_output_ty, user_provided_output_ty, Locations::All(output_span), ConstraintCategory::BoringNoLocation, ) { span_mirbug!( self, Location::START, "equate_inputs_and_outputs: `{:?}=={:?}` failed with `{:?}`", mir_output_ty, user_provided_output_ty, err ); } } } #[instrument(skip(self, span), level = "debug")] fn equate_normalized_input_or_output(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, span: Span) { if let Err(_) = self.eq_types(a, b, Locations::All(span), ConstraintCategory::BoringNoLocation) { // FIXME(jackh726): This is a hack. It's somewhat like // `rustc_traits::normalize_after_erasing_regions`. Ideally, we'd // like to normalize *before* inserting into `local_decls`, but // doing so ends up causing some other trouble. let b = match self.normalize_and_add_constraints(b) { Ok(n) => n, Err(_) => { debug!("equate_inputs_and_outputs: NoSolution"); b } }; // Note: if we have to introduce new placeholders during normalization above, then we won't have // added those universes to the universe info, which we would want in `relate_tys`. if let Err(terr) = self.eq_types(a, b, Locations::All(span), ConstraintCategory::BoringNoLocation) { span_mirbug!( self, Location::START, "equate_normalized_input_or_output: `{:?}=={:?}` failed with `{:?}`", a, b, terr ); } } } pub(crate) fn normalize_and_add_constraints(&mut self, t: Ty<'tcx>) -> Fallible<Ty<'tcx>> { let TypeOpOutput { output: norm_ty, constraints,.. } = self.param_env.and(type_op::normalize::Normalize::new(t)).fully_perform(self.infcx)?; debug!("{:?} normalized to {:?}", t, norm_ty); for data in constraints.into_iter().collect::<Vec<_>>() { ConstraintConversion::new( self.infcx, &self.borrowck_context.universal_regions, &self.region_bound_pairs, Some(self.implicit_region_bound), self.param_env, Locations::All(DUMMY_SP), ConstraintCategory::Internal, &mut self.borrowck_context.constraints, ) .convert_all(&*data); } Ok(norm_ty) } }
// If the user explicitly annotated the output types, enforce those. // Note that this only happens for closures. if let Some(user_provided_sig) = user_provided_sig { let user_provided_output_ty = user_provided_sig.output();
random_line_split
input_output.rs
//! This module contains code to equate the input/output types appearing //! in the MIR with the expected input/output types from the function //! signature. This requires a bit of processing, as the expected types //! are supplied to us before normalization and may contain opaque //! `impl Trait` instances. In contrast, the input/output types found in //! the MIR (specifically, in the special local variables for the //! `RETURN_PLACE` the MIR arguments) are always fully normalized (and //! contain revealed `impl Trait` values). use crate::type_check::constraint_conversion::ConstraintConversion; use rustc_index::vec::Idx; use rustc_infer::infer::LateBoundRegionConversionTime; use rustc_middle::mir::*; use rustc_middle::ty::Ty; use rustc_span::Span; use rustc_span::DUMMY_SP; use rustc_trait_selection::traits::query::type_op::{self, TypeOp}; use rustc_trait_selection::traits::query::Fallible; use type_op::TypeOpOutput; use crate::universal_regions::UniversalRegions; use super::{Locations, TypeChecker}; impl<'a, 'tcx> TypeChecker<'a, 'tcx> { #[instrument(skip(self, body, universal_regions), level = "debug")] pub(super) fn equate_inputs_and_outputs( &mut self, body: &Body<'tcx>, universal_regions: &UniversalRegions<'tcx>, normalized_inputs_and_output: &[Ty<'tcx>], ) { let (&normalized_output_ty, normalized_input_tys) = normalized_inputs_and_output.split_last().unwrap(); debug!(?normalized_output_ty); debug!(?normalized_input_tys); let mir_def_id = body.source.def_id().expect_local(); // If the user explicitly annotated the input types, extract // those. // // e.g., `|x: FxHashMap<_, &'static u32>|...` let user_provided_sig; if!self.tcx().is_closure(mir_def_id.to_def_id()) { user_provided_sig = None; } else { let typeck_results = self.tcx().typeck(mir_def_id); user_provided_sig = typeck_results.user_provided_sigs.get(&mir_def_id.to_def_id()).map( |user_provided_poly_sig| { // Instantiate the canonicalized variables from // user-provided signature (e.g., the `_` in the code // above) with fresh variables. let poly_sig = self.instantiate_canonical_with_fresh_inference_vars( body.span, &user_provided_poly_sig, ); // Replace the bound items in the fn sig with fresh // variables, so that they represent the view from // "inside" the closure. self.infcx .replace_bound_vars_with_fresh_vars( body.span, LateBoundRegionConversionTime::FnCall, poly_sig, ) .0 }, ); } debug!(?normalized_input_tys,?body.local_decls); // Equate expected input tys with those in the MIR. for (argument_index, &normalized_input_ty) in normalized_input_tys.iter().enumerate() { if argument_index + 1 >= body.local_decls.len() { self.tcx() .sess .delay_span_bug(body.span, "found more normalized_input_ty than local_decls"); break; } // In MIR, argument N is stored in local N+1. let local = Local::new(argument_index + 1); let mir_input_ty = body.local_decls[local].ty; let mir_input_span = body.local_decls[local].source_info.span; self.equate_normalized_input_or_output( normalized_input_ty, mir_input_ty, mir_input_span, ); } if let Some(user_provided_sig) = user_provided_sig { for (argument_index, &user_provided_input_ty) in user_provided_sig.inputs().iter().enumerate() { // In MIR, closures begin an implicit `self`, so // argument N is stored in local N+2. let local = Local::new(argument_index + 2); let mir_input_ty = body.local_decls[local].ty; let mir_input_span = body.local_decls[local].source_info.span; // If the user explicitly annotated the input types, enforce those. let user_provided_input_ty = self.normalize(user_provided_input_ty, Locations::All(mir_input_span)); self.equate_normalized_input_or_output( user_provided_input_ty, mir_input_ty, mir_input_span, ); } } assert!(body.yield_ty().is_some() == universal_regions.yield_ty.is_some()); if let Some(mir_yield_ty) = body.yield_ty() { let ur_yield_ty = universal_regions.yield_ty.unwrap(); let yield_span = body.local_decls[RETURN_PLACE].source_info.span; self.equate_normalized_input_or_output(ur_yield_ty, mir_yield_ty, yield_span); } // Return types are a bit more complex. They may contain opaque `impl Trait` types. let mir_output_ty = body.local_decls[RETURN_PLACE].ty; let output_span = body.local_decls[RETURN_PLACE].source_info.span; if let Err(terr) = self.eq_opaque_type_and_type( mir_output_ty, normalized_output_ty, Locations::All(output_span), ConstraintCategory::BoringNoLocation, ) { span_mirbug!( self, Location::START, "equate_inputs_and_outputs: `{:?}=={:?}` failed with `{:?}`", normalized_output_ty, mir_output_ty, terr ); }; // If the user explicitly annotated the output types, enforce those. // Note that this only happens for closures. if let Some(user_provided_sig) = user_provided_sig { let user_provided_output_ty = user_provided_sig.output(); let user_provided_output_ty = self.normalize(user_provided_output_ty, Locations::All(output_span)); if let Err(err) = self.eq_opaque_type_and_type( mir_output_ty, user_provided_output_ty, Locations::All(output_span), ConstraintCategory::BoringNoLocation, ) { span_mirbug!( self, Location::START, "equate_inputs_and_outputs: `{:?}=={:?}` failed with `{:?}`", mir_output_ty, user_provided_output_ty, err ); } } } #[instrument(skip(self, span), level = "debug")] fn equate_normalized_input_or_output(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, span: Span) { if let Err(_) = self.eq_types(a, b, Locations::All(span), ConstraintCategory::BoringNoLocation)
Location::START, "equate_normalized_input_or_output: `{:?}=={:?}` failed with `{:?}`", a, b, terr ); } } } pub(crate) fn normalize_and_add_constraints(&mut self, t: Ty<'tcx>) -> Fallible<Ty<'tcx>> { let TypeOpOutput { output: norm_ty, constraints,.. } = self.param_env.and(type_op::normalize::Normalize::new(t)).fully_perform(self.infcx)?; debug!("{:?} normalized to {:?}", t, norm_ty); for data in constraints.into_iter().collect::<Vec<_>>() { ConstraintConversion::new( self.infcx, &self.borrowck_context.universal_regions, &self.region_bound_pairs, Some(self.implicit_region_bound), self.param_env, Locations::All(DUMMY_SP), ConstraintCategory::Internal, &mut self.borrowck_context.constraints, ) .convert_all(&*data); } Ok(norm_ty) } }
{ // FIXME(jackh726): This is a hack. It's somewhat like // `rustc_traits::normalize_after_erasing_regions`. Ideally, we'd // like to normalize *before* inserting into `local_decls`, but // doing so ends up causing some other trouble. let b = match self.normalize_and_add_constraints(b) { Ok(n) => n, Err(_) => { debug!("equate_inputs_and_outputs: NoSolution"); b } }; // Note: if we have to introduce new placeholders during normalization above, then we won't have // added those universes to the universe info, which we would want in `relate_tys`. if let Err(terr) = self.eq_types(a, b, Locations::All(span), ConstraintCategory::BoringNoLocation) { span_mirbug!( self,
conditional_block
cstore.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. // 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. //! the rustc crate store interface. This also includes types that //! are *mostly* used as a part of that interface, but these should //! probably get a better home if someone can find one. use hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use hir::map as hir_map; use hir::map::definitions::{DefKey, DefPathTable}; use rustc_data_structures::svh::Svh; use ty::{self, TyCtxt}; use session::{Session, CrateDisambiguator}; use session::search_paths::PathKind; use std::any::Any; use std::path::{Path, PathBuf}; use syntax::ast; use syntax::symbol::Symbol; use syntax_pos::Span; use rustc_target::spec::Target; use rustc_data_structures::sync::{self, MetadataRef, Lrc}; pub use self::NativeLibraryKind::*; // lonely orphan structs and enums looking for a better home /// Where a crate came from on the local filesystem. One of these three options /// must be non-None. #[derive(PartialEq, Clone, Debug)] pub struct CrateSource { pub dylib: Option<(PathBuf, PathKind)>, pub rlib: Option<(PathBuf, PathKind)>, pub rmeta: Option<(PathBuf, PathKind)>, } #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] pub enum DepKind { /// A dependency that is only used for its macros, none of which are visible from other crates. /// These are included in the metadata only as placeholders and are ignored when decoding. UnexportedMacrosOnly, /// A dependency that is only used for its macros. MacrosOnly, /// A dependency that is always injected into the dependency list and so /// doesn't need to be linked to an rlib, e.g., the injected allocator. Implicit, /// A dependency that is required by an rlib version of this crate. /// Ordinary `extern crate`s result in `Explicit` dependencies. Explicit, } impl DepKind { pub fn
(self) -> bool { match self { DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true, DepKind::Implicit | DepKind::Explicit => false, } } } #[derive(PartialEq, Clone, Debug)] pub enum LibSource { Some(PathBuf), MetadataOnly, None, } impl LibSource { pub fn is_some(&self) -> bool { if let LibSource::Some(_) = *self { true } else { false } } pub fn option(&self) -> Option<PathBuf> { match *self { LibSource::Some(ref p) => Some(p.clone()), LibSource::MetadataOnly | LibSource::None => None, } } } #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] pub enum NativeLibraryKind { /// native static library (.a archive) NativeStatic, /// native static library, which doesn't get bundled into.rlibs NativeStaticNobundle, /// macOS-specific NativeFramework, /// default way to specify a dynamic library NativeUnknown, } #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct NativeLibrary { pub kind: NativeLibraryKind, pub name: Option<Symbol>, pub cfg: Option<ast::MetaItem>, pub foreign_module: Option<DefId>, pub wasm_import_module: Option<Symbol>, } #[derive(Clone, Hash, RustcEncodable, RustcDecodable)] pub struct ForeignModule { pub foreign_items: Vec<DefId>, pub def_id: DefId, } #[derive(Copy, Clone, Debug)] pub struct ExternCrate { pub src: ExternCrateSource, /// span of the extern crate that caused this to be loaded pub span: Span, /// Number of links to reach the extern; /// used to select the extern with the shortest path pub path_len: usize, /// If true, then this crate is the crate named by the extern /// crate referenced above. If false, then this crate is a dep /// of the crate. pub direct: bool, } #[derive(Copy, Clone, Debug)] pub enum ExternCrateSource { /// Crate is loaded by `extern crate`. Extern( /// def_id of the item in the current crate that caused /// this crate to be loaded; note that there could be multiple /// such ids DefId, ), // Crate is loaded by `use`. Use, /// Crate is implicitly loaded by an absolute or an `extern::` path. Path, } pub struct EncodedMetadata { pub raw_data: Vec<u8> } impl EncodedMetadata { pub fn new() -> EncodedMetadata { EncodedMetadata { raw_data: Vec::new(), } } } /// The backend's way to give the crate store access to the metadata in a library. /// Note that it returns the raw metadata bytes stored in the library file, whether /// it is compressed, uncompressed, some weird mix, etc. /// rmeta files are backend independent and not handled here. /// /// At the time of this writing, there is only one backend and one way to store /// metadata in library -- this trait just serves to decouple rustc_metadata from /// the archive reader, which depends on LLVM. pub trait MetadataLoader { fn get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>; fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>; } /// A store of Rust crates, through with their metadata /// can be accessed. /// /// Note that this trait should probably not be expanding today. All new /// functionality should be driven through queries instead! /// /// If you find a method on this trait named `{name}_untracked` it signifies /// that it's *not* tracked for dependency information throughout compilation /// (it'd break incremental compilation) and should only be called pre-HIR (e.g. /// during resolve) pub trait CrateStore { fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>; // resolve fn def_key(&self, def: DefId) -> DefKey; fn def_path(&self, def: DefId) -> hir_map::DefPath; fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash; fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>; // "queries" used in resolve that aren't tracked for incremental compilation fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol; fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator; fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh; fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>; fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics; fn postorder_cnums_untracked(&self) -> Vec<CrateNum>; // This is basically a 1-based range of ints, which is a little // silly - I may fix that. fn crates_untracked(&self) -> Vec<CrateNum>; // utility functions fn encode_metadata<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> EncodedMetadata; fn metadata_encoding_version(&self) -> &[u8]; } pub type CrateStoreDyn = dyn CrateStore + sync::Sync; // This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn used_crates(tcx: TyCtxt<'_, '_, '_>, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)> { let mut libs = tcx.crates() .iter() .cloned() .filter_map(|cnum| { if tcx.dep_kind(cnum).macros_only() { return None } let source = tcx.used_crate_source(cnum); let path = match prefer { LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0), LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0), }; let path = match path { Some(p) => LibSource::Some(p), None => { if source.rmeta.is_some() { LibSource::MetadataOnly } else { LibSource::None } } }; Some((cnum, path)) }) .collect::<Vec<_>>(); let mut ordering = tcx.postorder_cnums(LOCAL_CRATE); Lrc::make_mut(&mut ordering).reverse(); libs.sort_by_cached_key(|&(a, _)| { ordering.iter().position(|x| *x == a) }); libs }
macros_only
identifier_name
cstore.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. // 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. //! the rustc crate store interface. This also includes types that //! are *mostly* used as a part of that interface, but these should //! probably get a better home if someone can find one. use hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use hir::map as hir_map; use hir::map::definitions::{DefKey, DefPathTable}; use rustc_data_structures::svh::Svh; use ty::{self, TyCtxt}; use session::{Session, CrateDisambiguator}; use session::search_paths::PathKind; use std::any::Any; use std::path::{Path, PathBuf}; use syntax::ast; use syntax::symbol::Symbol; use syntax_pos::Span; use rustc_target::spec::Target; use rustc_data_structures::sync::{self, MetadataRef, Lrc}; pub use self::NativeLibraryKind::*; // lonely orphan structs and enums looking for a better home /// Where a crate came from on the local filesystem. One of these three options /// must be non-None. #[derive(PartialEq, Clone, Debug)] pub struct CrateSource { pub dylib: Option<(PathBuf, PathKind)>, pub rlib: Option<(PathBuf, PathKind)>, pub rmeta: Option<(PathBuf, PathKind)>, } #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] pub enum DepKind { /// A dependency that is only used for its macros, none of which are visible from other crates. /// These are included in the metadata only as placeholders and are ignored when decoding. UnexportedMacrosOnly, /// A dependency that is only used for its macros. MacrosOnly, /// A dependency that is always injected into the dependency list and so /// doesn't need to be linked to an rlib, e.g., the injected allocator. Implicit, /// A dependency that is required by an rlib version of this crate. /// Ordinary `extern crate`s result in `Explicit` dependencies. Explicit, } impl DepKind { pub fn macros_only(self) -> bool { match self { DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true, DepKind::Implicit | DepKind::Explicit => false, } } } #[derive(PartialEq, Clone, Debug)] pub enum LibSource { Some(PathBuf), MetadataOnly, None, } impl LibSource { pub fn is_some(&self) -> bool { if let LibSource::Some(_) = *self { true } else { false } } pub fn option(&self) -> Option<PathBuf> { match *self { LibSource::Some(ref p) => Some(p.clone()), LibSource::MetadataOnly | LibSource::None => None, } } } #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] pub enum NativeLibraryKind { /// native static library (.a archive) NativeStatic, /// native static library, which doesn't get bundled into.rlibs NativeStaticNobundle, /// macOS-specific NativeFramework, /// default way to specify a dynamic library NativeUnknown, } #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct NativeLibrary { pub kind: NativeLibraryKind, pub name: Option<Symbol>, pub cfg: Option<ast::MetaItem>, pub foreign_module: Option<DefId>, pub wasm_import_module: Option<Symbol>, } #[derive(Clone, Hash, RustcEncodable, RustcDecodable)] pub struct ForeignModule { pub foreign_items: Vec<DefId>, pub def_id: DefId, } #[derive(Copy, Clone, Debug)] pub struct ExternCrate { pub src: ExternCrateSource, /// span of the extern crate that caused this to be loaded pub span: Span, /// Number of links to reach the extern; /// used to select the extern with the shortest path pub path_len: usize, /// If true, then this crate is the crate named by the extern /// crate referenced above. If false, then this crate is a dep /// of the crate. pub direct: bool, } #[derive(Copy, Clone, Debug)] pub enum ExternCrateSource { /// Crate is loaded by `extern crate`. Extern( /// def_id of the item in the current crate that caused /// this crate to be loaded; note that there could be multiple /// such ids DefId, ), // Crate is loaded by `use`. Use, /// Crate is implicitly loaded by an absolute or an `extern::` path. Path, } pub struct EncodedMetadata { pub raw_data: Vec<u8> } impl EncodedMetadata { pub fn new() -> EncodedMetadata { EncodedMetadata { raw_data: Vec::new(), } } } /// The backend's way to give the crate store access to the metadata in a library. /// Note that it returns the raw metadata bytes stored in the library file, whether /// it is compressed, uncompressed, some weird mix, etc. /// rmeta files are backend independent and not handled here. /// /// At the time of this writing, there is only one backend and one way to store /// metadata in library -- this trait just serves to decouple rustc_metadata from /// the archive reader, which depends on LLVM. pub trait MetadataLoader { fn get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>; fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>; } /// A store of Rust crates, through with their metadata /// can be accessed. /// /// Note that this trait should probably not be expanding today. All new /// functionality should be driven through queries instead! /// /// If you find a method on this trait named `{name}_untracked` it signifies /// that it's *not* tracked for dependency information throughout compilation /// (it'd break incremental compilation) and should only be called pre-HIR (e.g. /// during resolve) pub trait CrateStore { fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>; // resolve fn def_key(&self, def: DefId) -> DefKey; fn def_path(&self, def: DefId) -> hir_map::DefPath; fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash; fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>; // "queries" used in resolve that aren't tracked for incremental compilation fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol; fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator; fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh; fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>; fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics; fn postorder_cnums_untracked(&self) -> Vec<CrateNum>; // This is basically a 1-based range of ints, which is a little // silly - I may fix that. fn crates_untracked(&self) -> Vec<CrateNum>; // utility functions fn encode_metadata<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> EncodedMetadata; fn metadata_encoding_version(&self) -> &[u8]; } pub type CrateStoreDyn = dyn CrateStore + sync::Sync; // This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn used_crates(tcx: TyCtxt<'_, '_, '_>, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)> { let mut libs = tcx.crates() .iter() .cloned() .filter_map(|cnum| { if tcx.dep_kind(cnum).macros_only() { return None } let source = tcx.used_crate_source(cnum); let path = match prefer { LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0), LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0), }; let path = match path { Some(p) => LibSource::Some(p), None => { if source.rmeta.is_some() { LibSource::MetadataOnly } else
} }; Some((cnum, path)) }) .collect::<Vec<_>>(); let mut ordering = tcx.postorder_cnums(LOCAL_CRATE); Lrc::make_mut(&mut ordering).reverse(); libs.sort_by_cached_key(|&(a, _)| { ordering.iter().position(|x| *x == a) }); libs }
{ LibSource::None }
conditional_block
cstore.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. // 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. //! the rustc crate store interface. This also includes types that //! are *mostly* used as a part of that interface, but these should //! probably get a better home if someone can find one. use hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use hir::map as hir_map; use hir::map::definitions::{DefKey, DefPathTable}; use rustc_data_structures::svh::Svh; use ty::{self, TyCtxt}; use session::{Session, CrateDisambiguator}; use session::search_paths::PathKind; use std::any::Any; use std::path::{Path, PathBuf}; use syntax::ast; use syntax::symbol::Symbol; use syntax_pos::Span; use rustc_target::spec::Target; use rustc_data_structures::sync::{self, MetadataRef, Lrc}; pub use self::NativeLibraryKind::*; // lonely orphan structs and enums looking for a better home /// Where a crate came from on the local filesystem. One of these three options /// must be non-None. #[derive(PartialEq, Clone, Debug)] pub struct CrateSource { pub dylib: Option<(PathBuf, PathKind)>, pub rlib: Option<(PathBuf, PathKind)>, pub rmeta: Option<(PathBuf, PathKind)>, } #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] pub enum DepKind { /// A dependency that is only used for its macros, none of which are visible from other crates. /// These are included in the metadata only as placeholders and are ignored when decoding. UnexportedMacrosOnly, /// A dependency that is only used for its macros. MacrosOnly, /// A dependency that is always injected into the dependency list and so /// doesn't need to be linked to an rlib, e.g., the injected allocator. Implicit, /// A dependency that is required by an rlib version of this crate. /// Ordinary `extern crate`s result in `Explicit` dependencies. Explicit, } impl DepKind { pub fn macros_only(self) -> bool
} #[derive(PartialEq, Clone, Debug)] pub enum LibSource { Some(PathBuf), MetadataOnly, None, } impl LibSource { pub fn is_some(&self) -> bool { if let LibSource::Some(_) = *self { true } else { false } } pub fn option(&self) -> Option<PathBuf> { match *self { LibSource::Some(ref p) => Some(p.clone()), LibSource::MetadataOnly | LibSource::None => None, } } } #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] pub enum NativeLibraryKind { /// native static library (.a archive) NativeStatic, /// native static library, which doesn't get bundled into.rlibs NativeStaticNobundle, /// macOS-specific NativeFramework, /// default way to specify a dynamic library NativeUnknown, } #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct NativeLibrary { pub kind: NativeLibraryKind, pub name: Option<Symbol>, pub cfg: Option<ast::MetaItem>, pub foreign_module: Option<DefId>, pub wasm_import_module: Option<Symbol>, } #[derive(Clone, Hash, RustcEncodable, RustcDecodable)] pub struct ForeignModule { pub foreign_items: Vec<DefId>, pub def_id: DefId, } #[derive(Copy, Clone, Debug)] pub struct ExternCrate { pub src: ExternCrateSource, /// span of the extern crate that caused this to be loaded pub span: Span, /// Number of links to reach the extern; /// used to select the extern with the shortest path pub path_len: usize, /// If true, then this crate is the crate named by the extern /// crate referenced above. If false, then this crate is a dep /// of the crate. pub direct: bool, } #[derive(Copy, Clone, Debug)] pub enum ExternCrateSource { /// Crate is loaded by `extern crate`. Extern( /// def_id of the item in the current crate that caused /// this crate to be loaded; note that there could be multiple /// such ids DefId, ), // Crate is loaded by `use`. Use, /// Crate is implicitly loaded by an absolute or an `extern::` path. Path, } pub struct EncodedMetadata { pub raw_data: Vec<u8> } impl EncodedMetadata { pub fn new() -> EncodedMetadata { EncodedMetadata { raw_data: Vec::new(), } } } /// The backend's way to give the crate store access to the metadata in a library. /// Note that it returns the raw metadata bytes stored in the library file, whether /// it is compressed, uncompressed, some weird mix, etc. /// rmeta files are backend independent and not handled here. /// /// At the time of this writing, there is only one backend and one way to store /// metadata in library -- this trait just serves to decouple rustc_metadata from /// the archive reader, which depends on LLVM. pub trait MetadataLoader { fn get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>; fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>; } /// A store of Rust crates, through with their metadata /// can be accessed. /// /// Note that this trait should probably not be expanding today. All new /// functionality should be driven through queries instead! /// /// If you find a method on this trait named `{name}_untracked` it signifies /// that it's *not* tracked for dependency information throughout compilation /// (it'd break incremental compilation) and should only be called pre-HIR (e.g. /// during resolve) pub trait CrateStore { fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>; // resolve fn def_key(&self, def: DefId) -> DefKey; fn def_path(&self, def: DefId) -> hir_map::DefPath; fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash; fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>; // "queries" used in resolve that aren't tracked for incremental compilation fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol; fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator; fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh; fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>; fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics; fn postorder_cnums_untracked(&self) -> Vec<CrateNum>; // This is basically a 1-based range of ints, which is a little // silly - I may fix that. fn crates_untracked(&self) -> Vec<CrateNum>; // utility functions fn encode_metadata<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> EncodedMetadata; fn metadata_encoding_version(&self) -> &[u8]; } pub type CrateStoreDyn = dyn CrateStore + sync::Sync; // This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn used_crates(tcx: TyCtxt<'_, '_, '_>, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)> { let mut libs = tcx.crates() .iter() .cloned() .filter_map(|cnum| { if tcx.dep_kind(cnum).macros_only() { return None } let source = tcx.used_crate_source(cnum); let path = match prefer { LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0), LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0), }; let path = match path { Some(p) => LibSource::Some(p), None => { if source.rmeta.is_some() { LibSource::MetadataOnly } else { LibSource::None } } }; Some((cnum, path)) }) .collect::<Vec<_>>(); let mut ordering = tcx.postorder_cnums(LOCAL_CRATE); Lrc::make_mut(&mut ordering).reverse(); libs.sort_by_cached_key(|&(a, _)| { ordering.iter().position(|x| *x == a) }); libs }
{ match self { DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true, DepKind::Implicit | DepKind::Explicit => false, } }
identifier_body
cstore.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. // 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. //! the rustc crate store interface. This also includes types that //! are *mostly* used as a part of that interface, but these should //! probably get a better home if someone can find one. use hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use hir::map as hir_map; use hir::map::definitions::{DefKey, DefPathTable}; use rustc_data_structures::svh::Svh; use ty::{self, TyCtxt}; use session::{Session, CrateDisambiguator}; use session::search_paths::PathKind; use std::any::Any; use std::path::{Path, PathBuf}; use syntax::ast; use syntax::symbol::Symbol; use syntax_pos::Span; use rustc_target::spec::Target; use rustc_data_structures::sync::{self, MetadataRef, Lrc}; pub use self::NativeLibraryKind::*; // lonely orphan structs and enums looking for a better home /// Where a crate came from on the local filesystem. One of these three options /// must be non-None. #[derive(PartialEq, Clone, Debug)] pub struct CrateSource { pub dylib: Option<(PathBuf, PathKind)>, pub rlib: Option<(PathBuf, PathKind)>, pub rmeta: Option<(PathBuf, PathKind)>, } #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] pub enum DepKind { /// A dependency that is only used for its macros, none of which are visible from other crates. /// These are included in the metadata only as placeholders and are ignored when decoding. UnexportedMacrosOnly, /// A dependency that is only used for its macros. MacrosOnly, /// A dependency that is always injected into the dependency list and so /// doesn't need to be linked to an rlib, e.g., the injected allocator. Implicit, /// A dependency that is required by an rlib version of this crate. /// Ordinary `extern crate`s result in `Explicit` dependencies. Explicit, } impl DepKind { pub fn macros_only(self) -> bool { match self { DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true, DepKind::Implicit | DepKind::Explicit => false, } } } #[derive(PartialEq, Clone, Debug)] pub enum LibSource { Some(PathBuf), MetadataOnly, None, } impl LibSource { pub fn is_some(&self) -> bool { if let LibSource::Some(_) = *self { true } else { false } } pub fn option(&self) -> Option<PathBuf> { match *self { LibSource::Some(ref p) => Some(p.clone()), LibSource::MetadataOnly | LibSource::None => None, } } } #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] pub enum NativeLibraryKind { /// native static library (.a archive) NativeStatic, /// native static library, which doesn't get bundled into.rlibs NativeStaticNobundle, /// macOS-specific NativeFramework, /// default way to specify a dynamic library NativeUnknown, } #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct NativeLibrary { pub kind: NativeLibraryKind, pub name: Option<Symbol>, pub cfg: Option<ast::MetaItem>, pub foreign_module: Option<DefId>, pub wasm_import_module: Option<Symbol>, } #[derive(Clone, Hash, RustcEncodable, RustcDecodable)] pub struct ForeignModule { pub foreign_items: Vec<DefId>, pub def_id: DefId, } #[derive(Copy, Clone, Debug)] pub struct ExternCrate { pub src: ExternCrateSource, /// span of the extern crate that caused this to be loaded pub span: Span, /// Number of links to reach the extern; /// used to select the extern with the shortest path pub path_len: usize, /// If true, then this crate is the crate named by the extern /// crate referenced above. If false, then this crate is a dep /// of the crate. pub direct: bool, } #[derive(Copy, Clone, Debug)] pub enum ExternCrateSource { /// Crate is loaded by `extern crate`. Extern( /// def_id of the item in the current crate that caused /// this crate to be loaded; note that there could be multiple /// such ids DefId, ), // Crate is loaded by `use`. Use, /// Crate is implicitly loaded by an absolute or an `extern::` path. Path, } pub struct EncodedMetadata { pub raw_data: Vec<u8> } impl EncodedMetadata { pub fn new() -> EncodedMetadata { EncodedMetadata { raw_data: Vec::new(), } } } /// The backend's way to give the crate store access to the metadata in a library. /// Note that it returns the raw metadata bytes stored in the library file, whether /// it is compressed, uncompressed, some weird mix, etc. /// rmeta files are backend independent and not handled here. /// /// At the time of this writing, there is only one backend and one way to store /// metadata in library -- this trait just serves to decouple rustc_metadata from /// the archive reader, which depends on LLVM. pub trait MetadataLoader { fn get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>; fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>; } /// A store of Rust crates, through with their metadata /// can be accessed. /// /// Note that this trait should probably not be expanding today. All new /// functionality should be driven through queries instead! /// /// If you find a method on this trait named `{name}_untracked` it signifies /// that it's *not* tracked for dependency information throughout compilation /// (it'd break incremental compilation) and should only be called pre-HIR (e.g. /// during resolve) pub trait CrateStore { fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>; // resolve fn def_key(&self, def: DefId) -> DefKey; fn def_path(&self, def: DefId) -> hir_map::DefPath; fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash; fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>; // "queries" used in resolve that aren't tracked for incremental compilation fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol; fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator; fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh; fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>; fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics; fn postorder_cnums_untracked(&self) -> Vec<CrateNum>; // This is basically a 1-based range of ints, which is a little // silly - I may fix that. fn crates_untracked(&self) -> Vec<CrateNum>; // utility functions fn encode_metadata<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> EncodedMetadata; fn metadata_encoding_version(&self) -> &[u8]; } pub type CrateStoreDyn = dyn CrateStore + sync::Sync; // This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn used_crates(tcx: TyCtxt<'_, '_, '_>, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)> { let mut libs = tcx.crates() .iter() .cloned() .filter_map(|cnum| { if tcx.dep_kind(cnum).macros_only() { return None } let source = tcx.used_crate_source(cnum); let path = match prefer { LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0), LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0), }; let path = match path { Some(p) => LibSource::Some(p), None => { if source.rmeta.is_some() { LibSource::MetadataOnly } else {
}) .collect::<Vec<_>>(); let mut ordering = tcx.postorder_cnums(LOCAL_CRATE); Lrc::make_mut(&mut ordering).reverse(); libs.sort_by_cached_key(|&(a, _)| { ordering.iter().position(|x| *x == a) }); libs }
LibSource::None } } }; Some((cnum, path))
random_line_split
ast.rs
// Copyright 2015 Pierre Talbot (IRCAM) // 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. //! AST of a PEG expression that is shared across all the compiling steps. #![macro_use] pub use identifier::*; pub use rust::Span; use rust; use std::fmt::{Formatter, Write, Display, Error}; pub type RTy = rust::P<rust::Ty>; pub type RExpr = rust::P<rust::Expr>; pub type RItem = rust::P<rust::Item>; #[derive(Clone, Debug)] pub enum Expression_<SubExpr:?Sized>{ StrLiteral(String), // "match me" AnySingleChar, //. CharacterClass(CharacterClassExpr), // [0-9] NonTerminalSymbol(Ident), // a_rule Sequence(Vec<Box<SubExpr>>), // a_rule next_rule Choice(Vec<Box<SubExpr>>), // try_this / or_try_this_one ZeroOrMore(Box<SubExpr>), // space* OneOrMore(Box<SubExpr>), // space+ Optional(Box<SubExpr>), // space? NotPredicate(Box<SubExpr>), //!space AndPredicate(Box<SubExpr>), // &space SemanticAction(Box<SubExpr>, Ident) // rule > function } #[derive(Clone, Debug)] pub struct CharacterClassExpr { pub intervals: Vec<CharacterInterval> } impl Display for CharacterClassExpr { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { try!(formatter.write_str("[\"")); for interval in &self.intervals { try!(interval.fmt(formatter)); } formatter.write_str("\"]") } } #[derive(Clone, Debug)] pub struct CharacterInterval { pub lo: char, pub hi: char } impl Display for CharacterInterval { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { if self.lo == self.hi { formatter.write_char(self.lo) } else { formatter.write_fmt(format_args!("{}-{}", self.lo, self.hi)) } } } pub trait ItemIdent { fn ident(&self) -> Ident; } pub trait ItemSpan { fn span(&self) -> Span; } pub trait ExprNode { fn expr_node<'a>(&'a self) -> &'a Expression_<Self>; } pub trait Visitor<Node: ExprNode, R> { fn visit_expr(&mut self, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_str_literal(&mut self, _parent: &Box<Node>, _lit: &String) -> R; fn visit_non_terminal_symbol(&mut self, _parent: &Box<Node>, _id: Ident) -> R; fn visit_character(&mut self, _parent: &Box<Node>) -> R; fn visit_any_single_char(&mut self, parent: &Box<Node>) -> R { self.visit_character(parent) } fn visit_character_class(&mut self, parent: &Box<Node>, _expr: &CharacterClassExpr) -> R { self.visit_character(parent) } fn visit_sequence(&mut self, _parent: &Box<Node>, exprs: &Vec<Box<Node>>) -> R; fn visit_choice(&mut self, _parent: &Box<Node>, exprs: &Vec<Box<Node>>) -> R; fn visit_repeat(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_zero_or_more(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_repeat(parent, expr) } fn visit_one_or_more(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_repeat(parent, expr) } fn visit_optional(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_syntactic_predicate(&mut self, _parent: &Box<Node>, expr: &Box<Node>) -> R { walk_expr(self, expr) } fn visit_not_predicate(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_syntactic_predicate(parent, expr) } fn visit_and_predicate(&mut self, parent: &Box<Node>, expr: &Box<Node>) -> R { self.visit_syntactic_predicate(parent, expr) } fn visit_semantic_action(&mut self, _parent: &Box<Node>, expr: &Box<Node>, _id: Ident) -> R { walk_expr(self, expr) } } /// We need this macro for factorizing the code since we can not specialize a trait on specific type parameter (we would need to specialize on `()` here). macro_rules! unit_visitor_impl { ($Node:ty, str_literal) => (fn visit_str_literal(&mut self, _parent: &Box<$Node>, _lit: &String) -> () {}); ($Node:ty, non_terminal) => (fn visit_non_terminal_symbol(&mut self, _parent: &Box<$Node>, _id: Ident) -> () {}); ($Node:ty, character) => (fn visit_character(&mut self, _parent: &Box<$Node>) -> () {}); ($Node:ty, sequence) => ( fn visit_sequence(&mut self, _parent: &Box<$Node>, exprs: &Vec<Box<$Node>>) -> () { walk_exprs(self, exprs); } ); ($Node:ty, choice) => ( fn visit_choice(&mut self, _parent: &Box<$Node>, exprs: &Vec<Box<$Node>>) -> () { walk_exprs(self, exprs); } ); } pub fn
<Node, R, V:?Sized>(visitor: &mut V, parent: &Box<Node>) -> R where Node: ExprNode, V: Visitor<Node, R> { use self::Expression_::*; match parent.expr_node() { &StrLiteral(ref lit) => { visitor.visit_str_literal(parent, lit) } &AnySingleChar => { visitor.visit_any_single_char(parent) } &NonTerminalSymbol(id) => { visitor.visit_non_terminal_symbol(parent, id) } &Sequence(ref seq) => { visitor.visit_sequence(parent, seq) } &Choice(ref choices) => { visitor.visit_choice(parent, choices) } &ZeroOrMore(ref expr) => { visitor.visit_zero_or_more(parent, expr) } &OneOrMore(ref expr) => { visitor.visit_one_or_more(parent, expr) } &Optional(ref expr) => { visitor.visit_optional(parent, expr) } &NotPredicate(ref expr) => { visitor.visit_not_predicate(parent, expr) } &AndPredicate(ref expr) => { visitor.visit_and_predicate(parent, expr) } &CharacterClass(ref char_class) => { visitor.visit_character_class(parent, char_class) } &SemanticAction(ref expr, id) => { visitor.visit_semantic_action(parent, expr, id) } } } pub fn walk_exprs<Node, R, V:?Sized>(visitor: &mut V, exprs: &Vec<Box<Node>>) -> Vec<R> where Node: ExprNode, V: Visitor<Node, R> { exprs.iter().map(|expr| visitor.visit_expr(expr)).collect() }
walk_expr
identifier_name