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 |
---|---|---|---|---|
no_0216_combination_sum_iii.rs
|
struct Solution;
impl Solution {
pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> {
let mut ans = Vec::new();
Self::helper(k, n, 1, &mut vec![], &mut ans);
ans
}
fn helper(k: i32, n: i32, start: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if k == 0 && n == 0 && tmp.len() > 0 {
ans.push(tmp.clone());
return;
}
for i in start..=9 {
// 后面的都比 n 大了,不用再计算了。
if i > n {
break;
}
tmp.push(i);
Self::helper(k - 1, n - i, i + 1, tmp, ans);
tmp.pop();
}
}
|
use super::*;
#[test]
fn test_combination_sum3() {
assert_eq!(Solution::combination_sum3(3, 7), vec![vec![1, 2, 4]]);
assert_eq!(
Solution::combination_sum3(3, 9),
vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]]
);
}
}
|
}
#[cfg(test)]
mod tests {
|
random_line_split
|
02-temperature.rs
|
#[derive(Debug, Copy, Clone)]
struct Celcius(f32);
#[derive(Debug, Copy, Clone)]
struct Fahrenheit(f32);
#[derive(Debug, Copy, Clone)]
struct Kelvin(f32);
impl From<Celcius> for Fahrenheit {
fn from(t: Celcius) -> Fahrenheit {
Fahrenheit(9.0/5.0 * t.0 + 32.0)
}
}
impl From<Celcius> for Kelvin {
fn from(t: Celcius) -> Kelvin {
Kelvin(t.0 + 273.15)
}
}
impl From<Kelvin> for Celcius {
fn
|
(t: Kelvin) -> Celcius {
Celcius(t.0 - 273.15)
}
}
impl From<Fahrenheit> for Celcius {
fn from(t: Fahrenheit) -> Celcius {
Celcius(5.0/9.0 * (t.0 - 32.0))
}
}
impl From<Fahrenheit> for Kelvin {
fn from(t: Fahrenheit) -> Kelvin {
Kelvin::from(Celcius::from(t))
}
}
impl From<Kelvin> for Fahrenheit {
fn from(t: Kelvin) -> Fahrenheit {
Fahrenheit::from(Celcius::from(t))
}
}
fn main() {
let a = Celcius(36.6);
// Celcius -> Fahrenheit
let b = Fahrenheit::from(a);
// Fahrenheit -> Kelvin
let c = Kelvin::from(b);
// Kelvin -> Celcius
let d = Celcius::from(c);
println!("{:?} vs {:?} vs {:?} vs {:?}", a, b, c, d);
}
|
from
|
identifier_name
|
02-temperature.rs
|
#[derive(Debug, Copy, Clone)]
struct Celcius(f32);
#[derive(Debug, Copy, Clone)]
struct Fahrenheit(f32);
#[derive(Debug, Copy, Clone)]
struct Kelvin(f32);
|
}
impl From<Celcius> for Kelvin {
fn from(t: Celcius) -> Kelvin {
Kelvin(t.0 + 273.15)
}
}
impl From<Kelvin> for Celcius {
fn from(t: Kelvin) -> Celcius {
Celcius(t.0 - 273.15)
}
}
impl From<Fahrenheit> for Celcius {
fn from(t: Fahrenheit) -> Celcius {
Celcius(5.0/9.0 * (t.0 - 32.0))
}
}
impl From<Fahrenheit> for Kelvin {
fn from(t: Fahrenheit) -> Kelvin {
Kelvin::from(Celcius::from(t))
}
}
impl From<Kelvin> for Fahrenheit {
fn from(t: Kelvin) -> Fahrenheit {
Fahrenheit::from(Celcius::from(t))
}
}
fn main() {
let a = Celcius(36.6);
// Celcius -> Fahrenheit
let b = Fahrenheit::from(a);
// Fahrenheit -> Kelvin
let c = Kelvin::from(b);
// Kelvin -> Celcius
let d = Celcius::from(c);
println!("{:?} vs {:?} vs {:?} vs {:?}", a, b, c, d);
}
|
impl From<Celcius> for Fahrenheit {
fn from(t: Celcius) -> Fahrenheit {
Fahrenheit(9.0/5.0 * t.0 + 32.0)
}
|
random_line_split
|
issue-20616-8.rs
|
// We need all these 9 issue-20616-N.rs files
// because we can only catch one parsing error at a time
type Type_1_<'a, T> = &'a T;
//type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T`
//type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(`
|
//type Type_3<T> = Box<T,,>; // error: expected type, found `,`
//type Type_4<T> = Type_1_<'static,, T>; // error: expected type, found `,`
type Type_5_<'a> = Type_1_<'a, ()>;
//type Type_5<'a> = Type_1_<'a, (),,>; // error: expected type, found `,`
//type Type_6 = Type_5_<'a,,>; // error: expected type, found `,`
//type Type_7 = Box<(),,>; // error: expected type, found `,`
type Type_8<'a,,> = &'a ();
//~^ error: expected one of `#`, `>`, `const`, identifier, or lifetime, found `,`
//type Type_9<T,,> = Box<T>; // error: expected identifier, found `,`
|
random_line_split
|
|
mesh.rs
|
use std;
use cgmath::*;
use shader::*;
use device::Device;
use material::Material;
use rasterization::triangle;
use texture::TextureCube;
use std::ops::{Sub, Add, Mul};
#[derive(Copy,Clone)]
pub struct Vertex {
pub position: Vector3<f32>,
pub normal: Vector3<f32>,
pub tex: Vector2<f32>,
}
pub struct Mesh {
pub index_buffer: Vec<u32>,
pub material_id: usize,
}
pub struct Model {
pub vertex_buffer: Vec<Vertex>,
pub material_list: Vec<Material>,
pub mesh_list: Vec<Mesh>,
min: Vector3<f32>,
max: Vector3<f32>,
normalize: bool,
}
impl Vertex {
pub fn new(position: &Vector3<f32>, tex: &Vector2<f32>, normal: &Vector3<f32>) -> Vertex {
Vertex {
position: position.clone(),
normal: normal.clone(),
tex: tex.clone(),
}
}
}
impl Mesh {
pub fn new() -> Mesh {
Mesh {
index_buffer: Vec::<u32>::new(),
material_id: 0,
}
}
fn draw(&self, shader: &mut Shader,
material: &Material,
vertex_buffer: &Vec<Vertex>,
device: &mut Device) -> u32 {
shader.set_material(material);
let vertex_func = match material.texture {
None => shader.vertex_func[0],
Some(_) => shader.vertex_func[1],
};
let is_cubemap = match material.texture_cube {
None => false,
Some(_) => true,
};
shader.texture_cube = match material.texture_cube {
None => None,
Some(ref t) => Some(t.clone()),
};
let cnt_triangle = self.index_buffer.len() / 3;
for indexes in self.index_buffer.chunks(3) {
let mut points_2d: [Point3<f32>; 3] = [Point3::<f32>::new(0.0, 0.0, 0.0); 3];
|
for i in 0..3 {
let p = vertex_buffer[indexes[i] as usize];
let v = p.position;
let n = p.normal;
let t = p.tex;
shader.reset(Vector4::<f32>::new(v.x, v.y, v.z, 1.0_f32), Vector4::<f32>::new(n.x, n.y, n.z, 0.0_f32), t);
let p_screen = vertex_func(shader);
if is_cubemap {
shader.vertex_out2_base = shader.vertex_out_len;
shader.vertex_cubemap();
}
let inverse_w = 1.0_f32 / p_screen.w;
for ind in 0..shader.vertex_out_len {
vertex_out[i][ind] = shader.out_vertex_data[ind] * inverse_w;
}
tex_coord[i] = t;
points_2d[i] = Point3::new(
(p_screen.x * inverse_w + 1.0_f32) * device.x_size as f32 * 0.5_f32,
(p_screen.y * inverse_w + 1.0_f32) * device.y_size as f32 * 0.5_f32,
inverse_w);
}
let col0 = Vector3::new(points_2d[0].x, points_2d[1].x, points_2d[2].x);
let col1 = Vector3::new(points_2d[0].y, points_2d[1].y, points_2d[2].y);
let col2 = Vector3::new(1.0_f32, 1.0_f32, 1.0_f32 );
if Matrix3::from_cols(col0, col1, col2).determinant() < 0.0_f32 {
continue;
}
// calc mip level:
shader.texture = match material.texture {
Some(ref texture) => {
let ba_pixel = Vector2::new(points_2d[1].x, points_2d[1].y)
.sub(Vector2::new(points_2d[0].x, points_2d[0].y));
let ca_pixel = Vector2::new(points_2d[2].x, points_2d[2].y)
.sub(Vector2::new(points_2d[0].x, points_2d[0].y));
let tex_size = texture.size;
let ba_texel = tex_coord[1].sub(tex_coord[0]).mul(&tex_size);
let ca_texel = tex_coord[2].sub(tex_coord[0]).mul(&tex_size);
// cross product in 2d = 2 * square of triangle
let sq_pixel = ba_pixel.x * ca_pixel.y - ba_pixel.y * ca_pixel.x;
let sq_texel = ba_texel.x * ca_texel.y - ba_texel.y * ca_texel.x;
let lod = (sq_texel / sq_pixel).abs().sqrt().max(1.0_f32).log2() as usize;
Some(texture.get_surface(lod))
},
None => None,
};
triangle(&mut device.cbuffer,
&mut device.zbuffer,
device.x_size,
device.y_size,
points_2d, vertex_out, shader);
}
cnt_triangle as u32
}
}
impl Model {
pub fn new() -> Model {
Model {
vertex_buffer: Vec::<Vertex>::new(),
material_list: Vec::<Material>::new(),
mesh_list: Vec::<Mesh>::new(),
min: Vector3::new(0.0_f32, 0.0_f32, 0.0_f32),
max: Vector3::new(0.0_f32, 0.0_f32, 0.0_f32),
normalize: false,
}
}
pub fn with_normalize(min: Vector3<f32>, max: Vector3<f32>) -> Model {
Model {
vertex_buffer: Vec::<Vertex>::new(),
material_list: Vec::<Material>::new(),
mesh_list: Vec::<Mesh>::new(),
min: min,
max: max,
normalize: true,
}
}
pub fn add_texture_cube(&mut self, dir_path: &std::path::Path, image_extension: &str) -> Result<(), String> {
let texture = std::rc::Rc::new(try!(TextureCube::new(dir_path, image_extension)));
for material in &mut self.material_list {
material.add_texture_cube(texture.clone());
}
Ok(())
}
pub fn draw(&self, shader: &mut Shader, device: &mut Device) -> u32 {
let mut triangle_cnt: u32 = 0;
for mesh in &self.mesh_list {
triangle_cnt += mesh.draw(shader,
&self.material_list[mesh.material_id],
&self.vertex_buffer,
device);
}
triangle_cnt
}
pub fn to_center_matrix(&self) -> Matrix4<f32> {
if self.normalize {
let size = self.max.sub(&self.min);
let scale = Vector3::from_value(1.0_f32/(size.x.max(size.y).max(size.z)));
let center = self.min.add(&size.mul(0.5_f32));
let mat_move = Matrix4::from_translation(center.mul(-1.0_f32));
let mat_scale = Matrix4::from(Matrix3::from_diagonal(scale));
mat_scale.mul(&mat_move)
} else {
Matrix4::from_scale(1.0_f32)
}
}
}
|
let mut tex_coord: [Vector2<f32>; 3] = [Vector2::<f32>::new(0.0, 0.0); 3];
let mut vertex_out = [[0.0_f32;MAX_OUT_VALUES];3];
|
random_line_split
|
mesh.rs
|
use std;
use cgmath::*;
use shader::*;
use device::Device;
use material::Material;
use rasterization::triangle;
use texture::TextureCube;
use std::ops::{Sub, Add, Mul};
#[derive(Copy,Clone)]
pub struct Vertex {
pub position: Vector3<f32>,
pub normal: Vector3<f32>,
pub tex: Vector2<f32>,
}
pub struct Mesh {
pub index_buffer: Vec<u32>,
pub material_id: usize,
}
pub struct Model {
pub vertex_buffer: Vec<Vertex>,
pub material_list: Vec<Material>,
pub mesh_list: Vec<Mesh>,
min: Vector3<f32>,
max: Vector3<f32>,
normalize: bool,
}
impl Vertex {
pub fn new(position: &Vector3<f32>, tex: &Vector2<f32>, normal: &Vector3<f32>) -> Vertex {
Vertex {
position: position.clone(),
normal: normal.clone(),
tex: tex.clone(),
}
}
}
impl Mesh {
pub fn new() -> Mesh {
Mesh {
index_buffer: Vec::<u32>::new(),
material_id: 0,
}
}
fn draw(&self, shader: &mut Shader,
material: &Material,
vertex_buffer: &Vec<Vertex>,
device: &mut Device) -> u32 {
shader.set_material(material);
let vertex_func = match material.texture {
None => shader.vertex_func[0],
Some(_) => shader.vertex_func[1],
};
let is_cubemap = match material.texture_cube {
None => false,
Some(_) => true,
};
shader.texture_cube = match material.texture_cube {
None => None,
Some(ref t) => Some(t.clone()),
};
let cnt_triangle = self.index_buffer.len() / 3;
for indexes in self.index_buffer.chunks(3) {
let mut points_2d: [Point3<f32>; 3] = [Point3::<f32>::new(0.0, 0.0, 0.0); 3];
let mut tex_coord: [Vector2<f32>; 3] = [Vector2::<f32>::new(0.0, 0.0); 3];
let mut vertex_out = [[0.0_f32;MAX_OUT_VALUES];3];
for i in 0..3 {
let p = vertex_buffer[indexes[i] as usize];
let v = p.position;
let n = p.normal;
let t = p.tex;
shader.reset(Vector4::<f32>::new(v.x, v.y, v.z, 1.0_f32), Vector4::<f32>::new(n.x, n.y, n.z, 0.0_f32), t);
let p_screen = vertex_func(shader);
if is_cubemap {
shader.vertex_out2_base = shader.vertex_out_len;
shader.vertex_cubemap();
}
let inverse_w = 1.0_f32 / p_screen.w;
for ind in 0..shader.vertex_out_len {
vertex_out[i][ind] = shader.out_vertex_data[ind] * inverse_w;
}
tex_coord[i] = t;
points_2d[i] = Point3::new(
(p_screen.x * inverse_w + 1.0_f32) * device.x_size as f32 * 0.5_f32,
(p_screen.y * inverse_w + 1.0_f32) * device.y_size as f32 * 0.5_f32,
inverse_w);
}
let col0 = Vector3::new(points_2d[0].x, points_2d[1].x, points_2d[2].x);
let col1 = Vector3::new(points_2d[0].y, points_2d[1].y, points_2d[2].y);
let col2 = Vector3::new(1.0_f32, 1.0_f32, 1.0_f32 );
if Matrix3::from_cols(col0, col1, col2).determinant() < 0.0_f32 {
continue;
}
// calc mip level:
shader.texture = match material.texture {
Some(ref texture) => {
let ba_pixel = Vector2::new(points_2d[1].x, points_2d[1].y)
.sub(Vector2::new(points_2d[0].x, points_2d[0].y));
let ca_pixel = Vector2::new(points_2d[2].x, points_2d[2].y)
.sub(Vector2::new(points_2d[0].x, points_2d[0].y));
let tex_size = texture.size;
let ba_texel = tex_coord[1].sub(tex_coord[0]).mul(&tex_size);
let ca_texel = tex_coord[2].sub(tex_coord[0]).mul(&tex_size);
// cross product in 2d = 2 * square of triangle
let sq_pixel = ba_pixel.x * ca_pixel.y - ba_pixel.y * ca_pixel.x;
let sq_texel = ba_texel.x * ca_texel.y - ba_texel.y * ca_texel.x;
let lod = (sq_texel / sq_pixel).abs().sqrt().max(1.0_f32).log2() as usize;
Some(texture.get_surface(lod))
},
None => None,
};
triangle(&mut device.cbuffer,
&mut device.zbuffer,
device.x_size,
device.y_size,
points_2d, vertex_out, shader);
}
cnt_triangle as u32
}
}
impl Model {
pub fn
|
() -> Model {
Model {
vertex_buffer: Vec::<Vertex>::new(),
material_list: Vec::<Material>::new(),
mesh_list: Vec::<Mesh>::new(),
min: Vector3::new(0.0_f32, 0.0_f32, 0.0_f32),
max: Vector3::new(0.0_f32, 0.0_f32, 0.0_f32),
normalize: false,
}
}
pub fn with_normalize(min: Vector3<f32>, max: Vector3<f32>) -> Model {
Model {
vertex_buffer: Vec::<Vertex>::new(),
material_list: Vec::<Material>::new(),
mesh_list: Vec::<Mesh>::new(),
min: min,
max: max,
normalize: true,
}
}
pub fn add_texture_cube(&mut self, dir_path: &std::path::Path, image_extension: &str) -> Result<(), String> {
let texture = std::rc::Rc::new(try!(TextureCube::new(dir_path, image_extension)));
for material in &mut self.material_list {
material.add_texture_cube(texture.clone());
}
Ok(())
}
pub fn draw(&self, shader: &mut Shader, device: &mut Device) -> u32 {
let mut triangle_cnt: u32 = 0;
for mesh in &self.mesh_list {
triangle_cnt += mesh.draw(shader,
&self.material_list[mesh.material_id],
&self.vertex_buffer,
device);
}
triangle_cnt
}
pub fn to_center_matrix(&self) -> Matrix4<f32> {
if self.normalize {
let size = self.max.sub(&self.min);
let scale = Vector3::from_value(1.0_f32/(size.x.max(size.y).max(size.z)));
let center = self.min.add(&size.mul(0.5_f32));
let mat_move = Matrix4::from_translation(center.mul(-1.0_f32));
let mat_scale = Matrix4::from(Matrix3::from_diagonal(scale));
mat_scale.mul(&mat_move)
} else {
Matrix4::from_scale(1.0_f32)
}
}
}
|
new
|
identifier_name
|
mesh.rs
|
use std;
use cgmath::*;
use shader::*;
use device::Device;
use material::Material;
use rasterization::triangle;
use texture::TextureCube;
use std::ops::{Sub, Add, Mul};
#[derive(Copy,Clone)]
pub struct Vertex {
pub position: Vector3<f32>,
pub normal: Vector3<f32>,
pub tex: Vector2<f32>,
}
pub struct Mesh {
pub index_buffer: Vec<u32>,
pub material_id: usize,
}
pub struct Model {
pub vertex_buffer: Vec<Vertex>,
pub material_list: Vec<Material>,
pub mesh_list: Vec<Mesh>,
min: Vector3<f32>,
max: Vector3<f32>,
normalize: bool,
}
impl Vertex {
pub fn new(position: &Vector3<f32>, tex: &Vector2<f32>, normal: &Vector3<f32>) -> Vertex {
Vertex {
position: position.clone(),
normal: normal.clone(),
tex: tex.clone(),
}
}
}
impl Mesh {
pub fn new() -> Mesh {
Mesh {
index_buffer: Vec::<u32>::new(),
material_id: 0,
}
}
fn draw(&self, shader: &mut Shader,
material: &Material,
vertex_buffer: &Vec<Vertex>,
device: &mut Device) -> u32 {
shader.set_material(material);
let vertex_func = match material.texture {
None => shader.vertex_func[0],
Some(_) => shader.vertex_func[1],
};
let is_cubemap = match material.texture_cube {
None => false,
Some(_) => true,
};
shader.texture_cube = match material.texture_cube {
None => None,
Some(ref t) => Some(t.clone()),
};
let cnt_triangle = self.index_buffer.len() / 3;
for indexes in self.index_buffer.chunks(3) {
let mut points_2d: [Point3<f32>; 3] = [Point3::<f32>::new(0.0, 0.0, 0.0); 3];
let mut tex_coord: [Vector2<f32>; 3] = [Vector2::<f32>::new(0.0, 0.0); 3];
let mut vertex_out = [[0.0_f32;MAX_OUT_VALUES];3];
for i in 0..3 {
let p = vertex_buffer[indexes[i] as usize];
let v = p.position;
let n = p.normal;
let t = p.tex;
shader.reset(Vector4::<f32>::new(v.x, v.y, v.z, 1.0_f32), Vector4::<f32>::new(n.x, n.y, n.z, 0.0_f32), t);
let p_screen = vertex_func(shader);
if is_cubemap {
shader.vertex_out2_base = shader.vertex_out_len;
shader.vertex_cubemap();
}
let inverse_w = 1.0_f32 / p_screen.w;
for ind in 0..shader.vertex_out_len {
vertex_out[i][ind] = shader.out_vertex_data[ind] * inverse_w;
}
tex_coord[i] = t;
points_2d[i] = Point3::new(
(p_screen.x * inverse_w + 1.0_f32) * device.x_size as f32 * 0.5_f32,
(p_screen.y * inverse_w + 1.0_f32) * device.y_size as f32 * 0.5_f32,
inverse_w);
}
let col0 = Vector3::new(points_2d[0].x, points_2d[1].x, points_2d[2].x);
let col1 = Vector3::new(points_2d[0].y, points_2d[1].y, points_2d[2].y);
let col2 = Vector3::new(1.0_f32, 1.0_f32, 1.0_f32 );
if Matrix3::from_cols(col0, col1, col2).determinant() < 0.0_f32 {
continue;
}
// calc mip level:
shader.texture = match material.texture {
Some(ref texture) => {
let ba_pixel = Vector2::new(points_2d[1].x, points_2d[1].y)
.sub(Vector2::new(points_2d[0].x, points_2d[0].y));
let ca_pixel = Vector2::new(points_2d[2].x, points_2d[2].y)
.sub(Vector2::new(points_2d[0].x, points_2d[0].y));
let tex_size = texture.size;
let ba_texel = tex_coord[1].sub(tex_coord[0]).mul(&tex_size);
let ca_texel = tex_coord[2].sub(tex_coord[0]).mul(&tex_size);
// cross product in 2d = 2 * square of triangle
let sq_pixel = ba_pixel.x * ca_pixel.y - ba_pixel.y * ca_pixel.x;
let sq_texel = ba_texel.x * ca_texel.y - ba_texel.y * ca_texel.x;
let lod = (sq_texel / sq_pixel).abs().sqrt().max(1.0_f32).log2() as usize;
Some(texture.get_surface(lod))
},
None => None,
};
triangle(&mut device.cbuffer,
&mut device.zbuffer,
device.x_size,
device.y_size,
points_2d, vertex_out, shader);
}
cnt_triangle as u32
}
}
impl Model {
pub fn new() -> Model {
Model {
vertex_buffer: Vec::<Vertex>::new(),
material_list: Vec::<Material>::new(),
mesh_list: Vec::<Mesh>::new(),
min: Vector3::new(0.0_f32, 0.0_f32, 0.0_f32),
max: Vector3::new(0.0_f32, 0.0_f32, 0.0_f32),
normalize: false,
}
}
pub fn with_normalize(min: Vector3<f32>, max: Vector3<f32>) -> Model {
Model {
vertex_buffer: Vec::<Vertex>::new(),
material_list: Vec::<Material>::new(),
mesh_list: Vec::<Mesh>::new(),
min: min,
max: max,
normalize: true,
}
}
pub fn add_texture_cube(&mut self, dir_path: &std::path::Path, image_extension: &str) -> Result<(), String> {
let texture = std::rc::Rc::new(try!(TextureCube::new(dir_path, image_extension)));
for material in &mut self.material_list {
material.add_texture_cube(texture.clone());
}
Ok(())
}
pub fn draw(&self, shader: &mut Shader, device: &mut Device) -> u32 {
let mut triangle_cnt: u32 = 0;
for mesh in &self.mesh_list {
triangle_cnt += mesh.draw(shader,
&self.material_list[mesh.material_id],
&self.vertex_buffer,
device);
}
triangle_cnt
}
pub fn to_center_matrix(&self) -> Matrix4<f32>
|
}
|
{
if self.normalize {
let size = self.max.sub(&self.min);
let scale = Vector3::from_value(1.0_f32/(size.x.max(size.y).max(size.z)));
let center = self.min.add(&size.mul(0.5_f32));
let mat_move = Matrix4::from_translation(center.mul(-1.0_f32));
let mat_scale = Matrix4::from(Matrix3::from_diagonal(scale));
mat_scale.mul(&mat_move)
} else {
Matrix4::from_scale(1.0_f32)
}
}
|
identifier_body
|
transcribe.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use ast::{TokenTree, TTDelim, TTTok, TTSeq, TTNonterminal, Ident};
use codemap::{Span, DUMMY_SP};
use diagnostic::SpanHandler;
use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
use parse::token::{EOF, INTERPOLATED, IDENT, Token, NtIdent};
use parse::token;
use parse::lexer::TokenAndSpan;
use std::rc::Rc;
use collections::HashMap;
///an unzipping of `TokenTree`s
#[deriving(Clone)]
struct TtFrame {
forest: Rc<Vec<ast::TokenTree>>,
idx: uint,
dotdotdoted: bool,
sep: Option<Token>,
}
#[deriving(Clone)]
pub struct TtReader<'a> {
sp_diag: &'a SpanHandler,
// the unzipped tree:
priv stack: Vec<TtFrame>,
/* for MBE-style macro transcription */
priv interpolations: HashMap<Ident, Rc<NamedMatch>>,
priv repeat_idx: Vec<uint>,
priv repeat_len: Vec<uint>,
/* cached: */
cur_tok: Token,
cur_span: Span,
}
/** This can do Macro-By-Example transcription. On the other hand, if
* `src` contains no `TTSeq`s and `TTNonterminal`s, `interp` can (and
* should) be none. */
pub fn new_tt_reader<'a>(sp_diag: &'a SpanHandler,
interp: Option<HashMap<Ident, Rc<NamedMatch>>>,
src: Vec<ast::TokenTree> )
-> TtReader<'a> {
let mut r = TtReader {
sp_diag: sp_diag,
stack: vec!(TtFrame {
forest: Rc::new(src),
idx: 0,
dotdotdoted: false,
sep: None,
}),
interpolations: match interp { /* just a convienience */
None => HashMap::new(),
Some(x) => x,
},
repeat_idx: Vec::new(),
repeat_len: Vec::new(),
/* dummy values, never read: */
cur_tok: EOF,
cur_span: DUMMY_SP,
};
tt_next_token(&mut r); /* get cur_tok and cur_span set up */
r
}
fn lookup_cur_matched_by_matched(r: &TtReader, start: Rc<NamedMatch>) -> Rc<NamedMatch> {
r.repeat_idx.iter().fold(start, |ad, idx| {
match *ad {
MatchedNonterminal(_) => {
// end of the line; duplicate henceforth
ad.clone()
}
MatchedSeq(ref ads, _) => ads.get(*idx).clone()
}
})
}
fn lookup_cur_matched(r: &TtReader, name: Ident) -> Rc<NamedMatch> {
let matched_opt = r.interpolations.find_copy(&name);
match matched_opt {
Some(s) => lookup_cur_matched_by_matched(r, s),
None => {
r.sp_diag.span_fatal(r.cur_span,
format!("unknown macro variable `{}`",
token::get_ident(name)));
}
}
}
#[deriving(Clone)]
enum LockstepIterSize {
LisUnconstrained,
LisConstraint(uint, Ident),
LisContradiction(~str),
}
fn lis_merge(lhs: LockstepIterSize, rhs: LockstepIterSize) -> LockstepIterSize {
match lhs {
LisUnconstrained => rhs.clone(),
LisContradiction(_) => lhs.clone(),
LisConstraint(l_len, l_id) => match rhs {
LisUnconstrained => lhs.clone(),
LisContradiction(_) => rhs.clone(),
LisConstraint(r_len, _) if l_len == r_len => lhs.clone(),
LisConstraint(r_len, r_id) => {
let l_n = token::get_ident(l_id);
let r_n = token::get_ident(r_id);
LisContradiction(format!("inconsistent lockstep iteration: \
'{}' has {} items, but '{}' has {}",
l_n, l_len, r_n, r_len))
}
}
}
}
fn lockstep_iter_size(t: &TokenTree, r: &TtReader) -> LockstepIterSize {
match *t {
TTDelim(ref tts) | TTSeq(_, ref tts, _, _) => {
tts.iter().fold(LisUnconstrained, |lis, tt| {
lis_merge(lis, lockstep_iter_size(tt, r))
})
}
TTTok(..) => LisUnconstrained,
TTNonterminal(_, name) => match *lookup_cur_matched(r, name) {
MatchedNonterminal(_) => LisUnconstrained,
MatchedSeq(ref ads, _) => LisConstraint(ads.len(), name)
}
}
}
// return the next token from the TtReader.
// EFFECT: advances the reader's token field
pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan {
// FIXME(pcwalton): Bad copy?
let ret_val = TokenAndSpan {
tok: r.cur_tok.clone(),
sp: r.cur_span.clone(),
};
loop {
let should_pop = match r.stack.last() {
None => {
assert_eq!(ret_val.tok, EOF);
return ret_val;
}
Some(frame) => {
if frame.idx < frame.forest.len() {
break;
}
!frame.dotdotdoted ||
*r.repeat_idx.last().unwrap() == *r.repeat_len.last().unwrap() - 1
}
};
/* done with this set; pop or repeat? */
if should_pop {
let prev = r.stack.pop().unwrap();
match r.stack.mut_last() {
None => {
r.cur_tok = EOF;
return ret_val;
}
Some(frame) => {
frame.idx += 1;
}
}
if prev.dotdotdoted {
r.repeat_idx.pop();
r.repeat_len.pop();
}
} else { /* repeat */
*r.repeat_idx.mut_last().unwrap() += 1u;
r.stack.mut_last().unwrap().idx = 0;
match r.stack.last().unwrap().sep.clone() {
Some(tk) => {
r.cur_tok = tk; /* repeat same span, I guess */
return ret_val;
}
None => {}
}
}
}
loop { /* because it's easiest, this handles `TTDelim` not starting
with a `TTTok`, even though it won't happen */
let t = {
let frame = r.stack.last().unwrap();
// FIXME(pcwalton): Bad copy.
(*frame.forest.get(frame.idx)).clone()
};
match t {
TTDelim(tts) => {
r.stack.push(TtFrame {
forest: tts,
idx: 0,
dotdotdoted: false,
sep: None
});
// if this could be 0-length, we'd need to potentially recur here
}
TTTok(sp, tok) => {
r.cur_span = sp;
r.cur_tok = tok;
r.stack.mut_last().unwrap().idx += 1;
return ret_val;
}
TTSeq(sp, tts, sep, zerok) => {
// FIXME(pcwalton): Bad copy.
match lockstep_iter_size(&TTSeq(sp, tts.clone(), sep.clone(), zerok), r) {
LisUnconstrained => {
r.sp_diag.span_fatal(
sp.clone(), /* blame macro writer */
"attempted to repeat an expression \
containing no syntax \
variables matched as repeating at this depth");
}
LisContradiction(ref msg) => {
// FIXME #2887 blame macro invoker instead
r.sp_diag.span_fatal(sp.clone(), *msg);
}
LisConstraint(len, _) => {
if len == 0 {
if!zerok {
// FIXME #2887 blame invoker
r.sp_diag.span_fatal(sp.clone(),
"this must repeat at least once");
}
r.stack.mut_last().unwrap().idx += 1;
return tt_next_token(r);
}
r.repeat_len.push(len);
r.repeat_idx.push(0);
r.stack.push(TtFrame {
forest: tts,
idx: 0,
dotdotdoted: true,
sep: sep.clone()
});
}
}
}
// FIXME #2887: think about span stuff here
TTNonterminal(sp, ident) => {
r.stack.mut_last().unwrap().idx += 1;
match *lookup_cur_matched(r, ident) {
/* sidestep the interpolation tricks for ident because
(a) idents can be in lots of places, so it'd be a pain
(b) we actually can, since it's a token. */
MatchedNonterminal(NtIdent(~sn,b)) => {
r.cur_span = sp;
r.cur_tok = IDENT(sn,b);
return ret_val;
}
MatchedNonterminal(ref other_whole_nt) => {
// FIXME(pcwalton): Bad copy.
r.cur_span = sp;
r.cur_tok = INTERPOLATED((*other_whole_nt).clone());
return ret_val;
}
MatchedSeq(..) => {
r.sp_diag.span_fatal(
r.cur_span, /* blame the macro writer */
format!("variable '{}' is still repeating at this depth",
token::get_ident(ident)));
}
}
}
}
}
|
}
|
random_line_split
|
|
transcribe.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use ast::{TokenTree, TTDelim, TTTok, TTSeq, TTNonterminal, Ident};
use codemap::{Span, DUMMY_SP};
use diagnostic::SpanHandler;
use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
use parse::token::{EOF, INTERPOLATED, IDENT, Token, NtIdent};
use parse::token;
use parse::lexer::TokenAndSpan;
use std::rc::Rc;
use collections::HashMap;
///an unzipping of `TokenTree`s
#[deriving(Clone)]
struct TtFrame {
forest: Rc<Vec<ast::TokenTree>>,
idx: uint,
dotdotdoted: bool,
sep: Option<Token>,
}
#[deriving(Clone)]
pub struct TtReader<'a> {
sp_diag: &'a SpanHandler,
// the unzipped tree:
priv stack: Vec<TtFrame>,
/* for MBE-style macro transcription */
priv interpolations: HashMap<Ident, Rc<NamedMatch>>,
priv repeat_idx: Vec<uint>,
priv repeat_len: Vec<uint>,
/* cached: */
cur_tok: Token,
cur_span: Span,
}
/** This can do Macro-By-Example transcription. On the other hand, if
* `src` contains no `TTSeq`s and `TTNonterminal`s, `interp` can (and
* should) be none. */
pub fn new_tt_reader<'a>(sp_diag: &'a SpanHandler,
interp: Option<HashMap<Ident, Rc<NamedMatch>>>,
src: Vec<ast::TokenTree> )
-> TtReader<'a> {
let mut r = TtReader {
sp_diag: sp_diag,
stack: vec!(TtFrame {
forest: Rc::new(src),
idx: 0,
dotdotdoted: false,
sep: None,
}),
interpolations: match interp { /* just a convienience */
None => HashMap::new(),
Some(x) => x,
},
repeat_idx: Vec::new(),
repeat_len: Vec::new(),
/* dummy values, never read: */
cur_tok: EOF,
cur_span: DUMMY_SP,
};
tt_next_token(&mut r); /* get cur_tok and cur_span set up */
r
}
fn lookup_cur_matched_by_matched(r: &TtReader, start: Rc<NamedMatch>) -> Rc<NamedMatch>
|
fn lookup_cur_matched(r: &TtReader, name: Ident) -> Rc<NamedMatch> {
let matched_opt = r.interpolations.find_copy(&name);
match matched_opt {
Some(s) => lookup_cur_matched_by_matched(r, s),
None => {
r.sp_diag.span_fatal(r.cur_span,
format!("unknown macro variable `{}`",
token::get_ident(name)));
}
}
}
#[deriving(Clone)]
enum LockstepIterSize {
LisUnconstrained,
LisConstraint(uint, Ident),
LisContradiction(~str),
}
fn lis_merge(lhs: LockstepIterSize, rhs: LockstepIterSize) -> LockstepIterSize {
match lhs {
LisUnconstrained => rhs.clone(),
LisContradiction(_) => lhs.clone(),
LisConstraint(l_len, l_id) => match rhs {
LisUnconstrained => lhs.clone(),
LisContradiction(_) => rhs.clone(),
LisConstraint(r_len, _) if l_len == r_len => lhs.clone(),
LisConstraint(r_len, r_id) => {
let l_n = token::get_ident(l_id);
let r_n = token::get_ident(r_id);
LisContradiction(format!("inconsistent lockstep iteration: \
'{}' has {} items, but '{}' has {}",
l_n, l_len, r_n, r_len))
}
}
}
}
fn lockstep_iter_size(t: &TokenTree, r: &TtReader) -> LockstepIterSize {
match *t {
TTDelim(ref tts) | TTSeq(_, ref tts, _, _) => {
tts.iter().fold(LisUnconstrained, |lis, tt| {
lis_merge(lis, lockstep_iter_size(tt, r))
})
}
TTTok(..) => LisUnconstrained,
TTNonterminal(_, name) => match *lookup_cur_matched(r, name) {
MatchedNonterminal(_) => LisUnconstrained,
MatchedSeq(ref ads, _) => LisConstraint(ads.len(), name)
}
}
}
// return the next token from the TtReader.
// EFFECT: advances the reader's token field
pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan {
// FIXME(pcwalton): Bad copy?
let ret_val = TokenAndSpan {
tok: r.cur_tok.clone(),
sp: r.cur_span.clone(),
};
loop {
let should_pop = match r.stack.last() {
None => {
assert_eq!(ret_val.tok, EOF);
return ret_val;
}
Some(frame) => {
if frame.idx < frame.forest.len() {
break;
}
!frame.dotdotdoted ||
*r.repeat_idx.last().unwrap() == *r.repeat_len.last().unwrap() - 1
}
};
/* done with this set; pop or repeat? */
if should_pop {
let prev = r.stack.pop().unwrap();
match r.stack.mut_last() {
None => {
r.cur_tok = EOF;
return ret_val;
}
Some(frame) => {
frame.idx += 1;
}
}
if prev.dotdotdoted {
r.repeat_idx.pop();
r.repeat_len.pop();
}
} else { /* repeat */
*r.repeat_idx.mut_last().unwrap() += 1u;
r.stack.mut_last().unwrap().idx = 0;
match r.stack.last().unwrap().sep.clone() {
Some(tk) => {
r.cur_tok = tk; /* repeat same span, I guess */
return ret_val;
}
None => {}
}
}
}
loop { /* because it's easiest, this handles `TTDelim` not starting
with a `TTTok`, even though it won't happen */
let t = {
let frame = r.stack.last().unwrap();
// FIXME(pcwalton): Bad copy.
(*frame.forest.get(frame.idx)).clone()
};
match t {
TTDelim(tts) => {
r.stack.push(TtFrame {
forest: tts,
idx: 0,
dotdotdoted: false,
sep: None
});
// if this could be 0-length, we'd need to potentially recur here
}
TTTok(sp, tok) => {
r.cur_span = sp;
r.cur_tok = tok;
r.stack.mut_last().unwrap().idx += 1;
return ret_val;
}
TTSeq(sp, tts, sep, zerok) => {
// FIXME(pcwalton): Bad copy.
match lockstep_iter_size(&TTSeq(sp, tts.clone(), sep.clone(), zerok), r) {
LisUnconstrained => {
r.sp_diag.span_fatal(
sp.clone(), /* blame macro writer */
"attempted to repeat an expression \
containing no syntax \
variables matched as repeating at this depth");
}
LisContradiction(ref msg) => {
// FIXME #2887 blame macro invoker instead
r.sp_diag.span_fatal(sp.clone(), *msg);
}
LisConstraint(len, _) => {
if len == 0 {
if!zerok {
// FIXME #2887 blame invoker
r.sp_diag.span_fatal(sp.clone(),
"this must repeat at least once");
}
r.stack.mut_last().unwrap().idx += 1;
return tt_next_token(r);
}
r.repeat_len.push(len);
r.repeat_idx.push(0);
r.stack.push(TtFrame {
forest: tts,
idx: 0,
dotdotdoted: true,
sep: sep.clone()
});
}
}
}
// FIXME #2887: think about span stuff here
TTNonterminal(sp, ident) => {
r.stack.mut_last().unwrap().idx += 1;
match *lookup_cur_matched(r, ident) {
/* sidestep the interpolation tricks for ident because
(a) idents can be in lots of places, so it'd be a pain
(b) we actually can, since it's a token. */
MatchedNonterminal(NtIdent(~sn,b)) => {
r.cur_span = sp;
r.cur_tok = IDENT(sn,b);
return ret_val;
}
MatchedNonterminal(ref other_whole_nt) => {
// FIXME(pcwalton): Bad copy.
r.cur_span = sp;
r.cur_tok = INTERPOLATED((*other_whole_nt).clone());
return ret_val;
}
MatchedSeq(..) => {
r.sp_diag.span_fatal(
r.cur_span, /* blame the macro writer */
format!("variable '{}' is still repeating at this depth",
token::get_ident(ident)));
}
}
}
}
}
}
|
{
r.repeat_idx.iter().fold(start, |ad, idx| {
match *ad {
MatchedNonterminal(_) => {
// end of the line; duplicate henceforth
ad.clone()
}
MatchedSeq(ref ads, _) => ads.get(*idx).clone()
}
})
}
|
identifier_body
|
transcribe.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use ast::{TokenTree, TTDelim, TTTok, TTSeq, TTNonterminal, Ident};
use codemap::{Span, DUMMY_SP};
use diagnostic::SpanHandler;
use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
use parse::token::{EOF, INTERPOLATED, IDENT, Token, NtIdent};
use parse::token;
use parse::lexer::TokenAndSpan;
use std::rc::Rc;
use collections::HashMap;
///an unzipping of `TokenTree`s
#[deriving(Clone)]
struct
|
{
forest: Rc<Vec<ast::TokenTree>>,
idx: uint,
dotdotdoted: bool,
sep: Option<Token>,
}
#[deriving(Clone)]
pub struct TtReader<'a> {
sp_diag: &'a SpanHandler,
// the unzipped tree:
priv stack: Vec<TtFrame>,
/* for MBE-style macro transcription */
priv interpolations: HashMap<Ident, Rc<NamedMatch>>,
priv repeat_idx: Vec<uint>,
priv repeat_len: Vec<uint>,
/* cached: */
cur_tok: Token,
cur_span: Span,
}
/** This can do Macro-By-Example transcription. On the other hand, if
* `src` contains no `TTSeq`s and `TTNonterminal`s, `interp` can (and
* should) be none. */
pub fn new_tt_reader<'a>(sp_diag: &'a SpanHandler,
interp: Option<HashMap<Ident, Rc<NamedMatch>>>,
src: Vec<ast::TokenTree> )
-> TtReader<'a> {
let mut r = TtReader {
sp_diag: sp_diag,
stack: vec!(TtFrame {
forest: Rc::new(src),
idx: 0,
dotdotdoted: false,
sep: None,
}),
interpolations: match interp { /* just a convienience */
None => HashMap::new(),
Some(x) => x,
},
repeat_idx: Vec::new(),
repeat_len: Vec::new(),
/* dummy values, never read: */
cur_tok: EOF,
cur_span: DUMMY_SP,
};
tt_next_token(&mut r); /* get cur_tok and cur_span set up */
r
}
fn lookup_cur_matched_by_matched(r: &TtReader, start: Rc<NamedMatch>) -> Rc<NamedMatch> {
r.repeat_idx.iter().fold(start, |ad, idx| {
match *ad {
MatchedNonterminal(_) => {
// end of the line; duplicate henceforth
ad.clone()
}
MatchedSeq(ref ads, _) => ads.get(*idx).clone()
}
})
}
fn lookup_cur_matched(r: &TtReader, name: Ident) -> Rc<NamedMatch> {
let matched_opt = r.interpolations.find_copy(&name);
match matched_opt {
Some(s) => lookup_cur_matched_by_matched(r, s),
None => {
r.sp_diag.span_fatal(r.cur_span,
format!("unknown macro variable `{}`",
token::get_ident(name)));
}
}
}
#[deriving(Clone)]
enum LockstepIterSize {
LisUnconstrained,
LisConstraint(uint, Ident),
LisContradiction(~str),
}
fn lis_merge(lhs: LockstepIterSize, rhs: LockstepIterSize) -> LockstepIterSize {
match lhs {
LisUnconstrained => rhs.clone(),
LisContradiction(_) => lhs.clone(),
LisConstraint(l_len, l_id) => match rhs {
LisUnconstrained => lhs.clone(),
LisContradiction(_) => rhs.clone(),
LisConstraint(r_len, _) if l_len == r_len => lhs.clone(),
LisConstraint(r_len, r_id) => {
let l_n = token::get_ident(l_id);
let r_n = token::get_ident(r_id);
LisContradiction(format!("inconsistent lockstep iteration: \
'{}' has {} items, but '{}' has {}",
l_n, l_len, r_n, r_len))
}
}
}
}
fn lockstep_iter_size(t: &TokenTree, r: &TtReader) -> LockstepIterSize {
match *t {
TTDelim(ref tts) | TTSeq(_, ref tts, _, _) => {
tts.iter().fold(LisUnconstrained, |lis, tt| {
lis_merge(lis, lockstep_iter_size(tt, r))
})
}
TTTok(..) => LisUnconstrained,
TTNonterminal(_, name) => match *lookup_cur_matched(r, name) {
MatchedNonterminal(_) => LisUnconstrained,
MatchedSeq(ref ads, _) => LisConstraint(ads.len(), name)
}
}
}
// return the next token from the TtReader.
// EFFECT: advances the reader's token field
pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan {
// FIXME(pcwalton): Bad copy?
let ret_val = TokenAndSpan {
tok: r.cur_tok.clone(),
sp: r.cur_span.clone(),
};
loop {
let should_pop = match r.stack.last() {
None => {
assert_eq!(ret_val.tok, EOF);
return ret_val;
}
Some(frame) => {
if frame.idx < frame.forest.len() {
break;
}
!frame.dotdotdoted ||
*r.repeat_idx.last().unwrap() == *r.repeat_len.last().unwrap() - 1
}
};
/* done with this set; pop or repeat? */
if should_pop {
let prev = r.stack.pop().unwrap();
match r.stack.mut_last() {
None => {
r.cur_tok = EOF;
return ret_val;
}
Some(frame) => {
frame.idx += 1;
}
}
if prev.dotdotdoted {
r.repeat_idx.pop();
r.repeat_len.pop();
}
} else { /* repeat */
*r.repeat_idx.mut_last().unwrap() += 1u;
r.stack.mut_last().unwrap().idx = 0;
match r.stack.last().unwrap().sep.clone() {
Some(tk) => {
r.cur_tok = tk; /* repeat same span, I guess */
return ret_val;
}
None => {}
}
}
}
loop { /* because it's easiest, this handles `TTDelim` not starting
with a `TTTok`, even though it won't happen */
let t = {
let frame = r.stack.last().unwrap();
// FIXME(pcwalton): Bad copy.
(*frame.forest.get(frame.idx)).clone()
};
match t {
TTDelim(tts) => {
r.stack.push(TtFrame {
forest: tts,
idx: 0,
dotdotdoted: false,
sep: None
});
// if this could be 0-length, we'd need to potentially recur here
}
TTTok(sp, tok) => {
r.cur_span = sp;
r.cur_tok = tok;
r.stack.mut_last().unwrap().idx += 1;
return ret_val;
}
TTSeq(sp, tts, sep, zerok) => {
// FIXME(pcwalton): Bad copy.
match lockstep_iter_size(&TTSeq(sp, tts.clone(), sep.clone(), zerok), r) {
LisUnconstrained => {
r.sp_diag.span_fatal(
sp.clone(), /* blame macro writer */
"attempted to repeat an expression \
containing no syntax \
variables matched as repeating at this depth");
}
LisContradiction(ref msg) => {
// FIXME #2887 blame macro invoker instead
r.sp_diag.span_fatal(sp.clone(), *msg);
}
LisConstraint(len, _) => {
if len == 0 {
if!zerok {
// FIXME #2887 blame invoker
r.sp_diag.span_fatal(sp.clone(),
"this must repeat at least once");
}
r.stack.mut_last().unwrap().idx += 1;
return tt_next_token(r);
}
r.repeat_len.push(len);
r.repeat_idx.push(0);
r.stack.push(TtFrame {
forest: tts,
idx: 0,
dotdotdoted: true,
sep: sep.clone()
});
}
}
}
// FIXME #2887: think about span stuff here
TTNonterminal(sp, ident) => {
r.stack.mut_last().unwrap().idx += 1;
match *lookup_cur_matched(r, ident) {
/* sidestep the interpolation tricks for ident because
(a) idents can be in lots of places, so it'd be a pain
(b) we actually can, since it's a token. */
MatchedNonterminal(NtIdent(~sn,b)) => {
r.cur_span = sp;
r.cur_tok = IDENT(sn,b);
return ret_val;
}
MatchedNonterminal(ref other_whole_nt) => {
// FIXME(pcwalton): Bad copy.
r.cur_span = sp;
r.cur_tok = INTERPOLATED((*other_whole_nt).clone());
return ret_val;
}
MatchedSeq(..) => {
r.sp_diag.span_fatal(
r.cur_span, /* blame the macro writer */
format!("variable '{}' is still repeating at this depth",
token::get_ident(ident)));
}
}
}
}
}
}
|
TtFrame
|
identifier_name
|
transcribe.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use ast::{TokenTree, TTDelim, TTTok, TTSeq, TTNonterminal, Ident};
use codemap::{Span, DUMMY_SP};
use diagnostic::SpanHandler;
use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
use parse::token::{EOF, INTERPOLATED, IDENT, Token, NtIdent};
use parse::token;
use parse::lexer::TokenAndSpan;
use std::rc::Rc;
use collections::HashMap;
///an unzipping of `TokenTree`s
#[deriving(Clone)]
struct TtFrame {
forest: Rc<Vec<ast::TokenTree>>,
idx: uint,
dotdotdoted: bool,
sep: Option<Token>,
}
#[deriving(Clone)]
pub struct TtReader<'a> {
sp_diag: &'a SpanHandler,
// the unzipped tree:
priv stack: Vec<TtFrame>,
/* for MBE-style macro transcription */
priv interpolations: HashMap<Ident, Rc<NamedMatch>>,
priv repeat_idx: Vec<uint>,
priv repeat_len: Vec<uint>,
/* cached: */
cur_tok: Token,
cur_span: Span,
}
/** This can do Macro-By-Example transcription. On the other hand, if
* `src` contains no `TTSeq`s and `TTNonterminal`s, `interp` can (and
* should) be none. */
pub fn new_tt_reader<'a>(sp_diag: &'a SpanHandler,
interp: Option<HashMap<Ident, Rc<NamedMatch>>>,
src: Vec<ast::TokenTree> )
-> TtReader<'a> {
let mut r = TtReader {
sp_diag: sp_diag,
stack: vec!(TtFrame {
forest: Rc::new(src),
idx: 0,
dotdotdoted: false,
sep: None,
}),
interpolations: match interp { /* just a convienience */
None => HashMap::new(),
Some(x) => x,
},
repeat_idx: Vec::new(),
repeat_len: Vec::new(),
/* dummy values, never read: */
cur_tok: EOF,
cur_span: DUMMY_SP,
};
tt_next_token(&mut r); /* get cur_tok and cur_span set up */
r
}
fn lookup_cur_matched_by_matched(r: &TtReader, start: Rc<NamedMatch>) -> Rc<NamedMatch> {
r.repeat_idx.iter().fold(start, |ad, idx| {
match *ad {
MatchedNonterminal(_) => {
// end of the line; duplicate henceforth
ad.clone()
}
MatchedSeq(ref ads, _) => ads.get(*idx).clone()
}
})
}
fn lookup_cur_matched(r: &TtReader, name: Ident) -> Rc<NamedMatch> {
let matched_opt = r.interpolations.find_copy(&name);
match matched_opt {
Some(s) => lookup_cur_matched_by_matched(r, s),
None => {
r.sp_diag.span_fatal(r.cur_span,
format!("unknown macro variable `{}`",
token::get_ident(name)));
}
}
}
#[deriving(Clone)]
enum LockstepIterSize {
LisUnconstrained,
LisConstraint(uint, Ident),
LisContradiction(~str),
}
fn lis_merge(lhs: LockstepIterSize, rhs: LockstepIterSize) -> LockstepIterSize {
match lhs {
LisUnconstrained => rhs.clone(),
LisContradiction(_) => lhs.clone(),
LisConstraint(l_len, l_id) => match rhs {
LisUnconstrained => lhs.clone(),
LisContradiction(_) => rhs.clone(),
LisConstraint(r_len, _) if l_len == r_len => lhs.clone(),
LisConstraint(r_len, r_id) => {
let l_n = token::get_ident(l_id);
let r_n = token::get_ident(r_id);
LisContradiction(format!("inconsistent lockstep iteration: \
'{}' has {} items, but '{}' has {}",
l_n, l_len, r_n, r_len))
}
}
}
}
fn lockstep_iter_size(t: &TokenTree, r: &TtReader) -> LockstepIterSize {
match *t {
TTDelim(ref tts) | TTSeq(_, ref tts, _, _) => {
tts.iter().fold(LisUnconstrained, |lis, tt| {
lis_merge(lis, lockstep_iter_size(tt, r))
})
}
TTTok(..) => LisUnconstrained,
TTNonterminal(_, name) => match *lookup_cur_matched(r, name) {
MatchedNonterminal(_) => LisUnconstrained,
MatchedSeq(ref ads, _) => LisConstraint(ads.len(), name)
}
}
}
// return the next token from the TtReader.
// EFFECT: advances the reader's token field
pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan {
// FIXME(pcwalton): Bad copy?
let ret_val = TokenAndSpan {
tok: r.cur_tok.clone(),
sp: r.cur_span.clone(),
};
loop {
let should_pop = match r.stack.last() {
None => {
assert_eq!(ret_val.tok, EOF);
return ret_val;
}
Some(frame) => {
if frame.idx < frame.forest.len() {
break;
}
!frame.dotdotdoted ||
*r.repeat_idx.last().unwrap() == *r.repeat_len.last().unwrap() - 1
}
};
/* done with this set; pop or repeat? */
if should_pop
|
else { /* repeat */
*r.repeat_idx.mut_last().unwrap() += 1u;
r.stack.mut_last().unwrap().idx = 0;
match r.stack.last().unwrap().sep.clone() {
Some(tk) => {
r.cur_tok = tk; /* repeat same span, I guess */
return ret_val;
}
None => {}
}
}
}
loop { /* because it's easiest, this handles `TTDelim` not starting
with a `TTTok`, even though it won't happen */
let t = {
let frame = r.stack.last().unwrap();
// FIXME(pcwalton): Bad copy.
(*frame.forest.get(frame.idx)).clone()
};
match t {
TTDelim(tts) => {
r.stack.push(TtFrame {
forest: tts,
idx: 0,
dotdotdoted: false,
sep: None
});
// if this could be 0-length, we'd need to potentially recur here
}
TTTok(sp, tok) => {
r.cur_span = sp;
r.cur_tok = tok;
r.stack.mut_last().unwrap().idx += 1;
return ret_val;
}
TTSeq(sp, tts, sep, zerok) => {
// FIXME(pcwalton): Bad copy.
match lockstep_iter_size(&TTSeq(sp, tts.clone(), sep.clone(), zerok), r) {
LisUnconstrained => {
r.sp_diag.span_fatal(
sp.clone(), /* blame macro writer */
"attempted to repeat an expression \
containing no syntax \
variables matched as repeating at this depth");
}
LisContradiction(ref msg) => {
// FIXME #2887 blame macro invoker instead
r.sp_diag.span_fatal(sp.clone(), *msg);
}
LisConstraint(len, _) => {
if len == 0 {
if!zerok {
// FIXME #2887 blame invoker
r.sp_diag.span_fatal(sp.clone(),
"this must repeat at least once");
}
r.stack.mut_last().unwrap().idx += 1;
return tt_next_token(r);
}
r.repeat_len.push(len);
r.repeat_idx.push(0);
r.stack.push(TtFrame {
forest: tts,
idx: 0,
dotdotdoted: true,
sep: sep.clone()
});
}
}
}
// FIXME #2887: think about span stuff here
TTNonterminal(sp, ident) => {
r.stack.mut_last().unwrap().idx += 1;
match *lookup_cur_matched(r, ident) {
/* sidestep the interpolation tricks for ident because
(a) idents can be in lots of places, so it'd be a pain
(b) we actually can, since it's a token. */
MatchedNonterminal(NtIdent(~sn,b)) => {
r.cur_span = sp;
r.cur_tok = IDENT(sn,b);
return ret_val;
}
MatchedNonterminal(ref other_whole_nt) => {
// FIXME(pcwalton): Bad copy.
r.cur_span = sp;
r.cur_tok = INTERPOLATED((*other_whole_nt).clone());
return ret_val;
}
MatchedSeq(..) => {
r.sp_diag.span_fatal(
r.cur_span, /* blame the macro writer */
format!("variable '{}' is still repeating at this depth",
token::get_ident(ident)));
}
}
}
}
}
}
|
{
let prev = r.stack.pop().unwrap();
match r.stack.mut_last() {
None => {
r.cur_tok = EOF;
return ret_val;
}
Some(frame) => {
frame.idx += 1;
}
}
if prev.dotdotdoted {
r.repeat_idx.pop();
r.repeat_len.pop();
}
}
|
conditional_block
|
lines_iterator.rs
|
use super::Row;
use crate::utils::lines::spans;
use crate::utils::span::{IndexedSpan, SpannedText};
/// Generates rows of text in constrained width.
///
/// Given a long text and a width constraint, it iterates over
/// substrings of the text, each within the constraint.
pub struct LinesIterator<'a> {
iter: spans::LinesIterator<DummySpannedText<'a>>,
/// Available width. Don't output lines wider than that.
width: usize,
}
struct DummySpannedText<'a> {
content: &'a str,
attrs: Vec<IndexedSpan<()>>,
}
impl<'a> DummySpannedText<'a> {
fn new(content: &'a str) -> Self {
let attrs = vec![IndexedSpan::simple_borrowed(content, ())];
DummySpannedText { content, attrs }
}
}
impl<'a> SpannedText for DummySpannedText<'a> {
type S = IndexedSpan<()>;
fn source(&self) -> &str {
self.content
}
fn spans(&self) -> &[IndexedSpan<()>]
|
}
impl<'a> LinesIterator<'a> {
/// Returns a new `LinesIterator` on `content`.
///
/// Yields rows of `width` cells or less.
pub fn new(content: &'a str, width: usize) -> Self {
let iter =
spans::LinesIterator::new(DummySpannedText::new(content), width);
LinesIterator { iter, width }
}
/// Leave a blank cell at the end of lines.
///
/// Unless a word had to be truncated, in which case
/// it takes the entire width.
pub fn show_spaces(self) -> Self {
let iter = self.iter.show_spaces();
let width = self.width;
LinesIterator { iter, width }
}
}
impl<'a> Iterator for LinesIterator<'a> {
type Item = Row;
fn next(&mut self) -> Option<Row> {
let row = self.iter.next()?;
let start = row.segments.first()?.start;
let end = row.segments.last()?.end;
let width = row.width;
Some(Row { start, end, width })
}
}
|
{
&self.attrs
}
|
identifier_body
|
lines_iterator.rs
|
use super::Row;
use crate::utils::lines::spans;
use crate::utils::span::{IndexedSpan, SpannedText};
/// Generates rows of text in constrained width.
///
/// Given a long text and a width constraint, it iterates over
/// substrings of the text, each within the constraint.
pub struct LinesIterator<'a> {
iter: spans::LinesIterator<DummySpannedText<'a>>,
/// Available width. Don't output lines wider than that.
width: usize,
}
struct
|
<'a> {
content: &'a str,
attrs: Vec<IndexedSpan<()>>,
}
impl<'a> DummySpannedText<'a> {
fn new(content: &'a str) -> Self {
let attrs = vec![IndexedSpan::simple_borrowed(content, ())];
DummySpannedText { content, attrs }
}
}
impl<'a> SpannedText for DummySpannedText<'a> {
type S = IndexedSpan<()>;
fn source(&self) -> &str {
self.content
}
fn spans(&self) -> &[IndexedSpan<()>] {
&self.attrs
}
}
impl<'a> LinesIterator<'a> {
/// Returns a new `LinesIterator` on `content`.
///
/// Yields rows of `width` cells or less.
pub fn new(content: &'a str, width: usize) -> Self {
let iter =
spans::LinesIterator::new(DummySpannedText::new(content), width);
LinesIterator { iter, width }
}
/// Leave a blank cell at the end of lines.
///
/// Unless a word had to be truncated, in which case
/// it takes the entire width.
pub fn show_spaces(self) -> Self {
let iter = self.iter.show_spaces();
let width = self.width;
LinesIterator { iter, width }
}
}
impl<'a> Iterator for LinesIterator<'a> {
type Item = Row;
fn next(&mut self) -> Option<Row> {
let row = self.iter.next()?;
let start = row.segments.first()?.start;
let end = row.segments.last()?.end;
let width = row.width;
Some(Row { start, end, width })
}
}
|
DummySpannedText
|
identifier_name
|
lines_iterator.rs
|
use super::Row;
use crate::utils::lines::spans;
use crate::utils::span::{IndexedSpan, SpannedText};
/// Generates rows of text in constrained width.
///
/// Given a long text and a width constraint, it iterates over
/// substrings of the text, each within the constraint.
pub struct LinesIterator<'a> {
iter: spans::LinesIterator<DummySpannedText<'a>>,
/// Available width. Don't output lines wider than that.
width: usize,
}
struct DummySpannedText<'a> {
content: &'a str,
attrs: Vec<IndexedSpan<()>>,
}
impl<'a> DummySpannedText<'a> {
fn new(content: &'a str) -> Self {
let attrs = vec![IndexedSpan::simple_borrowed(content, ())];
DummySpannedText { content, attrs }
}
}
impl<'a> SpannedText for DummySpannedText<'a> {
type S = IndexedSpan<()>;
fn source(&self) -> &str {
self.content
}
fn spans(&self) -> &[IndexedSpan<()>] {
&self.attrs
}
}
impl<'a> LinesIterator<'a> {
/// Returns a new `LinesIterator` on `content`.
///
/// Yields rows of `width` cells or less.
pub fn new(content: &'a str, width: usize) -> Self {
let iter =
spans::LinesIterator::new(DummySpannedText::new(content), width);
LinesIterator { iter, width }
}
/// Leave a blank cell at the end of lines.
///
/// Unless a word had to be truncated, in which case
/// it takes the entire width.
pub fn show_spaces(self) -> Self {
let iter = self.iter.show_spaces();
let width = self.width;
LinesIterator { iter, width }
}
}
impl<'a> Iterator for LinesIterator<'a> {
type Item = Row;
fn next(&mut self) -> Option<Row> {
let row = self.iter.next()?;
let start = row.segments.first()?.start;
let end = row.segments.last()?.end;
|
let width = row.width;
Some(Row { start, end, width })
}
}
|
random_line_split
|
|
htmltemplateelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTemplateElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLTemplateElement {
htmlelement: HTMLElement,
}
impl HTMLTemplateElementDerived for EventTarget {
fn is_htmltemplateelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTemplateElement)))
}
}
impl HTMLTemplateElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLTemplateElement {
HTMLTemplateElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLTemplateElement, localName, prefix, document)
|
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTemplateElement> {
let element = HTMLTemplateElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTemplateElementBinding::Wrap)
}
}
|
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
|
random_line_split
|
htmltemplateelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTemplateElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLTemplateElement {
htmlelement: HTMLElement,
}
impl HTMLTemplateElementDerived for EventTarget {
fn
|
(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTemplateElement)))
}
}
impl HTMLTemplateElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLTemplateElement {
HTMLTemplateElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLTemplateElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTemplateElement> {
let element = HTMLTemplateElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTemplateElementBinding::Wrap)
}
}
|
is_htmltemplateelement
|
identifier_name
|
htmltemplateelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTemplateElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLTemplateElement {
htmlelement: HTMLElement,
}
impl HTMLTemplateElementDerived for EventTarget {
fn is_htmltemplateelement(&self) -> bool
|
}
impl HTMLTemplateElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLTemplateElement {
HTMLTemplateElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLTemplateElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTemplateElement> {
let element = HTMLTemplateElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTemplateElementBinding::Wrap)
}
}
|
{
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTemplateElement)))
}
|
identifier_body
|
getter.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[email protected]>
//
// 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 syntax::ast;
use syntax::ast::P;
use syntax::ext::base::ExtCtxt;
use syntax::codemap::DUMMY_SP;
use syntax::ext::build::AstBuilder;
use syntax::ext::quote::rt::ToTokens;
use syntax::parse::token;
use super::Builder;
use super::super::node;
use super::utils;
/// A visitor to build the field setters for primitive registers
pub struct BuildGetters<'a, 'b, 'c> {
builder: &'a mut Builder,
cx: &'b ExtCtxt<'c>,
}
impl<'a, 'b, 'c> BuildGetters<'a, 'b, 'c> {
pub fn new(builder: &'a mut Builder, cx: &'b ExtCtxt<'c>)
-> BuildGetters<'a, 'b, 'c> {
BuildGetters { builder: builder, cx: cx }
}
}
impl<'a, 'b, 'c> node::RegVisitor for BuildGetters<'a, 'b, 'c> {
fn visit_prim_reg<'a>(&'a mut self, path: &Vec<String>,
reg: &'a node::Reg, _width: node::RegWidth,
fields: &Vec<node::Field>)
|
}
fn build_type<'a>(cx: &'a ExtCtxt, path: &Vec<String>,
reg: &node::Reg) -> P<ast::Item>
{
let packed_ty = utils::reg_primitive_type(cx, reg)
.expect("Unexpected non-primitive register");
let name = utils::getter_name(cx, path);
let reg_doc = match reg.docstring {
Some(d) => token::get_ident(d.node).get().into_string(),
None => "no documentation".into_string(),
};
let docstring = format!("`{}`: {}", reg.name.node, reg_doc);
let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring));
let item = quote_item!(cx,
$doc_attr
#[allow(non_camel_case_types)]
pub struct $name {
value: $packed_ty,
}
);
item.unwrap()
}
fn build_new<'a>(cx: &'a ExtCtxt, path: &Vec<String>)
-> P<ast::Item> {
let reg_ty: P<ast::Ty> =
cx.ty_ident(DUMMY_SP, utils::path_ident(cx, path));
let getter_ty: P<ast::Ty> = cx.ty_ident(DUMMY_SP,
utils::getter_name(cx, path));
let item = quote_item!(cx,
#[doc = "Create a getter reflecting the current value of the given register."]
pub fn new(reg: & $reg_ty) -> $getter_ty {
$getter_ty {
value: reg.value.get(),
}
}
);
item.unwrap()
}
/// Given an `Expr` of the given register's primitive type, return
/// an `Expr` of the field type
fn from_primitive<'a>(cx: &'a ExtCtxt, reg: &node::Reg,
field: &node::Field, prim: P<ast::Expr>)
-> P<ast::Expr> {
match field.ty.node {
node::UIntField => prim,
node::BoolField =>
cx.expr_binary(DUMMY_SP, ast::BiNe,
prim, utils::expr_int(cx, 0)),
node::EnumField {..} => {
let from = match reg.ty {
node::RegPrim(width,_) =>
match width {
node::Reg32 => "from_u32",
node::Reg16 => "from_u16",
node::Reg8 => "from_u8",
},
_ => fail!("Can't convert group register to primitive type"),
};
cx.expr_method_call(
DUMMY_SP,
cx.expr_call_global(
DUMMY_SP,
vec!(cx.ident_of("core"),
cx.ident_of("num"),
cx.ident_of(from)),
vec!(prim)
),
cx.ident_of("unwrap"),
Vec::new()
)
},
}
}
fn build_impl(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg,
fields: &Vec<node::Field>) -> P<ast::Item> {
let getter_ty = utils::getter_name(cx, path);
let new = build_new(cx, path);
let getters: Vec<P<ast::Method>> =
FromIterator::from_iter(
fields.iter()
.map(|field| build_field_get_fn(cx, path, reg, field)));
let it = quote_item!(cx,
#[allow(dead_code)]
impl $getter_ty {
$new
$getters
}
);
it.unwrap()
}
/// Build a getter for a field
fn build_field_get_fn<'a>(cx: &'a ExtCtxt, path: &Vec<String>, reg: &node::Reg,
field: &node::Field) -> P<ast::Method>
{
let fn_name = cx.ident_of(field.name.node.as_slice());
let field_ty: P<ast::Ty> =
cx.ty_path(utils::field_type_path(cx, path, reg, field), None);
let mask = utils::mask(cx, field);
let field_doc = match field.docstring {
Some(d) => d.node,
None => cx.ident_of("no documentation"),
};
let docstring = format!("Get value of `{}` field: {}",
field.name.node,
token::get_ident(field_doc).get());
let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring));
if field.count.node == 1 {
let shift = utils::shift(cx, None, field);
let value = from_primitive(
cx, reg, field,
quote_expr!(cx, (self.value >> $shift) & $mask));
quote_method!(cx,
$doc_attr
pub fn $fn_name<'a>(&'a self) -> $field_ty {
$value
}
)
} else {
let shift = utils::shift(cx, Some(quote_expr!(cx, idx)), field);
let value = from_primitive(
cx, reg, field,
quote_expr!(cx, (self.value >> $shift) & $mask));
quote_method!(cx,
$doc_attr
pub fn $fn_name<'a>(&'a self, idx: uint) -> $field_ty {
$value
}
)
}
}
|
{
if fields.iter().any(|f| f.access != node::WriteOnly) {
let it = build_type(self.cx, path, reg);
self.builder.push_item(it);
let it = build_impl(self.cx, path, reg, fields);
self.builder.push_item(it);
}
}
|
identifier_body
|
getter.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[email protected]>
//
// 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 syntax::ast;
use syntax::ast::P;
use syntax::ext::base::ExtCtxt;
use syntax::codemap::DUMMY_SP;
use syntax::ext::build::AstBuilder;
use syntax::ext::quote::rt::ToTokens;
use syntax::parse::token;
use super::Builder;
use super::super::node;
use super::utils;
/// A visitor to build the field setters for primitive registers
pub struct BuildGetters<'a, 'b, 'c> {
builder: &'a mut Builder,
cx: &'b ExtCtxt<'c>,
}
impl<'a, 'b, 'c> BuildGetters<'a, 'b, 'c> {
pub fn new(builder: &'a mut Builder, cx: &'b ExtCtxt<'c>)
-> BuildGetters<'a, 'b, 'c> {
BuildGetters { builder: builder, cx: cx }
}
}
impl<'a, 'b, 'c> node::RegVisitor for BuildGetters<'a, 'b, 'c> {
fn visit_prim_reg<'a>(&'a mut self, path: &Vec<String>,
reg: &'a node::Reg, _width: node::RegWidth,
fields: &Vec<node::Field>) {
if fields.iter().any(|f| f.access!= node::WriteOnly) {
let it = build_type(self.cx, path, reg);
self.builder.push_item(it);
let it = build_impl(self.cx, path, reg, fields);
self.builder.push_item(it);
}
}
}
fn build_type<'a>(cx: &'a ExtCtxt, path: &Vec<String>,
reg: &node::Reg) -> P<ast::Item>
{
let packed_ty = utils::reg_primitive_type(cx, reg)
.expect("Unexpected non-primitive register");
let name = utils::getter_name(cx, path);
let reg_doc = match reg.docstring {
Some(d) => token::get_ident(d.node).get().into_string(),
None => "no documentation".into_string(),
};
let docstring = format!("`{}`: {}", reg.name.node, reg_doc);
let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring));
let item = quote_item!(cx,
$doc_attr
#[allow(non_camel_case_types)]
pub struct $name {
value: $packed_ty,
}
);
item.unwrap()
}
fn build_new<'a>(cx: &'a ExtCtxt, path: &Vec<String>)
-> P<ast::Item> {
let reg_ty: P<ast::Ty> =
cx.ty_ident(DUMMY_SP, utils::path_ident(cx, path));
let getter_ty: P<ast::Ty> = cx.ty_ident(DUMMY_SP,
utils::getter_name(cx, path));
let item = quote_item!(cx,
#[doc = "Create a getter reflecting the current value of the given register."]
pub fn new(reg: & $reg_ty) -> $getter_ty {
$getter_ty {
value: reg.value.get(),
}
}
);
item.unwrap()
}
/// Given an `Expr` of the given register's primitive type, return
/// an `Expr` of the field type
fn from_primitive<'a>(cx: &'a ExtCtxt, reg: &node::Reg,
field: &node::Field, prim: P<ast::Expr>)
-> P<ast::Expr> {
match field.ty.node {
node::UIntField => prim,
node::BoolField =>
cx.expr_binary(DUMMY_SP, ast::BiNe,
prim, utils::expr_int(cx, 0)),
node::EnumField {..} => {
let from = match reg.ty {
node::RegPrim(width,_) =>
match width {
node::Reg32 => "from_u32",
node::Reg16 => "from_u16",
node::Reg8 => "from_u8",
},
_ => fail!("Can't convert group register to primitive type"),
};
cx.expr_method_call(
DUMMY_SP,
cx.expr_call_global(
DUMMY_SP,
vec!(cx.ident_of("core"),
cx.ident_of("num"),
cx.ident_of(from)),
vec!(prim)
),
|
}
}
fn build_impl(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg,
fields: &Vec<node::Field>) -> P<ast::Item> {
let getter_ty = utils::getter_name(cx, path);
let new = build_new(cx, path);
let getters: Vec<P<ast::Method>> =
FromIterator::from_iter(
fields.iter()
.map(|field| build_field_get_fn(cx, path, reg, field)));
let it = quote_item!(cx,
#[allow(dead_code)]
impl $getter_ty {
$new
$getters
}
);
it.unwrap()
}
/// Build a getter for a field
fn build_field_get_fn<'a>(cx: &'a ExtCtxt, path: &Vec<String>, reg: &node::Reg,
field: &node::Field) -> P<ast::Method>
{
let fn_name = cx.ident_of(field.name.node.as_slice());
let field_ty: P<ast::Ty> =
cx.ty_path(utils::field_type_path(cx, path, reg, field), None);
let mask = utils::mask(cx, field);
let field_doc = match field.docstring {
Some(d) => d.node,
None => cx.ident_of("no documentation"),
};
let docstring = format!("Get value of `{}` field: {}",
field.name.node,
token::get_ident(field_doc).get());
let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring));
if field.count.node == 1 {
let shift = utils::shift(cx, None, field);
let value = from_primitive(
cx, reg, field,
quote_expr!(cx, (self.value >> $shift) & $mask));
quote_method!(cx,
$doc_attr
pub fn $fn_name<'a>(&'a self) -> $field_ty {
$value
}
)
} else {
let shift = utils::shift(cx, Some(quote_expr!(cx, idx)), field);
let value = from_primitive(
cx, reg, field,
quote_expr!(cx, (self.value >> $shift) & $mask));
quote_method!(cx,
$doc_attr
pub fn $fn_name<'a>(&'a self, idx: uint) -> $field_ty {
$value
}
)
}
}
|
cx.ident_of("unwrap"),
Vec::new()
)
},
|
random_line_split
|
getter.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[email protected]>
//
// 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 syntax::ast;
use syntax::ast::P;
use syntax::ext::base::ExtCtxt;
use syntax::codemap::DUMMY_SP;
use syntax::ext::build::AstBuilder;
use syntax::ext::quote::rt::ToTokens;
use syntax::parse::token;
use super::Builder;
use super::super::node;
use super::utils;
/// A visitor to build the field setters for primitive registers
pub struct BuildGetters<'a, 'b, 'c> {
builder: &'a mut Builder,
cx: &'b ExtCtxt<'c>,
}
impl<'a, 'b, 'c> BuildGetters<'a, 'b, 'c> {
pub fn new(builder: &'a mut Builder, cx: &'b ExtCtxt<'c>)
-> BuildGetters<'a, 'b, 'c> {
BuildGetters { builder: builder, cx: cx }
}
}
impl<'a, 'b, 'c> node::RegVisitor for BuildGetters<'a, 'b, 'c> {
fn visit_prim_reg<'a>(&'a mut self, path: &Vec<String>,
reg: &'a node::Reg, _width: node::RegWidth,
fields: &Vec<node::Field>) {
if fields.iter().any(|f| f.access!= node::WriteOnly) {
let it = build_type(self.cx, path, reg);
self.builder.push_item(it);
let it = build_impl(self.cx, path, reg, fields);
self.builder.push_item(it);
}
}
}
fn
|
<'a>(cx: &'a ExtCtxt, path: &Vec<String>,
reg: &node::Reg) -> P<ast::Item>
{
let packed_ty = utils::reg_primitive_type(cx, reg)
.expect("Unexpected non-primitive register");
let name = utils::getter_name(cx, path);
let reg_doc = match reg.docstring {
Some(d) => token::get_ident(d.node).get().into_string(),
None => "no documentation".into_string(),
};
let docstring = format!("`{}`: {}", reg.name.node, reg_doc);
let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring));
let item = quote_item!(cx,
$doc_attr
#[allow(non_camel_case_types)]
pub struct $name {
value: $packed_ty,
}
);
item.unwrap()
}
fn build_new<'a>(cx: &'a ExtCtxt, path: &Vec<String>)
-> P<ast::Item> {
let reg_ty: P<ast::Ty> =
cx.ty_ident(DUMMY_SP, utils::path_ident(cx, path));
let getter_ty: P<ast::Ty> = cx.ty_ident(DUMMY_SP,
utils::getter_name(cx, path));
let item = quote_item!(cx,
#[doc = "Create a getter reflecting the current value of the given register."]
pub fn new(reg: & $reg_ty) -> $getter_ty {
$getter_ty {
value: reg.value.get(),
}
}
);
item.unwrap()
}
/// Given an `Expr` of the given register's primitive type, return
/// an `Expr` of the field type
fn from_primitive<'a>(cx: &'a ExtCtxt, reg: &node::Reg,
field: &node::Field, prim: P<ast::Expr>)
-> P<ast::Expr> {
match field.ty.node {
node::UIntField => prim,
node::BoolField =>
cx.expr_binary(DUMMY_SP, ast::BiNe,
prim, utils::expr_int(cx, 0)),
node::EnumField {..} => {
let from = match reg.ty {
node::RegPrim(width,_) =>
match width {
node::Reg32 => "from_u32",
node::Reg16 => "from_u16",
node::Reg8 => "from_u8",
},
_ => fail!("Can't convert group register to primitive type"),
};
cx.expr_method_call(
DUMMY_SP,
cx.expr_call_global(
DUMMY_SP,
vec!(cx.ident_of("core"),
cx.ident_of("num"),
cx.ident_of(from)),
vec!(prim)
),
cx.ident_of("unwrap"),
Vec::new()
)
},
}
}
fn build_impl(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg,
fields: &Vec<node::Field>) -> P<ast::Item> {
let getter_ty = utils::getter_name(cx, path);
let new = build_new(cx, path);
let getters: Vec<P<ast::Method>> =
FromIterator::from_iter(
fields.iter()
.map(|field| build_field_get_fn(cx, path, reg, field)));
let it = quote_item!(cx,
#[allow(dead_code)]
impl $getter_ty {
$new
$getters
}
);
it.unwrap()
}
/// Build a getter for a field
fn build_field_get_fn<'a>(cx: &'a ExtCtxt, path: &Vec<String>, reg: &node::Reg,
field: &node::Field) -> P<ast::Method>
{
let fn_name = cx.ident_of(field.name.node.as_slice());
let field_ty: P<ast::Ty> =
cx.ty_path(utils::field_type_path(cx, path, reg, field), None);
let mask = utils::mask(cx, field);
let field_doc = match field.docstring {
Some(d) => d.node,
None => cx.ident_of("no documentation"),
};
let docstring = format!("Get value of `{}` field: {}",
field.name.node,
token::get_ident(field_doc).get());
let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring));
if field.count.node == 1 {
let shift = utils::shift(cx, None, field);
let value = from_primitive(
cx, reg, field,
quote_expr!(cx, (self.value >> $shift) & $mask));
quote_method!(cx,
$doc_attr
pub fn $fn_name<'a>(&'a self) -> $field_ty {
$value
}
)
} else {
let shift = utils::shift(cx, Some(quote_expr!(cx, idx)), field);
let value = from_primitive(
cx, reg, field,
quote_expr!(cx, (self.value >> $shift) & $mask));
quote_method!(cx,
$doc_attr
pub fn $fn_name<'a>(&'a self, idx: uint) -> $field_ty {
$value
}
)
}
}
|
build_type
|
identifier_name
|
move-fragments-3.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we correctly compute the move fragments for a fn.
//
// Note that the code below is not actually incorrect; the
// `rustc_move_fragments` attribute is a hack that uses the error
// reporting mechanisms as a channel for communicating from the
// internals of the compiler.
// This checks the handling of `_` within variants, especially when mixed
// with bindings.
#![feature(rustc_attrs)]
use self::Lonely::{Zero, One, Two};
pub struct D { d: isize }
impl Drop for D { fn drop(&mut self)
|
}
pub enum Lonely<X,Y> { Zero, One(X), Two(X, Y) }
#[rustc_move_fragments]
pub fn test_match_bind_and_underscore(p: Lonely<D, D>) {
//~^ ERROR parent_of_fragments: `$(local p)`
//~| ERROR assigned_leaf_path: `($(local p) as Lonely::Zero)`
//~| ERROR assigned_leaf_path: `($(local p) as Lonely::One)`
//~| ERROR parent_of_fragments: `($(local p) as Lonely::Two)`
//~| ERROR moved_leaf_path: `($(local p) as Lonely::Two).#0`
//~| ERROR unmoved_fragment: `($(local p) as Lonely::Two).#1`
//~| ERROR assigned_leaf_path: `$(local left)`
match p {
Zero(..) => {}
One(_) => {} // <-- does not fragment `($(local p) as One)`...
Two(left, _) => {} // <--... *does* fragment `($(local p) as Two)`.
}
}
pub fn main() { }
|
{ }
|
identifier_body
|
move-fragments-3.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we correctly compute the move fragments for a fn.
//
// Note that the code below is not actually incorrect; the
// `rustc_move_fragments` attribute is a hack that uses the error
// reporting mechanisms as a channel for communicating from the
// internals of the compiler.
// This checks the handling of `_` within variants, especially when mixed
// with bindings.
#![feature(rustc_attrs)]
use self::Lonely::{Zero, One, Two};
pub struct D { d: isize }
impl Drop for D { fn drop(&mut self) { } }
pub enum Lonely<X,Y> { Zero, One(X), Two(X, Y) }
#[rustc_move_fragments]
pub fn test_match_bind_and_underscore(p: Lonely<D, D>) {
//~^ ERROR parent_of_fragments: `$(local p)`
//~| ERROR assigned_leaf_path: `($(local p) as Lonely::Zero)`
//~| ERROR assigned_leaf_path: `($(local p) as Lonely::One)`
//~| ERROR parent_of_fragments: `($(local p) as Lonely::Two)`
//~| ERROR moved_leaf_path: `($(local p) as Lonely::Two).#0`
//~| ERROR unmoved_fragment: `($(local p) as Lonely::Two).#1`
//~| ERROR assigned_leaf_path: `$(local left)`
match p {
Zero(..) => {}
One(_) => {} // <-- does not fragment `($(local p) as One)`...
Two(left, _) => {} // <--... *does* fragment `($(local p) as Two)`.
}
}
pub fn
|
() { }
|
main
|
identifier_name
|
move-fragments-3.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
// Test that we correctly compute the move fragments for a fn.
//
// Note that the code below is not actually incorrect; the
// `rustc_move_fragments` attribute is a hack that uses the error
// reporting mechanisms as a channel for communicating from the
// internals of the compiler.
// This checks the handling of `_` within variants, especially when mixed
// with bindings.
#![feature(rustc_attrs)]
use self::Lonely::{Zero, One, Two};
pub struct D { d: isize }
impl Drop for D { fn drop(&mut self) { } }
pub enum Lonely<X,Y> { Zero, One(X), Two(X, Y) }
#[rustc_move_fragments]
pub fn test_match_bind_and_underscore(p: Lonely<D, D>) {
//~^ ERROR parent_of_fragments: `$(local p)`
//~| ERROR assigned_leaf_path: `($(local p) as Lonely::Zero)`
//~| ERROR assigned_leaf_path: `($(local p) as Lonely::One)`
//~| ERROR parent_of_fragments: `($(local p) as Lonely::Two)`
//~| ERROR moved_leaf_path: `($(local p) as Lonely::Two).#0`
//~| ERROR unmoved_fragment: `($(local p) as Lonely::Two).#1`
//~| ERROR assigned_leaf_path: `$(local left)`
match p {
Zero(..) => {}
One(_) => {} // <-- does not fragment `($(local p) as One)`...
Two(left, _) => {} // <--... *does* fragment `($(local p) as Two)`.
}
}
pub fn main() { }
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
random_line_split
|
mod.rs
|
// ams - Advanced Memory Scanner
// Copyright (C) 2018 th0rex
//
// 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/>.
use communication::{Address, MemoryRegion};
pub struct
|
{
pub address: Address,
pub memory_region: MemoryRegion,
}
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "linux")]
pub use self::linux::get_stack_regions;
#[cfg(target_os = "windows")]
pub use self::windows::get_stack_regions;
|
StackRegion
|
identifier_name
|
mod.rs
|
// ams - Advanced Memory Scanner
// Copyright (C) 2018 th0rex
//
// 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/>.
use communication::{Address, MemoryRegion};
pub struct StackRegion {
|
pub memory_region: MemoryRegion,
}
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "linux")]
pub use self::linux::get_stack_regions;
#[cfg(target_os = "windows")]
pub use self::windows::get_stack_regions;
|
pub address: Address,
|
random_line_split
|
primitive.rs
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::mem::size_of;
use crate::{array::ArrayData, datatypes::ArrowNativeType};
use super::{Extend, _MutableArrayData};
pub(super) fn
|
<T: ArrowNativeType>(array: &ArrayData) -> Extend {
let values = &array.buffers()[0].data()[array.offset() * size_of::<T>()..];
Box::new(
move |mutable: &mut _MutableArrayData, _, start: usize, len: usize| {
let start = start * size_of::<T>();
let len = len * size_of::<T>();
let bytes = &values[start..start + len];
let buffer = &mut mutable.buffers[0];
buffer.extend_from_slice(bytes);
},
)
}
|
build_extend
|
identifier_name
|
primitive.rs
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
|
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::mem::size_of;
use crate::{array::ArrayData, datatypes::ArrowNativeType};
use super::{Extend, _MutableArrayData};
pub(super) fn build_extend<T: ArrowNativeType>(array: &ArrayData) -> Extend {
let values = &array.buffers()[0].data()[array.offset() * size_of::<T>()..];
Box::new(
move |mutable: &mut _MutableArrayData, _, start: usize, len: usize| {
let start = start * size_of::<T>();
let len = len * size_of::<T>();
let bytes = &values[start..start + len];
let buffer = &mut mutable.buffers[0];
buffer.extend_from_slice(bytes);
},
)
}
|
random_line_split
|
|
primitive.rs
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::mem::size_of;
use crate::{array::ArrayData, datatypes::ArrowNativeType};
use super::{Extend, _MutableArrayData};
pub(super) fn build_extend<T: ArrowNativeType>(array: &ArrayData) -> Extend
|
{
let values = &array.buffers()[0].data()[array.offset() * size_of::<T>()..];
Box::new(
move |mutable: &mut _MutableArrayData, _, start: usize, len: usize| {
let start = start * size_of::<T>();
let len = len * size_of::<T>();
let bytes = &values[start..start + len];
let buffer = &mut mutable.buffers[0];
buffer.extend_from_slice(bytes);
},
)
}
|
identifier_body
|
|
mod.rs
|
pub mod segment;
use std::path::PathBuf;
use std::fs::File;
use std::path::Path;
use std::fs;
use super::{Storage, StorageError, StorageResult};
use super::{Page, PAGE_SIZE, PageError};
use super::{Row, RowBuilder};
pub use self::segment::Segment;
pub struct Disk {
segment_size: usize, // bytes
pages_per_segment: usize,
directory: PathBuf,
first_segment: u64,
segments: Vec<Segment>,
current_segment: Segment,
// number of the current segment
segment_sequence_id: u64,
flushes: usize,
}
impl Disk {
// dir is the directory of the segments
pub fn new(segment_size_in_mb: usize, dir: PathBuf) -> StorageResult<Disk> {
// create the data directory for this disk storage
fs::create_dir(&dir).expect("Could not create disk storage");
let segment_size = segment_size_in_mb * 1024 * 1024;
let pages_per_segment = segment_size / PAGE_SIZE;
info!("pages per segment: {}", pages_per_segment);
let segment = Disk::open_segment(&dir, 0).expect("Could not open new segment");
Ok(Disk{segment_size: segment_size,
directory: dir,
pages_per_segment: pages_per_segment,
segments: Vec::new(),
first_segment: 0,
current_segment: segment,
segment_sequence_id: 0,
flushes: 0})
}
pub fn open_segment(dir: &PathBuf, segment_id: u64) -> StorageResult<Segment> {
info!("Creating new segment at {:?}", dir);
let segment = Segment::new(&dir, segment_id, 0).expect("Disk Storage: Could not create segment");
Ok(segment)
}
fn set_pages_per_segment(&mut self, pages_per_segment: usize) {
self.pages_per_segment = pages_per_segment;
}
// close the current segment and open a new one
pub fn flush(&mut self) -> StorageResult<()> {
info!("Flushing segment {}", self.segment_sequence_id);
info!("Current segment: {:?}", self.current_segment);
self.segment_sequence_id += 1;
// self.current_segment.close();
let segment = Disk::open_segment(&self.directory, self.segment_sequence_id).expect("Expected segment");
self.current_segment = segment;
self.flushes += 1;
Ok(())
}
}
impl Storage for Disk {
// getting a page requires first getting the right segment
fn get_page(&self, page: u64) -> StorageResult<Page> {
Err(StorageError::PageNotFound)
}
fn write_page(&mut self, page: &Page) -> StorageResult<()> {
self.current_segment.write(&page);
// if the segment is full, flush
if self.current_segment.pages >= self.pages_per_segment
|
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{Disk, Page};
use db::storage::Storage;
use tempdir::TempDir;
fn get_disk_storage() -> Disk {
let mut dir = TempDir::new("disk_storage").expect("Need a temp dir").into_path();
dir.push("stream");
Disk::new(1, dir).expect("Want that disk")
}
#[test]
fn test_disk_flush() {
let mut disk = get_disk_storage();
disk.flush();
assert_eq!(disk.flushes, 1);
disk.flush();
assert_eq!(disk.flushes, 2);
}
#[test]
fn test_disk_writes_segments_correctly() {
let mut disk = get_disk_storage();
disk.set_pages_per_segment(2); // flush after every page
let mut page = Page::new();
let data: [u8; 16] = [0; 16];
page.write(&data);
disk.write_page(&page);
assert_eq!(disk.flushes, 0);
disk.write_page(&page);
assert_eq!(disk.flushes, 1);
disk.get_page(0);
}
}
|
{
self.flush();
}
|
conditional_block
|
mod.rs
|
pub mod segment;
use std::path::PathBuf;
use std::fs::File;
use std::path::Path;
use std::fs;
use super::{Storage, StorageError, StorageResult};
use super::{Page, PAGE_SIZE, PageError};
use super::{Row, RowBuilder};
pub use self::segment::Segment;
pub struct Disk {
segment_size: usize, // bytes
pages_per_segment: usize,
directory: PathBuf,
first_segment: u64,
segments: Vec<Segment>,
current_segment: Segment,
// number of the current segment
segment_sequence_id: u64,
flushes: usize,
}
impl Disk {
// dir is the directory of the segments
pub fn new(segment_size_in_mb: usize, dir: PathBuf) -> StorageResult<Disk> {
// create the data directory for this disk storage
fs::create_dir(&dir).expect("Could not create disk storage");
let segment_size = segment_size_in_mb * 1024 * 1024;
let pages_per_segment = segment_size / PAGE_SIZE;
info!("pages per segment: {}", pages_per_segment);
let segment = Disk::open_segment(&dir, 0).expect("Could not open new segment");
Ok(Disk{segment_size: segment_size,
directory: dir,
pages_per_segment: pages_per_segment,
segments: Vec::new(),
first_segment: 0,
current_segment: segment,
segment_sequence_id: 0,
flushes: 0})
}
pub fn open_segment(dir: &PathBuf, segment_id: u64) -> StorageResult<Segment> {
|
let segment = Segment::new(&dir, segment_id, 0).expect("Disk Storage: Could not create segment");
Ok(segment)
}
fn set_pages_per_segment(&mut self, pages_per_segment: usize) {
self.pages_per_segment = pages_per_segment;
}
// close the current segment and open a new one
pub fn flush(&mut self) -> StorageResult<()> {
info!("Flushing segment {}", self.segment_sequence_id);
info!("Current segment: {:?}", self.current_segment);
self.segment_sequence_id += 1;
// self.current_segment.close();
let segment = Disk::open_segment(&self.directory, self.segment_sequence_id).expect("Expected segment");
self.current_segment = segment;
self.flushes += 1;
Ok(())
}
}
impl Storage for Disk {
// getting a page requires first getting the right segment
fn get_page(&self, page: u64) -> StorageResult<Page> {
Err(StorageError::PageNotFound)
}
fn write_page(&mut self, page: &Page) -> StorageResult<()> {
self.current_segment.write(&page);
// if the segment is full, flush
if self.current_segment.pages >= self.pages_per_segment {
self.flush();
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{Disk, Page};
use db::storage::Storage;
use tempdir::TempDir;
fn get_disk_storage() -> Disk {
let mut dir = TempDir::new("disk_storage").expect("Need a temp dir").into_path();
dir.push("stream");
Disk::new(1, dir).expect("Want that disk")
}
#[test]
fn test_disk_flush() {
let mut disk = get_disk_storage();
disk.flush();
assert_eq!(disk.flushes, 1);
disk.flush();
assert_eq!(disk.flushes, 2);
}
#[test]
fn test_disk_writes_segments_correctly() {
let mut disk = get_disk_storage();
disk.set_pages_per_segment(2); // flush after every page
let mut page = Page::new();
let data: [u8; 16] = [0; 16];
page.write(&data);
disk.write_page(&page);
assert_eq!(disk.flushes, 0);
disk.write_page(&page);
assert_eq!(disk.flushes, 1);
disk.get_page(0);
}
}
|
info!("Creating new segment at {:?}", dir);
|
random_line_split
|
mod.rs
|
pub mod segment;
use std::path::PathBuf;
use std::fs::File;
use std::path::Path;
use std::fs;
use super::{Storage, StorageError, StorageResult};
use super::{Page, PAGE_SIZE, PageError};
use super::{Row, RowBuilder};
pub use self::segment::Segment;
pub struct Disk {
segment_size: usize, // bytes
pages_per_segment: usize,
directory: PathBuf,
first_segment: u64,
segments: Vec<Segment>,
current_segment: Segment,
// number of the current segment
segment_sequence_id: u64,
flushes: usize,
}
impl Disk {
// dir is the directory of the segments
pub fn new(segment_size_in_mb: usize, dir: PathBuf) -> StorageResult<Disk> {
// create the data directory for this disk storage
fs::create_dir(&dir).expect("Could not create disk storage");
let segment_size = segment_size_in_mb * 1024 * 1024;
let pages_per_segment = segment_size / PAGE_SIZE;
info!("pages per segment: {}", pages_per_segment);
let segment = Disk::open_segment(&dir, 0).expect("Could not open new segment");
Ok(Disk{segment_size: segment_size,
directory: dir,
pages_per_segment: pages_per_segment,
segments: Vec::new(),
first_segment: 0,
current_segment: segment,
segment_sequence_id: 0,
flushes: 0})
}
pub fn open_segment(dir: &PathBuf, segment_id: u64) -> StorageResult<Segment> {
info!("Creating new segment at {:?}", dir);
let segment = Segment::new(&dir, segment_id, 0).expect("Disk Storage: Could not create segment");
Ok(segment)
}
fn set_pages_per_segment(&mut self, pages_per_segment: usize) {
self.pages_per_segment = pages_per_segment;
}
// close the current segment and open a new one
pub fn flush(&mut self) -> StorageResult<()> {
info!("Flushing segment {}", self.segment_sequence_id);
info!("Current segment: {:?}", self.current_segment);
self.segment_sequence_id += 1;
// self.current_segment.close();
let segment = Disk::open_segment(&self.directory, self.segment_sequence_id).expect("Expected segment");
self.current_segment = segment;
self.flushes += 1;
Ok(())
}
}
impl Storage for Disk {
// getting a page requires first getting the right segment
fn
|
(&self, page: u64) -> StorageResult<Page> {
Err(StorageError::PageNotFound)
}
fn write_page(&mut self, page: &Page) -> StorageResult<()> {
self.current_segment.write(&page);
// if the segment is full, flush
if self.current_segment.pages >= self.pages_per_segment {
self.flush();
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{Disk, Page};
use db::storage::Storage;
use tempdir::TempDir;
fn get_disk_storage() -> Disk {
let mut dir = TempDir::new("disk_storage").expect("Need a temp dir").into_path();
dir.push("stream");
Disk::new(1, dir).expect("Want that disk")
}
#[test]
fn test_disk_flush() {
let mut disk = get_disk_storage();
disk.flush();
assert_eq!(disk.flushes, 1);
disk.flush();
assert_eq!(disk.flushes, 2);
}
#[test]
fn test_disk_writes_segments_correctly() {
let mut disk = get_disk_storage();
disk.set_pages_per_segment(2); // flush after every page
let mut page = Page::new();
let data: [u8; 16] = [0; 16];
page.write(&data);
disk.write_page(&page);
assert_eq!(disk.flushes, 0);
disk.write_page(&page);
assert_eq!(disk.flushes, 1);
disk.get_page(0);
}
}
|
get_page
|
identifier_name
|
mod.rs
|
pub mod segment;
use std::path::PathBuf;
use std::fs::File;
use std::path::Path;
use std::fs;
use super::{Storage, StorageError, StorageResult};
use super::{Page, PAGE_SIZE, PageError};
use super::{Row, RowBuilder};
pub use self::segment::Segment;
pub struct Disk {
segment_size: usize, // bytes
pages_per_segment: usize,
directory: PathBuf,
first_segment: u64,
segments: Vec<Segment>,
current_segment: Segment,
// number of the current segment
segment_sequence_id: u64,
flushes: usize,
}
impl Disk {
// dir is the directory of the segments
pub fn new(segment_size_in_mb: usize, dir: PathBuf) -> StorageResult<Disk> {
// create the data directory for this disk storage
fs::create_dir(&dir).expect("Could not create disk storage");
let segment_size = segment_size_in_mb * 1024 * 1024;
let pages_per_segment = segment_size / PAGE_SIZE;
info!("pages per segment: {}", pages_per_segment);
let segment = Disk::open_segment(&dir, 0).expect("Could not open new segment");
Ok(Disk{segment_size: segment_size,
directory: dir,
pages_per_segment: pages_per_segment,
segments: Vec::new(),
first_segment: 0,
current_segment: segment,
segment_sequence_id: 0,
flushes: 0})
}
pub fn open_segment(dir: &PathBuf, segment_id: u64) -> StorageResult<Segment> {
info!("Creating new segment at {:?}", dir);
let segment = Segment::new(&dir, segment_id, 0).expect("Disk Storage: Could not create segment");
Ok(segment)
}
fn set_pages_per_segment(&mut self, pages_per_segment: usize) {
self.pages_per_segment = pages_per_segment;
}
// close the current segment and open a new one
pub fn flush(&mut self) -> StorageResult<()> {
info!("Flushing segment {}", self.segment_sequence_id);
info!("Current segment: {:?}", self.current_segment);
self.segment_sequence_id += 1;
// self.current_segment.close();
let segment = Disk::open_segment(&self.directory, self.segment_sequence_id).expect("Expected segment");
self.current_segment = segment;
self.flushes += 1;
Ok(())
}
}
impl Storage for Disk {
// getting a page requires first getting the right segment
fn get_page(&self, page: u64) -> StorageResult<Page>
|
fn write_page(&mut self, page: &Page) -> StorageResult<()> {
self.current_segment.write(&page);
// if the segment is full, flush
if self.current_segment.pages >= self.pages_per_segment {
self.flush();
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{Disk, Page};
use db::storage::Storage;
use tempdir::TempDir;
fn get_disk_storage() -> Disk {
let mut dir = TempDir::new("disk_storage").expect("Need a temp dir").into_path();
dir.push("stream");
Disk::new(1, dir).expect("Want that disk")
}
#[test]
fn test_disk_flush() {
let mut disk = get_disk_storage();
disk.flush();
assert_eq!(disk.flushes, 1);
disk.flush();
assert_eq!(disk.flushes, 2);
}
#[test]
fn test_disk_writes_segments_correctly() {
let mut disk = get_disk_storage();
disk.set_pages_per_segment(2); // flush after every page
let mut page = Page::new();
let data: [u8; 16] = [0; 16];
page.write(&data);
disk.write_page(&page);
assert_eq!(disk.flushes, 0);
disk.write_page(&page);
assert_eq!(disk.flushes, 1);
disk.get_page(0);
}
}
|
{
Err(StorageError::PageNotFound)
}
|
identifier_body
|
condvar.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
|
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use cell::UnsafeCell;
use libc::{self, DWORD};
use sys::c;
use sys::mutex::{self, Mutex};
use sys::os;
use time::Duration;
pub struct Condvar { inner: UnsafeCell<c::CONDITION_VARIABLE> }
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
impl Condvar {
pub const fn new() -> Condvar {
Condvar { inner: UnsafeCell::new(c::CONDITION_VARIABLE_INIT) }
}
#[inline]
pub unsafe fn wait(&self, mutex: &Mutex) {
let r = c::SleepConditionVariableSRW(self.inner.get(),
mutex::raw(mutex),
libc::INFINITE,
0);
debug_assert!(r!= 0);
}
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
let r = c::SleepConditionVariableSRW(self.inner.get(),
mutex::raw(mutex),
super::dur2timeout(dur),
0);
if r == 0 {
const ERROR_TIMEOUT: DWORD = 0x5B4;
debug_assert_eq!(os::errno() as usize, ERROR_TIMEOUT as usize);
false
} else {
true
}
}
#[inline]
pub unsafe fn notify_one(&self) {
c::WakeConditionVariable(self.inner.get())
}
#[inline]
pub unsafe fn notify_all(&self) {
c::WakeAllConditionVariable(self.inner.get())
}
pub unsafe fn destroy(&self) {
//...
}
}
|
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
|
random_line_split
|
condvar.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.
use prelude::v1::*;
use cell::UnsafeCell;
use libc::{self, DWORD};
use sys::c;
use sys::mutex::{self, Mutex};
use sys::os;
use time::Duration;
pub struct Condvar { inner: UnsafeCell<c::CONDITION_VARIABLE> }
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
impl Condvar {
pub const fn new() -> Condvar {
Condvar { inner: UnsafeCell::new(c::CONDITION_VARIABLE_INIT) }
}
#[inline]
pub unsafe fn wait(&self, mutex: &Mutex)
|
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
let r = c::SleepConditionVariableSRW(self.inner.get(),
mutex::raw(mutex),
super::dur2timeout(dur),
0);
if r == 0 {
const ERROR_TIMEOUT: DWORD = 0x5B4;
debug_assert_eq!(os::errno() as usize, ERROR_TIMEOUT as usize);
false
} else {
true
}
}
#[inline]
pub unsafe fn notify_one(&self) {
c::WakeConditionVariable(self.inner.get())
}
#[inline]
pub unsafe fn notify_all(&self) {
c::WakeAllConditionVariable(self.inner.get())
}
pub unsafe fn destroy(&self) {
//...
}
}
|
{
let r = c::SleepConditionVariableSRW(self.inner.get(),
mutex::raw(mutex),
libc::INFINITE,
0);
debug_assert!(r != 0);
}
|
identifier_body
|
condvar.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.
use prelude::v1::*;
use cell::UnsafeCell;
use libc::{self, DWORD};
use sys::c;
use sys::mutex::{self, Mutex};
use sys::os;
use time::Duration;
pub struct Condvar { inner: UnsafeCell<c::CONDITION_VARIABLE> }
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
impl Condvar {
pub const fn new() -> Condvar {
Condvar { inner: UnsafeCell::new(c::CONDITION_VARIABLE_INIT) }
}
#[inline]
pub unsafe fn wait(&self, mutex: &Mutex) {
let r = c::SleepConditionVariableSRW(self.inner.get(),
mutex::raw(mutex),
libc::INFINITE,
0);
debug_assert!(r!= 0);
}
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
let r = c::SleepConditionVariableSRW(self.inner.get(),
mutex::raw(mutex),
super::dur2timeout(dur),
0);
if r == 0
|
else {
true
}
}
#[inline]
pub unsafe fn notify_one(&self) {
c::WakeConditionVariable(self.inner.get())
}
#[inline]
pub unsafe fn notify_all(&self) {
c::WakeAllConditionVariable(self.inner.get())
}
pub unsafe fn destroy(&self) {
//...
}
}
|
{
const ERROR_TIMEOUT: DWORD = 0x5B4;
debug_assert_eq!(os::errno() as usize, ERROR_TIMEOUT as usize);
false
}
|
conditional_block
|
condvar.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.
use prelude::v1::*;
use cell::UnsafeCell;
use libc::{self, DWORD};
use sys::c;
use sys::mutex::{self, Mutex};
use sys::os;
use time::Duration;
pub struct Condvar { inner: UnsafeCell<c::CONDITION_VARIABLE> }
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
impl Condvar {
pub const fn new() -> Condvar {
Condvar { inner: UnsafeCell::new(c::CONDITION_VARIABLE_INIT) }
}
#[inline]
pub unsafe fn
|
(&self, mutex: &Mutex) {
let r = c::SleepConditionVariableSRW(self.inner.get(),
mutex::raw(mutex),
libc::INFINITE,
0);
debug_assert!(r!= 0);
}
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
let r = c::SleepConditionVariableSRW(self.inner.get(),
mutex::raw(mutex),
super::dur2timeout(dur),
0);
if r == 0 {
const ERROR_TIMEOUT: DWORD = 0x5B4;
debug_assert_eq!(os::errno() as usize, ERROR_TIMEOUT as usize);
false
} else {
true
}
}
#[inline]
pub unsafe fn notify_one(&self) {
c::WakeConditionVariable(self.inner.get())
}
#[inline]
pub unsafe fn notify_all(&self) {
c::WakeAllConditionVariable(self.inner.get())
}
pub unsafe fn destroy(&self) {
//...
}
}
|
wait
|
identifier_name
|
error.rs
|
#![allow(trivial_casts)] // Caused by error_chain!
#![allow(missing_docs)] // Caused by error_chain!
#![allow(redundant_closure)] // Caused by error_chain!
pub mod creation {
use MultiHashVariant;
error_chain! {
errors {
LengthTooLong(variant: MultiHashVariant, length: usize) {
description("multihash length too long")
display(
"multihash length {} longer than max length {} for hash kind {}",
length, variant.max_len(), variant.name())
}
UnknownCode(code: usize) {
description("unknown multihash code")
display("unknown multihash code: {}", code)
}
}
}
}
#[cfg(feature = "vec")]
pub mod from_bytes {
use std::io;
use super::creation;
error_chain! {
links {
creation::Error, creation::ErrorKind, Creation;
}
foreign_links {
io::Error, Io;
}
errors {
WrongLengthGiven(length: usize, expected_length: usize) {
description("given slice was the wrong length")
|
length, expected_length)
}
}
}
}
#[cfg(feature = "str")]
pub mod parse {
use bs58;
use super::from_bytes;
error_chain! {
links {
from_bytes::Error, from_bytes::ErrorKind, FromBytes;
}
foreign_links {
bs58::decode::DecodeError, Base58;
}
}
}
|
display(
"given slice had {} bytes of digest but contained a multihash with a {} byte digest",
|
random_line_split
|
send_event_to_device.rs
|
//! `PUT /_matrix/client/*/sendToDevice/{eventType}/{txnId}`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid
use std::collections::BTreeMap;
use ruma_common::{
api::ruma_api, events::AnyToDeviceEventContent, to_device::DeviceIdOrAllDevices,
TransactionId, UserId,
};
use ruma_serde::Raw;
ruma_api! {
metadata: {
description: "Send an event to a device or devices.",
method: PUT,
name: "send_event_to_device",
r0_path: "/_matrix/client/r0/sendToDevice/:event_type/:txn_id",
stable_path: "/_matrix/client/v3/sendToDevice/:event_type/:txn_id",
rate_limited: false,
authentication: AccessToken,
added: 1.0,
}
request: {
/// Type of event being sent to each device.
#[ruma_api(path)]
pub event_type: &'a str,
/// A request identifier unique to the access token used to send the request.
#[ruma_api(path)]
pub txn_id: &'a TransactionId,
/// Messages to send.
///
/// Different message events can be sent to different devices in the same request, but all
/// events within one request must be of the same type.
pub messages: Messages,
}
#[derive(Default)]
response: {}
error: crate::Error
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given event type, transaction ID and raw messages.
pub fn new_raw(event_type: &'a str, txn_id: &'a TransactionId, messages: Messages) -> Self {
Self { event_type, txn_id, messages }
}
}
impl Response {
/// Creates an empty `Response`.
pub fn new() -> Self
|
}
/// Messages to send in a send-to-device request.
///
/// Represented as a map of `{ user-ids => { device-ids => message-content } }`.
pub type Messages =
BTreeMap<Box<UserId>, BTreeMap<DeviceIdOrAllDevices, Raw<AnyToDeviceEventContent>>>;
}
|
{
Self {}
}
|
identifier_body
|
send_event_to_device.rs
|
//! `PUT /_matrix/client/*/sendToDevice/{eventType}/{txnId}`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid
use std::collections::BTreeMap;
use ruma_common::{
api::ruma_api, events::AnyToDeviceEventContent, to_device::DeviceIdOrAllDevices,
TransactionId, UserId,
};
use ruma_serde::Raw;
ruma_api! {
metadata: {
description: "Send an event to a device or devices.",
method: PUT,
name: "send_event_to_device",
r0_path: "/_matrix/client/r0/sendToDevice/:event_type/:txn_id",
stable_path: "/_matrix/client/v3/sendToDevice/:event_type/:txn_id",
rate_limited: false,
authentication: AccessToken,
added: 1.0,
}
request: {
/// Type of event being sent to each device.
#[ruma_api(path)]
pub event_type: &'a str,
/// A request identifier unique to the access token used to send the request.
#[ruma_api(path)]
pub txn_id: &'a TransactionId,
/// Messages to send.
///
/// Different message events can be sent to different devices in the same request, but all
/// events within one request must be of the same type.
pub messages: Messages,
}
#[derive(Default)]
response: {}
error: crate::Error
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given event type, transaction ID and raw messages.
pub fn
|
(event_type: &'a str, txn_id: &'a TransactionId, messages: Messages) -> Self {
Self { event_type, txn_id, messages }
}
}
impl Response {
/// Creates an empty `Response`.
pub fn new() -> Self {
Self {}
}
}
/// Messages to send in a send-to-device request.
///
/// Represented as a map of `{ user-ids => { device-ids => message-content } }`.
pub type Messages =
BTreeMap<Box<UserId>, BTreeMap<DeviceIdOrAllDevices, Raw<AnyToDeviceEventContent>>>;
}
|
new_raw
|
identifier_name
|
send_event_to_device.rs
|
//! `PUT /_matrix/client/*/sendToDevice/{eventType}/{txnId}`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid
use std::collections::BTreeMap;
use ruma_common::{
api::ruma_api, events::AnyToDeviceEventContent, to_device::DeviceIdOrAllDevices,
TransactionId, UserId,
};
use ruma_serde::Raw;
ruma_api! {
metadata: {
description: "Send an event to a device or devices.",
method: PUT,
name: "send_event_to_device",
r0_path: "/_matrix/client/r0/sendToDevice/:event_type/:txn_id",
stable_path: "/_matrix/client/v3/sendToDevice/:event_type/:txn_id",
rate_limited: false,
authentication: AccessToken,
added: 1.0,
}
request: {
/// Type of event being sent to each device.
#[ruma_api(path)]
pub event_type: &'a str,
/// A request identifier unique to the access token used to send the request.
#[ruma_api(path)]
pub txn_id: &'a TransactionId,
/// Messages to send.
///
/// Different message events can be sent to different devices in the same request, but all
/// events within one request must be of the same type.
pub messages: Messages,
}
#[derive(Default)]
response: {}
error: crate::Error
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given event type, transaction ID and raw messages.
pub fn new_raw(event_type: &'a str, txn_id: &'a TransactionId, messages: Messages) -> Self {
Self { event_type, txn_id, messages }
}
}
impl Response {
/// Creates an empty `Response`.
pub fn new() -> Self {
|
Self {}
}
}
/// Messages to send in a send-to-device request.
///
/// Represented as a map of `{ user-ids => { device-ids => message-content } }`.
pub type Messages =
BTreeMap<Box<UserId>, BTreeMap<DeviceIdOrAllDevices, Raw<AnyToDeviceEventContent>>>;
}
|
random_line_split
|
|
music.rs
|
use replies::ReplyRenderer;
use utils::current_timestamp;
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct MusicReply {
pub source: String,
pub target: String,
pub time: i64,
pub thumb_media_id: String,
pub title: String,
pub description: String,
pub music_url: String,
pub hq_music_url: String,
}
impl MusicReply {
#[inline]
pub fn new<S: Into<String>>(source: S, target: S, thumb_media_id: S) -> MusicReply {
MusicReply {
source: source.into(),
target: target.into(),
time: current_timestamp(),
thumb_media_id: thumb_media_id.into(),
title: "".to_owned(),
description: "".to_owned(),
music_url: "".to_owned(),
hq_music_url: "".to_owned(),
}
}
}
impl ReplyRenderer for MusicReply {
#[inline]
fn render(&self) -> String {
format!("<xml>\n\
<ToUserName><![CDATA[{target}]]></ToUserName>\n\
<FromUserName><![CDATA[{source}]]></FromUserName>\n\
<CreateTime>{time}</CreateTime>\n\
<MsgType><![CDATA[music]]></MsgType>\n\
<Music>\n\
<ThumbMediaId><![CDATA[{thumb_media_id}]]></ThumbMediaId>\n\
<Title><![CDATA[{title}]]></Title>\n\
|
</xml>",
target=self.target,
source=self.source,
time=self.time,
thumb_media_id=self.thumb_media_id,
title=self.title,
description=self.description,
music_url=self.music_url,
hq_music_url=self.hq_music_url,
)
}
}
#[cfg(test)]
mod tests {
use replies::ReplyRenderer;
use super::MusicReply;
#[test]
fn test_render_music_reply() {
let reply = MusicReply::new("test1", "test2", "test");
let rendered = reply.render();
assert!(rendered.contains("test1"));
assert!(rendered.contains("test2"));
assert!(rendered.contains("test"));
}
}
|
<Description><![CDATA[{description}]]></Description>\n\
<MusicUrl><![CDATA[{music_url}]]></MusicUrl>\n\
<HQMusicUrl><![CDATA[{hq_music_url}]]></HQMusicUrl>\n\
</Music>\n\
|
random_line_split
|
music.rs
|
use replies::ReplyRenderer;
use utils::current_timestamp;
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct MusicReply {
pub source: String,
pub target: String,
pub time: i64,
pub thumb_media_id: String,
pub title: String,
pub description: String,
pub music_url: String,
pub hq_music_url: String,
}
impl MusicReply {
#[inline]
pub fn
|
<S: Into<String>>(source: S, target: S, thumb_media_id: S) -> MusicReply {
MusicReply {
source: source.into(),
target: target.into(),
time: current_timestamp(),
thumb_media_id: thumb_media_id.into(),
title: "".to_owned(),
description: "".to_owned(),
music_url: "".to_owned(),
hq_music_url: "".to_owned(),
}
}
}
impl ReplyRenderer for MusicReply {
#[inline]
fn render(&self) -> String {
format!("<xml>\n\
<ToUserName><![CDATA[{target}]]></ToUserName>\n\
<FromUserName><![CDATA[{source}]]></FromUserName>\n\
<CreateTime>{time}</CreateTime>\n\
<MsgType><![CDATA[music]]></MsgType>\n\
<Music>\n\
<ThumbMediaId><![CDATA[{thumb_media_id}]]></ThumbMediaId>\n\
<Title><![CDATA[{title}]]></Title>\n\
<Description><![CDATA[{description}]]></Description>\n\
<MusicUrl><![CDATA[{music_url}]]></MusicUrl>\n\
<HQMusicUrl><![CDATA[{hq_music_url}]]></HQMusicUrl>\n\
</Music>\n\
</xml>",
target=self.target,
source=self.source,
time=self.time,
thumb_media_id=self.thumb_media_id,
title=self.title,
description=self.description,
music_url=self.music_url,
hq_music_url=self.hq_music_url,
)
}
}
#[cfg(test)]
mod tests {
use replies::ReplyRenderer;
use super::MusicReply;
#[test]
fn test_render_music_reply() {
let reply = MusicReply::new("test1", "test2", "test");
let rendered = reply.render();
assert!(rendered.contains("test1"));
assert!(rendered.contains("test2"));
assert!(rendered.contains("test"));
}
}
|
new
|
identifier_name
|
problem-0025.rs
|
/// Problem 25
/// The Fibonacci sequence is defined by the recurrence relation:
///
/// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
/// Hence the first 12 terms will be:
///
/// F1 = 1
/// F2 = 1
/// F3 = 2
/// F4 = 3
/// F5 = 5
/// F6 = 8
/// F7 = 13
/// F8 = 21
/// F9 = 34
|
/// The 12th term, F12, is the first term to contain three digits.
///
/// What is the index of the first term in the Fibonacci sequence to contain
/// 1000 digits?
fn main() {
let mut a: Vec<u8> = vec![1];
let mut b: Vec<u8> = vec![1];
let mut c: Vec<u8> = vec![2];
let mut i: u64 = 3;
loop {
// Vector digit addition
let mut rem: u8 = 0;
c.clear();
let mut j = 0;
loop {
let mut s = rem;
if j < a.len() {
s += a[j];
}
if j < b.len() {
s += b[j];
}
c.push(s%10);
rem = s / 10;
j += 1;
if j >= a.len() && j >= b.len() && rem == 0 {
break
}
}
if c.len() >= 1000 {
println!("Answer: {}", i);
// println!("{:?}", c);
break
}
a = b.to_vec();
b = c.to_vec();
i += 1;
}
}
|
/// F10 = 55
/// F11 = 89
/// F12 = 144
///
|
random_line_split
|
problem-0025.rs
|
/// Problem 25
/// The Fibonacci sequence is defined by the recurrence relation:
///
/// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
/// Hence the first 12 terms will be:
///
/// F1 = 1
/// F2 = 1
/// F3 = 2
/// F4 = 3
/// F5 = 5
/// F6 = 8
/// F7 = 13
/// F8 = 21
/// F9 = 34
/// F10 = 55
/// F11 = 89
/// F12 = 144
///
/// The 12th term, F12, is the first term to contain three digits.
///
/// What is the index of the first term in the Fibonacci sequence to contain
/// 1000 digits?
fn main() {
l
|
if j >= a.len() && j >= b.len() && rem == 0 {
break
}
}
if c.len() >= 1000 {
println!("Answer: {}", i);
// println!("{:?}", c);
break
}
a = b.to_vec();
b = c.to_vec();
i += 1;
}
}
|
et mut a: Vec<u8> = vec![1];
let mut b: Vec<u8> = vec![1];
let mut c: Vec<u8> = vec![2];
let mut i: u64 = 3;
loop {
// Vector digit addition
let mut rem: u8 = 0;
c.clear();
let mut j = 0;
loop {
let mut s = rem;
if j < a.len() {
s += a[j];
}
if j < b.len() {
s += b[j];
}
c.push(s%10);
rem = s / 10;
j += 1;
|
identifier_body
|
problem-0025.rs
|
/// Problem 25
/// The Fibonacci sequence is defined by the recurrence relation:
///
/// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
/// Hence the first 12 terms will be:
///
/// F1 = 1
/// F2 = 1
/// F3 = 2
/// F4 = 3
/// F5 = 5
/// F6 = 8
/// F7 = 13
/// F8 = 21
/// F9 = 34
/// F10 = 55
/// F11 = 89
/// F12 = 144
///
/// The 12th term, F12, is the first term to contain three digits.
///
/// What is the index of the first term in the Fibonacci sequence to contain
/// 1000 digits?
fn main() {
let mut a: Vec<u8> = vec![1];
let mut b: Vec<u8> = vec![1];
let mut c: Vec<u8> = vec![2];
let mut i: u64 = 3;
loop {
// Vector digit addition
let mut rem: u8 = 0;
c.clear();
let mut j = 0;
loop {
let mut s = rem;
if j < a.len() {
|
if j < b.len() {
s += b[j];
}
c.push(s%10);
rem = s / 10;
j += 1;
if j >= a.len() && j >= b.len() && rem == 0 {
break
}
}
if c.len() >= 1000 {
println!("Answer: {}", i);
// println!("{:?}", c);
break
}
a = b.to_vec();
b = c.to_vec();
i += 1;
}
}
|
s += a[j];
}
|
conditional_block
|
problem-0025.rs
|
/// Problem 25
/// The Fibonacci sequence is defined by the recurrence relation:
///
/// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
/// Hence the first 12 terms will be:
///
/// F1 = 1
/// F2 = 1
/// F3 = 2
/// F4 = 3
/// F5 = 5
/// F6 = 8
/// F7 = 13
/// F8 = 21
/// F9 = 34
/// F10 = 55
/// F11 = 89
/// F12 = 144
///
/// The 12th term, F12, is the first term to contain three digits.
///
/// What is the index of the first term in the Fibonacci sequence to contain
/// 1000 digits?
fn main
|
let mut a: Vec<u8> = vec![1];
let mut b: Vec<u8> = vec![1];
let mut c: Vec<u8> = vec![2];
let mut i: u64 = 3;
loop {
// Vector digit addition
let mut rem: u8 = 0;
c.clear();
let mut j = 0;
loop {
let mut s = rem;
if j < a.len() {
s += a[j];
}
if j < b.len() {
s += b[j];
}
c.push(s%10);
rem = s / 10;
j += 1;
if j >= a.len() && j >= b.len() && rem == 0 {
break
}
}
if c.len() >= 1000 {
println!("Answer: {}", i);
// println!("{:?}", c);
break
}
a = b.to_vec();
b = c.to_vec();
i += 1;
}
}
|
() {
|
identifier_name
|
sqlite_string.rs
|
// This is used when either vtab or modern-sqlite is on. Different methods are
// used in each feature. Avoid having to track this for each function. We will
// still warn for anything that's not used by either, though.
#![cfg_attr(
not(all(feature = "vtab", feature = "modern-sqlite")),
allow(dead_code)
)]
use crate::ffi;
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int};
use std::ptr::NonNull;
/// A string we own that's allocated on the SQLite heap. Automatically calls
/// `sqlite3_free` when dropped, unless `into_raw` (or `into_inner`) is called
/// on it. If constructed from a rust string, `sqlite3_malloc` is used.
///
/// It has identical representation to a nonnull `*mut c_char`, so you can use
/// it transparently as one. It's nonnull, so Option<SqliteMallocString> can be
/// used for nullable ones (it's still just one pointer).
///
/// Most strings shouldn't use this! Only places where the string needs to be
/// freed with `sqlite3_free`. This includes `sqlite3_extended_sql` results,
/// some error message pointers... Note that misuse is extremely dangerous!
///
/// Note that this is *not* a lossless interface. Incoming strings with internal
/// NULs are modified, and outgoing strings which are non-UTF8 are modified.
/// This seems unavoidable -- it tries very hard to not panic.
#[repr(transparent)]
pub(crate) struct SqliteMallocString {
ptr: NonNull<c_char>,
_boo: PhantomData<Box<[c_char]>>,
}
// This is owned data for a primitive type, and thus it's safe to implement
// these. That said, nothing needs them, and they make things easier to misuse.
// unsafe impl Send for SqliteMallocString {}
// unsafe impl Sync for SqliteMallocString {}
impl SqliteMallocString {
/// SAFETY: Caller must be certain that `m` a nul-terminated c string
/// allocated by sqlite3_malloc, and that SQLite expects us to free it!
#[inline]
pub(crate) unsafe fn from_raw_nonnull(ptr: NonNull<c_char>) -> Self {
Self {
ptr,
_boo: PhantomData,
}
}
/// SAFETY: Caller must be certain that `m` a nul-terminated c string
/// allocated by sqlite3_malloc, and that SQLite expects us to free it!
#[inline]
pub(crate) unsafe fn from_raw(ptr: *mut c_char) -> Option<Self> {
NonNull::new(ptr).map(|p| Self::from_raw_nonnull(p))
}
/// Get the pointer behind `self`. After this is called, we no longer manage
/// it.
#[inline]
pub(crate) fn into_inner(self) -> NonNull<c_char> {
let p = self.ptr;
std::mem::forget(self);
p
}
/// Get the pointer behind `self`. After this is called, we no longer manage
/// it.
#[inline]
pub(crate) fn into_raw(self) -> *mut c_char {
self.into_inner().as_ptr()
}
/// Borrow the pointer behind `self`. We still manage it when this function
/// returns. If you want to relinquish ownership, use `into_raw`.
#[inline]
pub(crate) fn as_ptr(&self) -> *const c_char {
self.ptr.as_ptr()
}
#[inline]
pub(crate) fn as_cstr(&self) -> &std::ffi::CStr {
unsafe { std::ffi::CStr::from_ptr(self.as_ptr()) }
}
#[inline]
pub(crate) fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
self.as_cstr().to_string_lossy()
}
/// Convert `s` into a SQLite string.
///
/// This should almost never be done except for cases like error messages or
/// other strings that SQLite frees.
///
/// If `s` contains internal NULs, we'll replace them with
/// `NUL_REPLACE_CHAR`.
///
/// Except for debug_asserts which may trigger during testing, this function
/// never panics. If we hit integer overflow or the allocation fails, we
/// call `handle_alloc_error` which aborts the program after calling a
/// global hook.
///
/// This means it's safe to use in extern "C" functions even outside of
/// catch_unwind.
pub(crate) fn from_str(s: &str) -> Self {
use std::convert::TryFrom;
let s = if s.as_bytes().contains(&0) {
std::borrow::Cow::Owned(make_nonnull(s))
} else {
std::borrow::Cow::Borrowed(s)
};
debug_assert!(!s.as_bytes().contains(&0));
let bytes: &[u8] = s.as_ref().as_bytes();
let src_ptr: *const c_char = bytes.as_ptr().cast();
let src_len = bytes.len();
let maybe_len_plus_1 = s.len().checked_add(1).and_then(|v| c_int::try_from(v).ok());
unsafe {
let res_ptr = maybe_len_plus_1
.and_then(|len_to_alloc| {
// `>` because we added 1.
debug_assert!(len_to_alloc > 0);
debug_assert_eq!((len_to_alloc - 1) as usize, src_len);
NonNull::new(ffi::sqlite3_malloc(len_to_alloc) as *mut c_char)
})
.unwrap_or_else(|| {
use std::alloc::{handle_alloc_error, Layout};
// Report via handle_alloc_error so that it can be handled with any
// other allocation errors and properly diagnosed.
//
// This is safe:
// - `align` is never 0
// - `align` is always a power of 2.
// - `size` needs no realignment because it's guaranteed to be aligned
// (everything is aligned to 1)
// - `size` is also never zero, although this function doesn't actually require
// it now.
let layout = Layout::from_size_align_unchecked(s.len().saturating_add(1), 1);
// Note: This call does not return.
handle_alloc_error(layout);
});
let buf: *mut c_char = res_ptr.as_ptr() as *mut c_char;
src_ptr.copy_to_nonoverlapping(buf, src_len);
buf.add(src_len).write(0);
debug_assert_eq!(std::ffi::CStr::from_ptr(res_ptr.as_ptr()).to_bytes(), bytes);
Self::from_raw_nonnull(res_ptr)
}
}
}
const NUL_REPLACE: &str = "␀";
#[cold]
fn make_nonnull(v: &str) -> String {
v.replace('\0', NUL_REPLACE)
}
impl Drop for SqliteMallocString {
#[inline]
fn drop(&mut self) {
unsafe { ffi::sqlite3_free(self.ptr.as_ptr().cast()) };
}
|
impl std::fmt::Debug for SqliteMallocString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_string_lossy().fmt(f)
}
}
impl std::fmt::Display for SqliteMallocString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_string_lossy().fmt(f)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_from_str() {
let to_check = [
("", ""),
("\0", "␀"),
("␀", "␀"),
("\0bar", "␀bar"),
("foo\0bar", "foo␀bar"),
("foo\0", "foo␀"),
("a\0b\0c\0\0d", "a␀b␀c␀␀d"),
("foobar0123", "foobar0123"),
];
for &(input, output) in &to_check {
let s = SqliteMallocString::from_str(input);
assert_eq!(s.to_string_lossy(), output);
assert_eq!(s.as_cstr().to_str().unwrap(), output);
}
}
// This will trigger an asan error if into_raw still freed the ptr.
#[test]
fn test_lossy() {
let p = SqliteMallocString::from_str("abcd").into_raw();
// Make invalid
let s = unsafe {
p.cast::<u8>().write(b'\xff');
SqliteMallocString::from_raw(p).unwrap()
};
assert_eq!(s.to_string_lossy().as_ref(), "\u{FFFD}bcd");
}
// This will trigger an asan error if into_raw still freed the ptr.
#[test]
fn test_into_raw() {
let mut v = vec![];
for i in 0..1000 {
v.push(SqliteMallocString::from_str(&i.to_string()).into_raw());
v.push(SqliteMallocString::from_str(&format!("abc {} 😀", i)).into_raw());
}
unsafe {
for (i, s) in v.chunks_mut(2).enumerate() {
let s0 = std::mem::replace(&mut s[0], std::ptr::null_mut());
let s1 = std::mem::replace(&mut s[1], std::ptr::null_mut());
assert_eq!(
std::ffi::CStr::from_ptr(s0).to_str().unwrap(),
&i.to_string()
);
assert_eq!(
std::ffi::CStr::from_ptr(s1).to_str().unwrap(),
&format!("abc {} 😀", i)
);
let _ = SqliteMallocString::from_raw(s0).unwrap();
let _ = SqliteMallocString::from_raw(s1).unwrap();
}
}
}
}
|
}
|
random_line_split
|
sqlite_string.rs
|
// This is used when either vtab or modern-sqlite is on. Different methods are
// used in each feature. Avoid having to track this for each function. We will
// still warn for anything that's not used by either, though.
#![cfg_attr(
not(all(feature = "vtab", feature = "modern-sqlite")),
allow(dead_code)
)]
use crate::ffi;
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int};
use std::ptr::NonNull;
/// A string we own that's allocated on the SQLite heap. Automatically calls
/// `sqlite3_free` when dropped, unless `into_raw` (or `into_inner`) is called
/// on it. If constructed from a rust string, `sqlite3_malloc` is used.
///
/// It has identical representation to a nonnull `*mut c_char`, so you can use
/// it transparently as one. It's nonnull, so Option<SqliteMallocString> can be
/// used for nullable ones (it's still just one pointer).
///
/// Most strings shouldn't use this! Only places where the string needs to be
/// freed with `sqlite3_free`. This includes `sqlite3_extended_sql` results,
/// some error message pointers... Note that misuse is extremely dangerous!
///
/// Note that this is *not* a lossless interface. Incoming strings with internal
/// NULs are modified, and outgoing strings which are non-UTF8 are modified.
/// This seems unavoidable -- it tries very hard to not panic.
#[repr(transparent)]
pub(crate) struct SqliteMallocString {
ptr: NonNull<c_char>,
_boo: PhantomData<Box<[c_char]>>,
}
// This is owned data for a primitive type, and thus it's safe to implement
// these. That said, nothing needs them, and they make things easier to misuse.
// unsafe impl Send for SqliteMallocString {}
// unsafe impl Sync for SqliteMallocString {}
impl SqliteMallocString {
/// SAFETY: Caller must be certain that `m` a nul-terminated c string
/// allocated by sqlite3_malloc, and that SQLite expects us to free it!
#[inline]
pub(crate) unsafe fn from_raw_nonnull(ptr: NonNull<c_char>) -> Self {
Self {
ptr,
_boo: PhantomData,
}
}
/// SAFETY: Caller must be certain that `m` a nul-terminated c string
/// allocated by sqlite3_malloc, and that SQLite expects us to free it!
#[inline]
pub(crate) unsafe fn from_raw(ptr: *mut c_char) -> Option<Self> {
NonNull::new(ptr).map(|p| Self::from_raw_nonnull(p))
}
/// Get the pointer behind `self`. After this is called, we no longer manage
/// it.
#[inline]
pub(crate) fn into_inner(self) -> NonNull<c_char> {
let p = self.ptr;
std::mem::forget(self);
p
}
/// Get the pointer behind `self`. After this is called, we no longer manage
/// it.
#[inline]
pub(crate) fn into_raw(self) -> *mut c_char {
self.into_inner().as_ptr()
}
/// Borrow the pointer behind `self`. We still manage it when this function
/// returns. If you want to relinquish ownership, use `into_raw`.
#[inline]
pub(crate) fn as_ptr(&self) -> *const c_char {
self.ptr.as_ptr()
}
#[inline]
pub(crate) fn as_cstr(&self) -> &std::ffi::CStr {
unsafe { std::ffi::CStr::from_ptr(self.as_ptr()) }
}
#[inline]
pub(crate) fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
self.as_cstr().to_string_lossy()
}
/// Convert `s` into a SQLite string.
///
/// This should almost never be done except for cases like error messages or
/// other strings that SQLite frees.
///
/// If `s` contains internal NULs, we'll replace them with
/// `NUL_REPLACE_CHAR`.
///
/// Except for debug_asserts which may trigger during testing, this function
/// never panics. If we hit integer overflow or the allocation fails, we
/// call `handle_alloc_error` which aborts the program after calling a
/// global hook.
///
/// This means it's safe to use in extern "C" functions even outside of
/// catch_unwind.
pub(crate) fn from_str(s: &str) -> Self {
use std::convert::TryFrom;
let s = if s.as_bytes().contains(&0)
|
else {
std::borrow::Cow::Borrowed(s)
};
debug_assert!(!s.as_bytes().contains(&0));
let bytes: &[u8] = s.as_ref().as_bytes();
let src_ptr: *const c_char = bytes.as_ptr().cast();
let src_len = bytes.len();
let maybe_len_plus_1 = s.len().checked_add(1).and_then(|v| c_int::try_from(v).ok());
unsafe {
let res_ptr = maybe_len_plus_1
.and_then(|len_to_alloc| {
// `>` because we added 1.
debug_assert!(len_to_alloc > 0);
debug_assert_eq!((len_to_alloc - 1) as usize, src_len);
NonNull::new(ffi::sqlite3_malloc(len_to_alloc) as *mut c_char)
})
.unwrap_or_else(|| {
use std::alloc::{handle_alloc_error, Layout};
// Report via handle_alloc_error so that it can be handled with any
// other allocation errors and properly diagnosed.
//
// This is safe:
// - `align` is never 0
// - `align` is always a power of 2.
// - `size` needs no realignment because it's guaranteed to be aligned
// (everything is aligned to 1)
// - `size` is also never zero, although this function doesn't actually require
// it now.
let layout = Layout::from_size_align_unchecked(s.len().saturating_add(1), 1);
// Note: This call does not return.
handle_alloc_error(layout);
});
let buf: *mut c_char = res_ptr.as_ptr() as *mut c_char;
src_ptr.copy_to_nonoverlapping(buf, src_len);
buf.add(src_len).write(0);
debug_assert_eq!(std::ffi::CStr::from_ptr(res_ptr.as_ptr()).to_bytes(), bytes);
Self::from_raw_nonnull(res_ptr)
}
}
}
const NUL_REPLACE: &str = "␀";
#[cold]
fn make_nonnull(v: &str) -> String {
v.replace('\0', NUL_REPLACE)
}
impl Drop for SqliteMallocString {
#[inline]
fn drop(&mut self) {
unsafe { ffi::sqlite3_free(self.ptr.as_ptr().cast()) };
}
}
impl std::fmt::Debug for SqliteMallocString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_string_lossy().fmt(f)
}
}
impl std::fmt::Display for SqliteMallocString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_string_lossy().fmt(f)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_from_str() {
let to_check = [
("", ""),
("\0", "␀"),
("␀", "␀"),
("\0bar", "␀bar"),
("foo\0bar", "foo␀bar"),
("foo\0", "foo␀"),
("a\0b\0c\0\0d", "a␀b␀c␀␀d"),
("foobar0123", "foobar0123"),
];
for &(input, output) in &to_check {
let s = SqliteMallocString::from_str(input);
assert_eq!(s.to_string_lossy(), output);
assert_eq!(s.as_cstr().to_str().unwrap(), output);
}
}
// This will trigger an asan error if into_raw still freed the ptr.
#[test]
fn test_lossy() {
let p = SqliteMallocString::from_str("abcd").into_raw();
// Make invalid
let s = unsafe {
p.cast::<u8>().write(b'\xff');
SqliteMallocString::from_raw(p).unwrap()
};
assert_eq!(s.to_string_lossy().as_ref(), "\u{FFFD}bcd");
}
// This will trigger an asan error if into_raw still freed the ptr.
#[test]
fn test_into_raw() {
let mut v = vec![];
for i in 0..1000 {
v.push(SqliteMallocString::from_str(&i.to_string()).into_raw());
v.push(SqliteMallocString::from_str(&format!("abc {} 😀", i)).into_raw());
}
unsafe {
for (i, s) in v.chunks_mut(2).enumerate() {
let s0 = std::mem::replace(&mut s[0], std::ptr::null_mut());
let s1 = std::mem::replace(&mut s[1], std::ptr::null_mut());
assert_eq!(
std::ffi::CStr::from_ptr(s0).to_str().unwrap(),
&i.to_string()
);
assert_eq!(
std::ffi::CStr::from_ptr(s1).to_str().unwrap(),
&format!("abc {} 😀", i)
);
let _ = SqliteMallocString::from_raw(s0).unwrap();
let _ = SqliteMallocString::from_raw(s1).unwrap();
}
}
}
}
|
{
std::borrow::Cow::Owned(make_nonnull(s))
}
|
conditional_block
|
sqlite_string.rs
|
// This is used when either vtab or modern-sqlite is on. Different methods are
// used in each feature. Avoid having to track this for each function. We will
// still warn for anything that's not used by either, though.
#![cfg_attr(
not(all(feature = "vtab", feature = "modern-sqlite")),
allow(dead_code)
)]
use crate::ffi;
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int};
use std::ptr::NonNull;
/// A string we own that's allocated on the SQLite heap. Automatically calls
/// `sqlite3_free` when dropped, unless `into_raw` (or `into_inner`) is called
/// on it. If constructed from a rust string, `sqlite3_malloc` is used.
///
/// It has identical representation to a nonnull `*mut c_char`, so you can use
/// it transparently as one. It's nonnull, so Option<SqliteMallocString> can be
/// used for nullable ones (it's still just one pointer).
///
/// Most strings shouldn't use this! Only places where the string needs to be
/// freed with `sqlite3_free`. This includes `sqlite3_extended_sql` results,
/// some error message pointers... Note that misuse is extremely dangerous!
///
/// Note that this is *not* a lossless interface. Incoming strings with internal
/// NULs are modified, and outgoing strings which are non-UTF8 are modified.
/// This seems unavoidable -- it tries very hard to not panic.
#[repr(transparent)]
pub(crate) struct SqliteMallocString {
ptr: NonNull<c_char>,
_boo: PhantomData<Box<[c_char]>>,
}
// This is owned data for a primitive type, and thus it's safe to implement
// these. That said, nothing needs them, and they make things easier to misuse.
// unsafe impl Send for SqliteMallocString {}
// unsafe impl Sync for SqliteMallocString {}
impl SqliteMallocString {
/// SAFETY: Caller must be certain that `m` a nul-terminated c string
/// allocated by sqlite3_malloc, and that SQLite expects us to free it!
#[inline]
pub(crate) unsafe fn from_raw_nonnull(ptr: NonNull<c_char>) -> Self {
Self {
ptr,
_boo: PhantomData,
}
}
/// SAFETY: Caller must be certain that `m` a nul-terminated c string
/// allocated by sqlite3_malloc, and that SQLite expects us to free it!
#[inline]
pub(crate) unsafe fn from_raw(ptr: *mut c_char) -> Option<Self> {
NonNull::new(ptr).map(|p| Self::from_raw_nonnull(p))
}
/// Get the pointer behind `self`. After this is called, we no longer manage
/// it.
#[inline]
pub(crate) fn into_inner(self) -> NonNull<c_char> {
let p = self.ptr;
std::mem::forget(self);
p
}
/// Get the pointer behind `self`. After this is called, we no longer manage
/// it.
#[inline]
pub(crate) fn
|
(self) -> *mut c_char {
self.into_inner().as_ptr()
}
/// Borrow the pointer behind `self`. We still manage it when this function
/// returns. If you want to relinquish ownership, use `into_raw`.
#[inline]
pub(crate) fn as_ptr(&self) -> *const c_char {
self.ptr.as_ptr()
}
#[inline]
pub(crate) fn as_cstr(&self) -> &std::ffi::CStr {
unsafe { std::ffi::CStr::from_ptr(self.as_ptr()) }
}
#[inline]
pub(crate) fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
self.as_cstr().to_string_lossy()
}
/// Convert `s` into a SQLite string.
///
/// This should almost never be done except for cases like error messages or
/// other strings that SQLite frees.
///
/// If `s` contains internal NULs, we'll replace them with
/// `NUL_REPLACE_CHAR`.
///
/// Except for debug_asserts which may trigger during testing, this function
/// never panics. If we hit integer overflow or the allocation fails, we
/// call `handle_alloc_error` which aborts the program after calling a
/// global hook.
///
/// This means it's safe to use in extern "C" functions even outside of
/// catch_unwind.
pub(crate) fn from_str(s: &str) -> Self {
use std::convert::TryFrom;
let s = if s.as_bytes().contains(&0) {
std::borrow::Cow::Owned(make_nonnull(s))
} else {
std::borrow::Cow::Borrowed(s)
};
debug_assert!(!s.as_bytes().contains(&0));
let bytes: &[u8] = s.as_ref().as_bytes();
let src_ptr: *const c_char = bytes.as_ptr().cast();
let src_len = bytes.len();
let maybe_len_plus_1 = s.len().checked_add(1).and_then(|v| c_int::try_from(v).ok());
unsafe {
let res_ptr = maybe_len_plus_1
.and_then(|len_to_alloc| {
// `>` because we added 1.
debug_assert!(len_to_alloc > 0);
debug_assert_eq!((len_to_alloc - 1) as usize, src_len);
NonNull::new(ffi::sqlite3_malloc(len_to_alloc) as *mut c_char)
})
.unwrap_or_else(|| {
use std::alloc::{handle_alloc_error, Layout};
// Report via handle_alloc_error so that it can be handled with any
// other allocation errors and properly diagnosed.
//
// This is safe:
// - `align` is never 0
// - `align` is always a power of 2.
// - `size` needs no realignment because it's guaranteed to be aligned
// (everything is aligned to 1)
// - `size` is also never zero, although this function doesn't actually require
// it now.
let layout = Layout::from_size_align_unchecked(s.len().saturating_add(1), 1);
// Note: This call does not return.
handle_alloc_error(layout);
});
let buf: *mut c_char = res_ptr.as_ptr() as *mut c_char;
src_ptr.copy_to_nonoverlapping(buf, src_len);
buf.add(src_len).write(0);
debug_assert_eq!(std::ffi::CStr::from_ptr(res_ptr.as_ptr()).to_bytes(), bytes);
Self::from_raw_nonnull(res_ptr)
}
}
}
const NUL_REPLACE: &str = "␀";
#[cold]
fn make_nonnull(v: &str) -> String {
v.replace('\0', NUL_REPLACE)
}
impl Drop for SqliteMallocString {
#[inline]
fn drop(&mut self) {
unsafe { ffi::sqlite3_free(self.ptr.as_ptr().cast()) };
}
}
impl std::fmt::Debug for SqliteMallocString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_string_lossy().fmt(f)
}
}
impl std::fmt::Display for SqliteMallocString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_string_lossy().fmt(f)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_from_str() {
let to_check = [
("", ""),
("\0", "␀"),
("␀", "␀"),
("\0bar", "␀bar"),
("foo\0bar", "foo␀bar"),
("foo\0", "foo␀"),
("a\0b\0c\0\0d", "a␀b␀c␀␀d"),
("foobar0123", "foobar0123"),
];
for &(input, output) in &to_check {
let s = SqliteMallocString::from_str(input);
assert_eq!(s.to_string_lossy(), output);
assert_eq!(s.as_cstr().to_str().unwrap(), output);
}
}
// This will trigger an asan error if into_raw still freed the ptr.
#[test]
fn test_lossy() {
let p = SqliteMallocString::from_str("abcd").into_raw();
// Make invalid
let s = unsafe {
p.cast::<u8>().write(b'\xff');
SqliteMallocString::from_raw(p).unwrap()
};
assert_eq!(s.to_string_lossy().as_ref(), "\u{FFFD}bcd");
}
// This will trigger an asan error if into_raw still freed the ptr.
#[test]
fn test_into_raw() {
let mut v = vec![];
for i in 0..1000 {
v.push(SqliteMallocString::from_str(&i.to_string()).into_raw());
v.push(SqliteMallocString::from_str(&format!("abc {} 😀", i)).into_raw());
}
unsafe {
for (i, s) in v.chunks_mut(2).enumerate() {
let s0 = std::mem::replace(&mut s[0], std::ptr::null_mut());
let s1 = std::mem::replace(&mut s[1], std::ptr::null_mut());
assert_eq!(
std::ffi::CStr::from_ptr(s0).to_str().unwrap(),
&i.to_string()
);
assert_eq!(
std::ffi::CStr::from_ptr(s1).to_str().unwrap(),
&format!("abc {} 😀", i)
);
let _ = SqliteMallocString::from_raw(s0).unwrap();
let _ = SqliteMallocString::from_raw(s1).unwrap();
}
}
}
}
|
into_raw
|
identifier_name
|
sqlite_string.rs
|
// This is used when either vtab or modern-sqlite is on. Different methods are
// used in each feature. Avoid having to track this for each function. We will
// still warn for anything that's not used by either, though.
#![cfg_attr(
not(all(feature = "vtab", feature = "modern-sqlite")),
allow(dead_code)
)]
use crate::ffi;
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int};
use std::ptr::NonNull;
/// A string we own that's allocated on the SQLite heap. Automatically calls
/// `sqlite3_free` when dropped, unless `into_raw` (or `into_inner`) is called
/// on it. If constructed from a rust string, `sqlite3_malloc` is used.
///
/// It has identical representation to a nonnull `*mut c_char`, so you can use
/// it transparently as one. It's nonnull, so Option<SqliteMallocString> can be
/// used for nullable ones (it's still just one pointer).
///
/// Most strings shouldn't use this! Only places where the string needs to be
/// freed with `sqlite3_free`. This includes `sqlite3_extended_sql` results,
/// some error message pointers... Note that misuse is extremely dangerous!
///
/// Note that this is *not* a lossless interface. Incoming strings with internal
/// NULs are modified, and outgoing strings which are non-UTF8 are modified.
/// This seems unavoidable -- it tries very hard to not panic.
#[repr(transparent)]
pub(crate) struct SqliteMallocString {
ptr: NonNull<c_char>,
_boo: PhantomData<Box<[c_char]>>,
}
// This is owned data for a primitive type, and thus it's safe to implement
// these. That said, nothing needs them, and they make things easier to misuse.
// unsafe impl Send for SqliteMallocString {}
// unsafe impl Sync for SqliteMallocString {}
impl SqliteMallocString {
/// SAFETY: Caller must be certain that `m` a nul-terminated c string
/// allocated by sqlite3_malloc, and that SQLite expects us to free it!
#[inline]
pub(crate) unsafe fn from_raw_nonnull(ptr: NonNull<c_char>) -> Self {
Self {
ptr,
_boo: PhantomData,
}
}
/// SAFETY: Caller must be certain that `m` a nul-terminated c string
/// allocated by sqlite3_malloc, and that SQLite expects us to free it!
#[inline]
pub(crate) unsafe fn from_raw(ptr: *mut c_char) -> Option<Self> {
NonNull::new(ptr).map(|p| Self::from_raw_nonnull(p))
}
/// Get the pointer behind `self`. After this is called, we no longer manage
/// it.
#[inline]
pub(crate) fn into_inner(self) -> NonNull<c_char> {
let p = self.ptr;
std::mem::forget(self);
p
}
/// Get the pointer behind `self`. After this is called, we no longer manage
/// it.
#[inline]
pub(crate) fn into_raw(self) -> *mut c_char {
self.into_inner().as_ptr()
}
/// Borrow the pointer behind `self`. We still manage it when this function
/// returns. If you want to relinquish ownership, use `into_raw`.
#[inline]
pub(crate) fn as_ptr(&self) -> *const c_char {
self.ptr.as_ptr()
}
#[inline]
pub(crate) fn as_cstr(&self) -> &std::ffi::CStr {
unsafe { std::ffi::CStr::from_ptr(self.as_ptr()) }
}
#[inline]
pub(crate) fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
self.as_cstr().to_string_lossy()
}
/// Convert `s` into a SQLite string.
///
/// This should almost never be done except for cases like error messages or
/// other strings that SQLite frees.
///
/// If `s` contains internal NULs, we'll replace them with
/// `NUL_REPLACE_CHAR`.
///
/// Except for debug_asserts which may trigger during testing, this function
/// never panics. If we hit integer overflow or the allocation fails, we
/// call `handle_alloc_error` which aborts the program after calling a
/// global hook.
///
/// This means it's safe to use in extern "C" functions even outside of
/// catch_unwind.
pub(crate) fn from_str(s: &str) -> Self {
use std::convert::TryFrom;
let s = if s.as_bytes().contains(&0) {
std::borrow::Cow::Owned(make_nonnull(s))
} else {
std::borrow::Cow::Borrowed(s)
};
debug_assert!(!s.as_bytes().contains(&0));
let bytes: &[u8] = s.as_ref().as_bytes();
let src_ptr: *const c_char = bytes.as_ptr().cast();
let src_len = bytes.len();
let maybe_len_plus_1 = s.len().checked_add(1).and_then(|v| c_int::try_from(v).ok());
unsafe {
let res_ptr = maybe_len_plus_1
.and_then(|len_to_alloc| {
// `>` because we added 1.
debug_assert!(len_to_alloc > 0);
debug_assert_eq!((len_to_alloc - 1) as usize, src_len);
NonNull::new(ffi::sqlite3_malloc(len_to_alloc) as *mut c_char)
})
.unwrap_or_else(|| {
use std::alloc::{handle_alloc_error, Layout};
// Report via handle_alloc_error so that it can be handled with any
// other allocation errors and properly diagnosed.
//
// This is safe:
// - `align` is never 0
// - `align` is always a power of 2.
// - `size` needs no realignment because it's guaranteed to be aligned
// (everything is aligned to 1)
// - `size` is also never zero, although this function doesn't actually require
// it now.
let layout = Layout::from_size_align_unchecked(s.len().saturating_add(1), 1);
// Note: This call does not return.
handle_alloc_error(layout);
});
let buf: *mut c_char = res_ptr.as_ptr() as *mut c_char;
src_ptr.copy_to_nonoverlapping(buf, src_len);
buf.add(src_len).write(0);
debug_assert_eq!(std::ffi::CStr::from_ptr(res_ptr.as_ptr()).to_bytes(), bytes);
Self::from_raw_nonnull(res_ptr)
}
}
}
const NUL_REPLACE: &str = "␀";
#[cold]
fn make_nonnull(v: &str) -> String {
v.replace('\0', NUL_REPLACE)
}
impl Drop for SqliteMallocString {
#[inline]
fn drop(&mut self) {
unsafe { ffi::sqlite3_free(self.ptr.as_ptr().cast()) };
}
}
impl std::fmt::Debug for SqliteMallocString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_string_lossy().fmt(f)
}
}
impl std::fmt::Display for SqliteMallocString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_string_lossy().fmt(f)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_from_str() {
let to_check = [
("", ""),
("\0", "␀"),
("␀", "␀"),
("\0bar", "␀bar"),
("foo\0bar", "foo␀bar"),
("foo\0", "foo␀"),
("a\0b\0c\0\0d", "a␀b␀c␀␀d"),
("foobar0123", "foobar0123"),
];
for &(input, output) in &to_check {
let s = SqliteMallocString::from_str(input);
assert_eq!(s.to_string_lossy(), output);
assert_eq!(s.as_cstr().to_str().unwrap(), output);
}
}
// This will trigger an asan error if into_raw still freed the ptr.
#[test]
fn test_lossy() {
let p = Sqli
|
gger an asan error if into_raw still freed the ptr.
#[test]
fn test_into_raw() {
let mut v = vec![];
for i in 0..1000 {
v.push(SqliteMallocString::from_str(&i.to_string()).into_raw());
v.push(SqliteMallocString::from_str(&format!("abc {} 😀", i)).into_raw());
}
unsafe {
for (i, s) in v.chunks_mut(2).enumerate() {
let s0 = std::mem::replace(&mut s[0], std::ptr::null_mut());
let s1 = std::mem::replace(&mut s[1], std::ptr::null_mut());
assert_eq!(
std::ffi::CStr::from_ptr(s0).to_str().unwrap(),
&i.to_string()
);
assert_eq!(
std::ffi::CStr::from_ptr(s1).to_str().unwrap(),
&format!("abc {} 😀", i)
);
let _ = SqliteMallocString::from_raw(s0).unwrap();
let _ = SqliteMallocString::from_raw(s1).unwrap();
}
}
}
}
|
teMallocString::from_str("abcd").into_raw();
// Make invalid
let s = unsafe {
p.cast::<u8>().write(b'\xff');
SqliteMallocString::from_raw(p).unwrap()
};
assert_eq!(s.to_string_lossy().as_ref(), "\u{FFFD}bcd");
}
// This will tri
|
identifier_body
|
mode_info.rs
|
attributes: u16,
win_a: u8,
win_b: u8,
granularity: u16,
winsize: u16,
segment_a: u16,
segment_b: u16,
winfuncptr: u32,
bytesperscanline: u16,
pub xresolution: u16,
pub yresolution: u16,
xcharsize: u8,
ycharsize: u8,
numberofplanes: u8,
bitsperpixel: u8,
numberofbanks: u8,
memorymodel: u8,
banksize: u8,
numberofimagepages: u8,
unused: u8,
redmasksize: u8,
redfieldposition: u8,
greenmasksize: u8,
greenfieldposition: u8,
bluemasksize: u8,
bluefieldposition: u8,
rsvdmasksize: u8,
rsvdfieldposition: u8,
directcolormodeinfo: u8,
pub physbaseptr: u32,
offscreenmemoryoffset: u32,
offscreenmemsize: u16,
}
|
/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
|
random_line_split
|
|
mode_info.rs
|
/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct
|
{
attributes: u16,
win_a: u8,
win_b: u8,
granularity: u16,
winsize: u16,
segment_a: u16,
segment_b: u16,
winfuncptr: u32,
bytesperscanline: u16,
pub xresolution: u16,
pub yresolution: u16,
xcharsize: u8,
ycharsize: u8,
numberofplanes: u8,
bitsperpixel: u8,
numberofbanks: u8,
memorymodel: u8,
banksize: u8,
numberofimagepages: u8,
unused: u8,
redmasksize: u8,
redfieldposition: u8,
greenmasksize: u8,
greenfieldposition: u8,
bluemasksize: u8,
bluefieldposition: u8,
rsvdmasksize: u8,
rsvdfieldposition: u8,
directcolormodeinfo: u8,
pub physbaseptr: u32,
offscreenmemoryoffset: u32,
offscreenmemsize: u16,
}
|
VBEModeInfo
|
identifier_name
|
publish.rs
|
use cargo::ops;
use cargo::core::{MultiShell};
use cargo::util::{CliResult, CliError};
use cargo::util::important_paths::find_root_manifest_for_cwd;
#[derive(RustcDecodable)]
struct Options {
flag_host: Option<String>,
flag_token: Option<String>,
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_no_verify: bool,
}
pub const USAGE: &'static str = "
Upload a package to the registry
Usage:
cargo publish [options]
Options:
-h, --help Print this message
--host HOST Host to upload the package to
--token TOKEN Token to use when uploading
--no-verify Don't verify package tarball before publish
--manifest-path PATH Path to the manifest to compile
-v, --verbose Use verbose output
";
pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
shell.set_verbose(options.flag_verbose);
let Options {
flag_token: token,
flag_host: host,
flag_manifest_path,
flag_no_verify: no_verify,
..
} = options;
let root = try!(find_root_manifest_for_cwd(flag_manifest_path.clone()));
|
ops::publish(&root, shell, token, host,!no_verify).map(|_| None).map_err(|err| {
CliError::from_boxed(err, 101)
})
}
|
random_line_split
|
|
publish.rs
|
use cargo::ops;
use cargo::core::{MultiShell};
use cargo::util::{CliResult, CliError};
use cargo::util::important_paths::find_root_manifest_for_cwd;
#[derive(RustcDecodable)]
struct Options {
flag_host: Option<String>,
flag_token: Option<String>,
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_no_verify: bool,
}
pub const USAGE: &'static str = "
Upload a package to the registry
Usage:
cargo publish [options]
Options:
-h, --help Print this message
--host HOST Host to upload the package to
--token TOKEN Token to use when uploading
--no-verify Don't verify package tarball before publish
--manifest-path PATH Path to the manifest to compile
-v, --verbose Use verbose output
";
pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>>
|
{
shell.set_verbose(options.flag_verbose);
let Options {
flag_token: token,
flag_host: host,
flag_manifest_path,
flag_no_verify: no_verify,
..
} = options;
let root = try!(find_root_manifest_for_cwd(flag_manifest_path.clone()));
ops::publish(&root, shell, token, host, !no_verify).map(|_| None).map_err(|err| {
CliError::from_boxed(err, 101)
})
}
|
identifier_body
|
|
publish.rs
|
use cargo::ops;
use cargo::core::{MultiShell};
use cargo::util::{CliResult, CliError};
use cargo::util::important_paths::find_root_manifest_for_cwd;
#[derive(RustcDecodable)]
struct Options {
flag_host: Option<String>,
flag_token: Option<String>,
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_no_verify: bool,
}
pub const USAGE: &'static str = "
Upload a package to the registry
Usage:
cargo publish [options]
Options:
-h, --help Print this message
--host HOST Host to upload the package to
--token TOKEN Token to use when uploading
--no-verify Don't verify package tarball before publish
--manifest-path PATH Path to the manifest to compile
-v, --verbose Use verbose output
";
pub fn
|
(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
shell.set_verbose(options.flag_verbose);
let Options {
flag_token: token,
flag_host: host,
flag_manifest_path,
flag_no_verify: no_verify,
..
} = options;
let root = try!(find_root_manifest_for_cwd(flag_manifest_path.clone()));
ops::publish(&root, shell, token, host,!no_verify).map(|_| None).map_err(|err| {
CliError::from_boxed(err, 101)
})
}
|
execute
|
identifier_name
|
issue-3556.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[deriving(Show)]
enum Token {
Text(String),
ETag(Vec<String>, String),
UTag(Vec<String>, String),
Section(Vec<String>, bool, Vec<Token>, String,
String, String, String, String),
IncompleteSection(Vec<String>, bool, String, bool),
Partial(String, String, String),
}
fn check_strs(actual: &str, expected: &str) -> bool
{
if actual!= expected
|
return true;
}
pub fn main()
{
// assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")"));
// assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())),
// "ETag(@~[ ~\"foo\" ], @~\"bar\")"));
let t = Text("foo".to_string());
let u = Section(vec!["alpha".to_string()],
true,
vec![t],
"foo".to_string(),
"foo".to_string(), "foo".to_string(), "foo".to_string(),
"foo".to_string());
let v = format!("{}", u); // this is the line that causes the seg fault
assert!(v.len() > 0);
}
|
{
println!("Found {}, but expected {}", actual, expected);
return false;
}
|
conditional_block
|
issue-3556.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[deriving(Show)]
enum
|
{
Text(String),
ETag(Vec<String>, String),
UTag(Vec<String>, String),
Section(Vec<String>, bool, Vec<Token>, String,
String, String, String, String),
IncompleteSection(Vec<String>, bool, String, bool),
Partial(String, String, String),
}
fn check_strs(actual: &str, expected: &str) -> bool
{
if actual!= expected
{
println!("Found {}, but expected {}", actual, expected);
return false;
}
return true;
}
pub fn main()
{
// assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")"));
// assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())),
// "ETag(@~[ ~\"foo\" ], @~\"bar\")"));
let t = Text("foo".to_string());
let u = Section(vec!["alpha".to_string()],
true,
vec![t],
"foo".to_string(),
"foo".to_string(), "foo".to_string(), "foo".to_string(),
"foo".to_string());
let v = format!("{}", u); // this is the line that causes the seg fault
assert!(v.len() > 0);
}
|
Token
|
identifier_name
|
issue-3556.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[deriving(Show)]
enum Token {
Text(String),
ETag(Vec<String>, String),
UTag(Vec<String>, String),
Section(Vec<String>, bool, Vec<Token>, String,
String, String, String, String),
IncompleteSection(Vec<String>, bool, String, bool),
Partial(String, String, String),
}
fn check_strs(actual: &str, expected: &str) -> bool
|
pub fn main()
{
// assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")"));
// assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())),
// "ETag(@~[ ~\"foo\" ], @~\"bar\")"));
let t = Text("foo".to_string());
let u = Section(vec!["alpha".to_string()],
true,
vec![t],
"foo".to_string(),
"foo".to_string(), "foo".to_string(), "foo".to_string(),
"foo".to_string());
let v = format!("{}", u); // this is the line that causes the seg fault
assert!(v.len() > 0);
}
|
{
if actual != expected
{
println!("Found {}, but expected {}", actual, expected);
return false;
}
return true;
}
|
identifier_body
|
issue-3556.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[deriving(Show)]
enum Token {
Text(String),
ETag(Vec<String>, String),
UTag(Vec<String>, String),
Section(Vec<String>, bool, Vec<Token>, String,
String, String, String, String),
IncompleteSection(Vec<String>, bool, String, bool),
Partial(String, String, String),
}
fn check_strs(actual: &str, expected: &str) -> bool
{
if actual!= expected
{
println!("Found {}, but expected {}", actual, expected);
|
return false;
}
return true;
}
pub fn main()
{
// assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")"));
// assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())),
// "ETag(@~[ ~\"foo\" ], @~\"bar\")"));
let t = Text("foo".to_string());
let u = Section(vec!["alpha".to_string()],
true,
vec![t],
"foo".to_string(),
"foo".to_string(), "foo".to_string(), "foo".to_string(),
"foo".to_string());
let v = format!("{}", u); // this is the line that causes the seg fault
assert!(v.len() > 0);
}
|
random_line_split
|
|
main.rs
|
extern crate printspool_marlin;
use std::env;
use std::os::unix::fs::PermissionsExt;
use pidfile_rs::Pidfile;
use nix::sched::{CpuSet, sched_setaffinity};
use nix::unistd::Pid;
use printspool_marlin::MachineConfig;
pub use printspool_machine::paths;
fn main() -> Result<(), Box<dyn std::error::Error>>
|
pidfile.write()?;
// All other teg processes are prevented from running on cpu 0 so that it can be dedicated
// to the driver processes (eg. printspool-marlin).
let mut cpu_set = CpuSet::new();
cpu_set.set(0)?;
sched_setaffinity(Pid::from_raw(0), &cpu_set)?;
// Create single-threaded runtime that will run printspool-marlin only on the dedicated CPU
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
rt.block_on(printspool_marlin::start(config_path))?;
Ok(())
}
|
{
let mut args = env::args();
let machine_id = args.nth(1)
.expect("Expected useage: tegh.marlin $MACHINE_ID");
let pid_file = MachineConfig::pid_file_path(&machine_id);
let config_path = MachineConfig::config_file_path(&machine_id);
// Create and lock the pidfile
// See: https://yakking.branchable.com/posts/procrun-2-pidfiles/
let pidfile = Pidfile::new(
&pid_file,
std::fs::Permissions::from_mode(0o600),
)?;
// Must run daemonize before starting tokio!
nix::unistd::daemon(true, true)
.expect("Error daemonizing marlin driver process");
// After daemonizing the process write the pid to the pidfile
|
identifier_body
|
main.rs
|
extern crate printspool_marlin;
use std::env;
use std::os::unix::fs::PermissionsExt;
use pidfile_rs::Pidfile;
use nix::sched::{CpuSet, sched_setaffinity};
use nix::unistd::Pid;
use printspool_marlin::MachineConfig;
pub use printspool_machine::paths;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = env::args();
let machine_id = args.nth(1)
|
let config_path = MachineConfig::config_file_path(&machine_id);
// Create and lock the pidfile
// See: https://yakking.branchable.com/posts/procrun-2-pidfiles/
let pidfile = Pidfile::new(
&pid_file,
std::fs::Permissions::from_mode(0o600),
)?;
// Must run daemonize before starting tokio!
nix::unistd::daemon(true, true)
.expect("Error daemonizing marlin driver process");
// After daemonizing the process write the pid to the pidfile
pidfile.write()?;
// All other teg processes are prevented from running on cpu 0 so that it can be dedicated
// to the driver processes (eg. printspool-marlin).
let mut cpu_set = CpuSet::new();
cpu_set.set(0)?;
sched_setaffinity(Pid::from_raw(0), &cpu_set)?;
// Create single-threaded runtime that will run printspool-marlin only on the dedicated CPU
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
rt.block_on(printspool_marlin::start(config_path))?;
Ok(())
}
|
.expect("Expected useage: tegh.marlin $MACHINE_ID");
let pid_file = MachineConfig::pid_file_path(&machine_id);
|
random_line_split
|
main.rs
|
extern crate printspool_marlin;
use std::env;
use std::os::unix::fs::PermissionsExt;
use pidfile_rs::Pidfile;
use nix::sched::{CpuSet, sched_setaffinity};
use nix::unistd::Pid;
use printspool_marlin::MachineConfig;
pub use printspool_machine::paths;
fn
|
() -> Result<(), Box<dyn std::error::Error>> {
let mut args = env::args();
let machine_id = args.nth(1)
.expect("Expected useage: tegh.marlin $MACHINE_ID");
let pid_file = MachineConfig::pid_file_path(&machine_id);
let config_path = MachineConfig::config_file_path(&machine_id);
// Create and lock the pidfile
// See: https://yakking.branchable.com/posts/procrun-2-pidfiles/
let pidfile = Pidfile::new(
&pid_file,
std::fs::Permissions::from_mode(0o600),
)?;
// Must run daemonize before starting tokio!
nix::unistd::daemon(true, true)
.expect("Error daemonizing marlin driver process");
// After daemonizing the process write the pid to the pidfile
pidfile.write()?;
// All other teg processes are prevented from running on cpu 0 so that it can be dedicated
// to the driver processes (eg. printspool-marlin).
let mut cpu_set = CpuSet::new();
cpu_set.set(0)?;
sched_setaffinity(Pid::from_raw(0), &cpu_set)?;
// Create single-threaded runtime that will run printspool-marlin only on the dedicated CPU
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
rt.block_on(printspool_marlin::start(config_path))?;
Ok(())
}
|
main
|
identifier_name
|
eval.rs
|
/*
Copyright 2017-2020 Andrew Medworth <[email protected]>
This file is part of Dots-and-Boxes Engine.
Dots-and-Boxes Engine is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Dots-and-Boxes Engine 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Dots-and-Boxes Engine. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::game::{Move, Position, SimplePosition, CompoundPosition, Side, CPosMove};
use crate::nimstring::{self, NimstringPosition};
use std::collections::HashMap;
use std::isize;
pub trait EvaluablePosition<M> : NimstringPosition<M> {
// Given a loony position and the capture, find the corresponding double-dealing move.
// Behaviour on a non-loony position is undefined.
fn find_ddeal_move(&self, m: M) -> M;
}
impl EvaluablePosition<Move> for SimplePosition {
fn find_ddeal_move(self: &SimplePosition, capture: Move) -> Move {
// (capture.x, capture.y) might be the valency-1 coin or the valency-2 one
let (v2_x, v2_y, excl_side) = if self.valency(capture.x, capture.y) == 1 {
let (x, y) = self.offset(capture.x, capture.y, capture.side).unwrap();
(x, y, capture.side.opposite())
} else {
(capture.x, capture.y, capture.side)
};
if self.valency(v2_x, v2_y)!= 2 {
panic!("Expected ({},{}) to have valency 2, found {} in {}",
v2_x, v2_y, self.valency(v2_x, v2_y), self);
}
for s in Side::all_except(excl_side) {
if self.is_legal_move(Move{x: v2_x, y: v2_y, side: s}) {
return Move{x: v2_x, y: v2_y, side: s};
}
}
panic!("Could not find double-dealing move corresponding to {} in {}", capture, self);
}
}
impl EvaluablePosition<CPosMove> for CompoundPosition {
fn find_ddeal_move(self: &CompoundPosition, capture: CPosMove) -> CPosMove {
CPosMove{part: capture.part, m: self.parts[capture.part].find_ddeal_move(capture.m)}
}
}
// Evaluate a position given a set of moves to consider
fn eval_moves<M, P>(pos: &mut P, moves: &Vec<M>,
cache: &mut HashMap<usize, (isize, M)>) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> {
if moves.is_empty() {
return (0, None);
}
let mut value = isize::MIN;
let mut best_move = moves[0];
for &m in moves {
let outcome = pos.make_move(m);
let sign = if outcome.coins_captured > 0 { 1 } else { -1 };
let (next_val, _) = eval_cache(pos, cache);
let sub_val = (outcome.coins_captured as isize) + sign * next_val;
pos.undo_move(m);
if sub_val > value {
value = sub_val;
best_move = m;
}
}
cache.insert(pos.zhash(), (value, best_move));
(value, Some(best_move))
}
// Determine what moves deserve consideration in a given position
fn moves_to_consider<M, P>(pos: &mut P) -> Vec<M>
where M: Copy, P: EvaluablePosition<M> {
let legal_moves = pos.legal_moves();
// If there are any captures which don't affect looniness, just go ahead and make those
let is_loony = pos.is_loony();
let mut capture: Option<M> = None;
for &m in &legal_moves {
let captures = pos.would_capture(m);
if captures == 0 {
continue;
}
capture = Some(m);
if!is_loony || nimstring::would_be_loony(pos, m) {
return vec!(m);
}
}
// Consider only capturing all and double-dealing in the loony case
// TODO: Use other canonical play results to further reduce the set of moves considered
if is_loony {
let capture = capture.unwrap();
let ddeal_move = pos.find_ddeal_move(capture);
vec!(capture, ddeal_move)
} else {
legal_moves
}
}
fn eval_cache<M, P>(pos: &mut P, cache: &mut HashMap<usize, (isize, M)>) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> {
if let Some(&(val, best_move)) = cache.get(&pos.zhash()) {
return (val, Some(best_move));
}
let moves = moves_to_consider(pos);
eval_moves(pos, &moves, cache)
}
// Calculate the value function of a given position and a move which achieves that value
pub fn eval<M, P>(pos: &P) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> + Clone {
let mut cache = HashMap::new();
let mut pos = pos.clone();
eval_cache(&mut pos, &mut cache)
}
#[cfg(test)]
mod test {
use crate::eval::*;
use crate::examples::*;
use rand::{Rng, SeedableRng};
use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use std::cmp;
use time::Instant;
#[test]
fn eval_chain() {
for i in 1..10 {
let mut chain = make_chain(i);
let (val, _) = eval(&chain);
let expected_val = -(i as isize);
assert_eq!(expected_val, val, "Closed {}-chain", i);
chain.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&chain);
assert_eq!(-expected_val, val, "Opened {}-chain", i);
assert!(chain.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
}
}
#[test]
fn eval_double_chain() {
let (val, _) = eval(&double_chain(1));
assert_eq!(0, val);
for i in 2..10 {
let mut pos = double_chain(i);
let (val, _) = eval(&pos);
let expected_val = 4 - 2*(i as isize);
assert_eq!(expected_val, val, "Evaluation of double chain length {}", i);
pos.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&pos);
assert_eq!(-expected_val, val, "Evaluation of opened double chain length {}", i);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
}
}
#[test]
fn eval_multi_chains() {
let mut pos = multi_chains(3, 4);
let (val, _) = eval(&pos);
assert_eq!(-2, val);
pos.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&pos);
assert_eq!(2, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
pos.make_move(Move{x: 0, y: 0, side: Side::Right});
let (val, best_move) = eval(&pos);
assert_eq!(1, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 1, y: 0, side: Side::Right}));
pos.make_move(Move{x: 1, y: 0, side: Side::Right});
let (val, best_move) = eval(&pos);
assert_eq!(0, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 2, y: 0, side: Side::Right}));
pos.make_move(Move{x: 2, y: 0, side: Side::Right});
let (val, _) = eval(&pos);
assert_eq!(-1, val);
}
#[test]
fn eval_double_loop() {
for i in 2..8 {
let mut pos = double_loop(i);
let (val, _) = eval(&pos);
let expected_val = 8 - 4*(i as isize);
assert_eq!(expected_val, val, "Evaluation of double loop width {}", i);
pos.make_move(Move{x: 0, y: 0, side: Side::Right});
let (val, _) = eval(&pos);
assert_eq!(-expected_val, val, "Evaluation of opened double loop width {}", i);
}
}
#[test]
fn eval_ex3p1() {
let mut pos = ex3p1();
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
assert_eq!(3, val);
assert!(pos.moves_equivalent(best_move, Move{x: 2, y: 1, side: Side::Bottom}));
pos.make_move(Move{x: 2, y: 1, side: Side::Bottom});
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
assert_eq!(-3, val);
assert!(pos.moves_equivalent(best_move, Move{x: 0, y: 0, side: Side::Bottom}));
pos.make_move(Move{x: 0, y: 0, side: Side::Bottom});
let (val, _) = eval(&pos);
assert_eq!(3, val);
pos.undo_move(Move{x: 0, y: 0, side: Side::Bottom});
pos.make_move(Move{x: 0, y: 2, side: Side::Left});
let (val, _) = eval(&pos);
assert_eq!(5, val);
}
#[test]
fn eval_ex3p12() {
let mut pos = ex3p12();
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
let expected_val = 9;
assert_eq!(expected_val, val);
assert!(pos.moves_equivalent(best_move, Move{x: 4, y: 0, side: Side::Bottom}));
pos.make_move(Move{x: 4, y: 0, side: Side::Bottom});
let (val, _) = eval(&pos);
assert_eq!(-expected_val, val);
}
#[derive(Debug)]
struct OLMTCase {
i: usize,
k: usize,
exp_val: isize,
taking_optimal: bool,
ddeal_optimal: bool,
}
impl OLMTCase {
fn new(i: usize, k: usize, exp_val: isize,
taking_optimal: bool, ddeal_optimal: bool) -> OLMTCase {
OLMTCase{i: i, k: k, exp_val: exp_val,
taking_optimal: taking_optimal, ddeal_optimal: ddeal_optimal}
}
}
#[test]
fn eval_one_long_multi_three() {
// Check the P_{i,4} table from the paper
let cases = vec!(
OLMTCase::new(0, 4, -4, true, false),
OLMTCase::new(1, 4, -3, false, true),
OLMTCase::new(2, 4, -2, false, true),
OLMTCase::new(3, 4, -1, true, true),
OLMTCase::new(4, 4, -2, true, false),
OLMTCase::new(5, 4, -1, true, true),
OLMTCase::new(6, 4, -2, true, false),
OLMTCase::new(7, 4, -1, true, true),
OLMTCase::new(8, 4, -2, true, false),
);
for case in cases.iter() {
let mut pos = one_long_multi_three(case.i, case.k);
let (val, _) = eval(&pos);
assert_eq!(case.exp_val, val, "{:?}", case);
let part = if case.i == 0 { 0 } else { 1 };
let open = CPosMove::new(part, 0, 0, Side::Left);
pos.make_move(open);
// Once the first chain is opened, capturing the first coin
// is the only move to consider
assert_eq!(1, moves_to_consider(&mut pos).len());
let (val, best_move) = eval(&pos);
assert_eq!(-case.exp_val, val, "{:?}", case);
assert_eq!(1, pos.make_move(best_move.unwrap()).coins_captured);
let (val, best_move) = eval(&pos);
if case.i > 0 {
assert_eq!(2, moves_to_consider(&mut pos).len());
}
assert_eq!(-case.exp_val-1, val, "{:?}", case);
let mut ok_moves: Vec<CPosMove> = Vec::with_capacity(2);
if case.taking_optimal {
ok_moves.push(CPosMove::new(part, 1, 0, Side::Right));
}
if case.ddeal_optimal {
ok_moves.push(CPosMove::new(part, 2, 0, Side::Right));
}
assert!(ok_moves.iter().any(|&m| pos.moves_equivalent(m, best_move.unwrap())),
"{:?} {:?} {}", case, ok_moves, best_move.unwrap());
}
}
#[test]
fn
|
() {
let mut pos = CompoundPosition::new(vec!(make_chain(2), make_chain(2)));
pos.make_move(CPosMove::new(0, 0, 0, Side::Left));
pos.make_move(CPosMove::new(1, 0, 0, Side::Left));
assert_eq!(1, moves_to_consider(&mut pos).len());
}
// For use in generative tests
fn make_random_pos(r: &mut StdRng) -> SimplePosition {
let width: usize = r.gen_range(1..4);
let height: usize = r.gen_range(1..4);
let mut pos = SimplePosition::new_game(width, height);
let mut moves = pos.legal_moves();
moves.as_mut_slice().shuffle(r);
let max_remaining_moves = 9; // Limits running cost of naive minimax
let min_move_count: usize = if moves.len() > max_remaining_moves {
moves.len() - max_remaining_moves
} else {
0
};
let move_count = r.gen_range(min_move_count..moves.len() + 1);
for i in 0..move_count {
let m = moves[i];
pos.make_move(m);
}
pos
}
// Dumb evaluation algorithm to compare to optimised one
fn naive_minimax(pos: &mut SimplePosition) -> isize {
let moves = pos.legal_moves();
if moves.is_empty() {
return 0;
}
let mut result = isize::MIN;
for &m in &moves {
let outcome = pos.make_move(m);
let captures = outcome.coins_captured as isize;
let m_val = if captures > 0 {
captures + naive_minimax(pos)
} else {
-naive_minimax(pos)
};
pos.undo_move(m);
result = cmp::max(result, m_val);
}
result
}
#[test]
fn matches_naive_minimax() {
let test_time_s = 10 as f64;
let mut seed: [u8; 32] = [0; 32];
seed[0] = 123;
let mut r: StdRng = SeedableRng::from_seed(seed);
let mut i = 0;
let start_time = Instant::now();
loop {
let mut pos = make_random_pos(&mut r);
let expected_val = naive_minimax(&mut pos);
let (val, best_move) = eval(&pos);
assert_eq!(expected_val, val, "SimplePosition {} value matches naive minimax", i);
if!pos.is_end_of_game() {
let best_move = best_move.unwrap();
let outcome = pos.make_move(best_move);
let captures = outcome.coins_captured as isize;
let (next_val, _) = eval(&pos);
let expected_next_val = if captures > 0 {
expected_val - captures
} else {
-expected_val
};
assert_eq!(expected_next_val, next_val);
}
let elapsed = start_time.elapsed();
if elapsed.as_seconds_f64() >= test_time_s {
break;
}
i += 1;
}
}
// TODO: Test that rotations and reflections do not affect the evaluation
// #[test]
// fn eval_p50() {
// let mut pos = p50();
// let (val, best_move) = eval(&pos);
// let best_move = best_move.unwrap();
// assert_eq!(4, val);
// assert!(pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Right})
// || pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Bottom})
// || pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Left}));
// }
}
|
multiple_loony_parts
|
identifier_name
|
eval.rs
|
/*
Copyright 2017-2020 Andrew Medworth <[email protected]>
This file is part of Dots-and-Boxes Engine.
Dots-and-Boxes Engine is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Dots-and-Boxes Engine 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Dots-and-Boxes Engine. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::game::{Move, Position, SimplePosition, CompoundPosition, Side, CPosMove};
use crate::nimstring::{self, NimstringPosition};
use std::collections::HashMap;
use std::isize;
pub trait EvaluablePosition<M> : NimstringPosition<M> {
// Given a loony position and the capture, find the corresponding double-dealing move.
// Behaviour on a non-loony position is undefined.
fn find_ddeal_move(&self, m: M) -> M;
}
impl EvaluablePosition<Move> for SimplePosition {
fn find_ddeal_move(self: &SimplePosition, capture: Move) -> Move {
// (capture.x, capture.y) might be the valency-1 coin or the valency-2 one
let (v2_x, v2_y, excl_side) = if self.valency(capture.x, capture.y) == 1 {
let (x, y) = self.offset(capture.x, capture.y, capture.side).unwrap();
(x, y, capture.side.opposite())
} else {
(capture.x, capture.y, capture.side)
};
if self.valency(v2_x, v2_y)!= 2 {
panic!("Expected ({},{}) to have valency 2, found {} in {}",
v2_x, v2_y, self.valency(v2_x, v2_y), self);
}
for s in Side::all_except(excl_side) {
if self.is_legal_move(Move{x: v2_x, y: v2_y, side: s}) {
return Move{x: v2_x, y: v2_y, side: s};
}
}
panic!("Could not find double-dealing move corresponding to {} in {}", capture, self);
}
}
impl EvaluablePosition<CPosMove> for CompoundPosition {
fn find_ddeal_move(self: &CompoundPosition, capture: CPosMove) -> CPosMove {
CPosMove{part: capture.part, m: self.parts[capture.part].find_ddeal_move(capture.m)}
}
}
// Evaluate a position given a set of moves to consider
fn eval_moves<M, P>(pos: &mut P, moves: &Vec<M>,
cache: &mut HashMap<usize, (isize, M)>) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> {
if moves.is_empty() {
return (0, None);
}
let mut value = isize::MIN;
let mut best_move = moves[0];
for &m in moves {
let outcome = pos.make_move(m);
let sign = if outcome.coins_captured > 0 { 1 } else { -1 };
let (next_val, _) = eval_cache(pos, cache);
let sub_val = (outcome.coins_captured as isize) + sign * next_val;
pos.undo_move(m);
if sub_val > value {
value = sub_val;
best_move = m;
}
}
cache.insert(pos.zhash(), (value, best_move));
(value, Some(best_move))
}
// Determine what moves deserve consideration in a given position
fn moves_to_consider<M, P>(pos: &mut P) -> Vec<M>
where M: Copy, P: EvaluablePosition<M> {
let legal_moves = pos.legal_moves();
// If there are any captures which don't affect looniness, just go ahead and make those
let is_loony = pos.is_loony();
let mut capture: Option<M> = None;
for &m in &legal_moves {
let captures = pos.would_capture(m);
if captures == 0 {
continue;
}
capture = Some(m);
if!is_loony || nimstring::would_be_loony(pos, m) {
return vec!(m);
}
}
// Consider only capturing all and double-dealing in the loony case
// TODO: Use other canonical play results to further reduce the set of moves considered
if is_loony {
let capture = capture.unwrap();
let ddeal_move = pos.find_ddeal_move(capture);
vec!(capture, ddeal_move)
} else {
legal_moves
}
}
fn eval_cache<M, P>(pos: &mut P, cache: &mut HashMap<usize, (isize, M)>) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> {
if let Some(&(val, best_move)) = cache.get(&pos.zhash()) {
return (val, Some(best_move));
}
let moves = moves_to_consider(pos);
eval_moves(pos, &moves, cache)
}
// Calculate the value function of a given position and a move which achieves that value
pub fn eval<M, P>(pos: &P) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> + Clone {
let mut cache = HashMap::new();
let mut pos = pos.clone();
eval_cache(&mut pos, &mut cache)
}
#[cfg(test)]
mod test {
use crate::eval::*;
use crate::examples::*;
use rand::{Rng, SeedableRng};
use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use std::cmp;
use time::Instant;
#[test]
fn eval_chain() {
for i in 1..10 {
let mut chain = make_chain(i);
let (val, _) = eval(&chain);
let expected_val = -(i as isize);
assert_eq!(expected_val, val, "Closed {}-chain", i);
chain.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&chain);
assert_eq!(-expected_val, val, "Opened {}-chain", i);
assert!(chain.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
}
}
#[test]
fn eval_double_chain() {
let (val, _) = eval(&double_chain(1));
assert_eq!(0, val);
for i in 2..10 {
let mut pos = double_chain(i);
let (val, _) = eval(&pos);
let expected_val = 4 - 2*(i as isize);
assert_eq!(expected_val, val, "Evaluation of double chain length {}", i);
pos.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&pos);
assert_eq!(-expected_val, val, "Evaluation of opened double chain length {}", i);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
}
}
#[test]
fn eval_multi_chains() {
let mut pos = multi_chains(3, 4);
let (val, _) = eval(&pos);
assert_eq!(-2, val);
pos.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&pos);
assert_eq!(2, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
pos.make_move(Move{x: 0, y: 0, side: Side::Right});
let (val, best_move) = eval(&pos);
assert_eq!(1, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 1, y: 0, side: Side::Right}));
pos.make_move(Move{x: 1, y: 0, side: Side::Right});
let (val, best_move) = eval(&pos);
assert_eq!(0, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 2, y: 0, side: Side::Right}));
pos.make_move(Move{x: 2, y: 0, side: Side::Right});
let (val, _) = eval(&pos);
assert_eq!(-1, val);
}
#[test]
fn eval_double_loop() {
for i in 2..8 {
let mut pos = double_loop(i);
let (val, _) = eval(&pos);
let expected_val = 8 - 4*(i as isize);
assert_eq!(expected_val, val, "Evaluation of double loop width {}", i);
pos.make_move(Move{x: 0, y: 0, side: Side::Right});
let (val, _) = eval(&pos);
assert_eq!(-expected_val, val, "Evaluation of opened double loop width {}", i);
}
}
#[test]
fn eval_ex3p1() {
let mut pos = ex3p1();
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
assert_eq!(3, val);
assert!(pos.moves_equivalent(best_move, Move{x: 2, y: 1, side: Side::Bottom}));
pos.make_move(Move{x: 2, y: 1, side: Side::Bottom});
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
assert_eq!(-3, val);
assert!(pos.moves_equivalent(best_move, Move{x: 0, y: 0, side: Side::Bottom}));
pos.make_move(Move{x: 0, y: 0, side: Side::Bottom});
let (val, _) = eval(&pos);
assert_eq!(3, val);
pos.undo_move(Move{x: 0, y: 0, side: Side::Bottom});
pos.make_move(Move{x: 0, y: 2, side: Side::Left});
let (val, _) = eval(&pos);
assert_eq!(5, val);
}
#[test]
fn eval_ex3p12() {
let mut pos = ex3p12();
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
let expected_val = 9;
assert_eq!(expected_val, val);
assert!(pos.moves_equivalent(best_move, Move{x: 4, y: 0, side: Side::Bottom}));
pos.make_move(Move{x: 4, y: 0, side: Side::Bottom});
let (val, _) = eval(&pos);
assert_eq!(-expected_val, val);
}
#[derive(Debug)]
struct OLMTCase {
i: usize,
k: usize,
exp_val: isize,
taking_optimal: bool,
ddeal_optimal: bool,
}
impl OLMTCase {
fn new(i: usize, k: usize, exp_val: isize,
taking_optimal: bool, ddeal_optimal: bool) -> OLMTCase {
OLMTCase{i: i, k: k, exp_val: exp_val,
taking_optimal: taking_optimal, ddeal_optimal: ddeal_optimal}
}
}
#[test]
fn eval_one_long_multi_three() {
// Check the P_{i,4} table from the paper
let cases = vec!(
OLMTCase::new(0, 4, -4, true, false),
OLMTCase::new(1, 4, -3, false, true),
OLMTCase::new(2, 4, -2, false, true),
OLMTCase::new(3, 4, -1, true, true),
OLMTCase::new(4, 4, -2, true, false),
OLMTCase::new(5, 4, -1, true, true),
OLMTCase::new(6, 4, -2, true, false),
OLMTCase::new(7, 4, -1, true, true),
OLMTCase::new(8, 4, -2, true, false),
);
for case in cases.iter() {
let mut pos = one_long_multi_three(case.i, case.k);
let (val, _) = eval(&pos);
assert_eq!(case.exp_val, val, "{:?}", case);
let part = if case.i == 0 { 0 } else { 1 };
let open = CPosMove::new(part, 0, 0, Side::Left);
pos.make_move(open);
// Once the first chain is opened, capturing the first coin
// is the only move to consider
assert_eq!(1, moves_to_consider(&mut pos).len());
let (val, best_move) = eval(&pos);
assert_eq!(-case.exp_val, val, "{:?}", case);
assert_eq!(1, pos.make_move(best_move.unwrap()).coins_captured);
let (val, best_move) = eval(&pos);
if case.i > 0 {
assert_eq!(2, moves_to_consider(&mut pos).len());
}
assert_eq!(-case.exp_val-1, val, "{:?}", case);
let mut ok_moves: Vec<CPosMove> = Vec::with_capacity(2);
if case.taking_optimal {
ok_moves.push(CPosMove::new(part, 1, 0, Side::Right));
}
if case.ddeal_optimal {
ok_moves.push(CPosMove::new(part, 2, 0, Side::Right));
}
assert!(ok_moves.iter().any(|&m| pos.moves_equivalent(m, best_move.unwrap())),
"{:?} {:?} {}", case, ok_moves, best_move.unwrap());
}
}
#[test]
fn multiple_loony_parts() {
let mut pos = CompoundPosition::new(vec!(make_chain(2), make_chain(2)));
pos.make_move(CPosMove::new(0, 0, 0, Side::Left));
pos.make_move(CPosMove::new(1, 0, 0, Side::Left));
assert_eq!(1, moves_to_consider(&mut pos).len());
}
// For use in generative tests
fn make_random_pos(r: &mut StdRng) -> SimplePosition {
let width: usize = r.gen_range(1..4);
let height: usize = r.gen_range(1..4);
let mut pos = SimplePosition::new_game(width, height);
let mut moves = pos.legal_moves();
moves.as_mut_slice().shuffle(r);
let max_remaining_moves = 9; // Limits running cost of naive minimax
let min_move_count: usize = if moves.len() > max_remaining_moves {
moves.len() - max_remaining_moves
} else {
0
};
let move_count = r.gen_range(min_move_count..moves.len() + 1);
for i in 0..move_count {
let m = moves[i];
pos.make_move(m);
}
pos
}
// Dumb evaluation algorithm to compare to optimised one
fn naive_minimax(pos: &mut SimplePosition) -> isize
|
#[test]
fn matches_naive_minimax() {
let test_time_s = 10 as f64;
let mut seed: [u8; 32] = [0; 32];
seed[0] = 123;
let mut r: StdRng = SeedableRng::from_seed(seed);
let mut i = 0;
let start_time = Instant::now();
loop {
let mut pos = make_random_pos(&mut r);
let expected_val = naive_minimax(&mut pos);
let (val, best_move) = eval(&pos);
assert_eq!(expected_val, val, "SimplePosition {} value matches naive minimax", i);
if!pos.is_end_of_game() {
let best_move = best_move.unwrap();
let outcome = pos.make_move(best_move);
let captures = outcome.coins_captured as isize;
let (next_val, _) = eval(&pos);
let expected_next_val = if captures > 0 {
expected_val - captures
} else {
-expected_val
};
assert_eq!(expected_next_val, next_val);
}
let elapsed = start_time.elapsed();
if elapsed.as_seconds_f64() >= test_time_s {
break;
}
i += 1;
}
}
// TODO: Test that rotations and reflections do not affect the evaluation
// #[test]
// fn eval_p50() {
// let mut pos = p50();
// let (val, best_move) = eval(&pos);
// let best_move = best_move.unwrap();
// assert_eq!(4, val);
// assert!(pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Right})
// || pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Bottom})
// || pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Left}));
// }
}
|
{
let moves = pos.legal_moves();
if moves.is_empty() {
return 0;
}
let mut result = isize::MIN;
for &m in &moves {
let outcome = pos.make_move(m);
let captures = outcome.coins_captured as isize;
let m_val = if captures > 0 {
captures + naive_minimax(pos)
} else {
-naive_minimax(pos)
};
pos.undo_move(m);
result = cmp::max(result, m_val);
}
result
}
|
identifier_body
|
eval.rs
|
/*
Copyright 2017-2020 Andrew Medworth <[email protected]>
This file is part of Dots-and-Boxes Engine.
Dots-and-Boxes Engine is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Dots-and-Boxes Engine 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Dots-and-Boxes Engine. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::game::{Move, Position, SimplePosition, CompoundPosition, Side, CPosMove};
use crate::nimstring::{self, NimstringPosition};
use std::collections::HashMap;
use std::isize;
pub trait EvaluablePosition<M> : NimstringPosition<M> {
// Given a loony position and the capture, find the corresponding double-dealing move.
// Behaviour on a non-loony position is undefined.
fn find_ddeal_move(&self, m: M) -> M;
}
impl EvaluablePosition<Move> for SimplePosition {
fn find_ddeal_move(self: &SimplePosition, capture: Move) -> Move {
// (capture.x, capture.y) might be the valency-1 coin or the valency-2 one
let (v2_x, v2_y, excl_side) = if self.valency(capture.x, capture.y) == 1 {
let (x, y) = self.offset(capture.x, capture.y, capture.side).unwrap();
(x, y, capture.side.opposite())
} else {
(capture.x, capture.y, capture.side)
};
if self.valency(v2_x, v2_y)!= 2 {
panic!("Expected ({},{}) to have valency 2, found {} in {}",
v2_x, v2_y, self.valency(v2_x, v2_y), self);
}
for s in Side::all_except(excl_side) {
if self.is_legal_move(Move{x: v2_x, y: v2_y, side: s}) {
return Move{x: v2_x, y: v2_y, side: s};
}
}
panic!("Could not find double-dealing move corresponding to {} in {}", capture, self);
}
}
impl EvaluablePosition<CPosMove> for CompoundPosition {
fn find_ddeal_move(self: &CompoundPosition, capture: CPosMove) -> CPosMove {
CPosMove{part: capture.part, m: self.parts[capture.part].find_ddeal_move(capture.m)}
}
}
// Evaluate a position given a set of moves to consider
fn eval_moves<M, P>(pos: &mut P, moves: &Vec<M>,
cache: &mut HashMap<usize, (isize, M)>) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> {
if moves.is_empty() {
return (0, None);
}
let mut value = isize::MIN;
let mut best_move = moves[0];
for &m in moves {
let outcome = pos.make_move(m);
let sign = if outcome.coins_captured > 0 { 1 } else { -1 };
let (next_val, _) = eval_cache(pos, cache);
let sub_val = (outcome.coins_captured as isize) + sign * next_val;
pos.undo_move(m);
if sub_val > value {
value = sub_val;
best_move = m;
}
}
cache.insert(pos.zhash(), (value, best_move));
(value, Some(best_move))
}
// Determine what moves deserve consideration in a given position
fn moves_to_consider<M, P>(pos: &mut P) -> Vec<M>
where M: Copy, P: EvaluablePosition<M> {
let legal_moves = pos.legal_moves();
// If there are any captures which don't affect looniness, just go ahead and make those
let is_loony = pos.is_loony();
let mut capture: Option<M> = None;
for &m in &legal_moves {
let captures = pos.would_capture(m);
if captures == 0 {
continue;
}
capture = Some(m);
if!is_loony || nimstring::would_be_loony(pos, m) {
return vec!(m);
}
}
// Consider only capturing all and double-dealing in the loony case
// TODO: Use other canonical play results to further reduce the set of moves considered
if is_loony {
let capture = capture.unwrap();
let ddeal_move = pos.find_ddeal_move(capture);
vec!(capture, ddeal_move)
} else {
legal_moves
}
}
fn eval_cache<M, P>(pos: &mut P, cache: &mut HashMap<usize, (isize, M)>) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> {
if let Some(&(val, best_move)) = cache.get(&pos.zhash()) {
return (val, Some(best_move));
}
let moves = moves_to_consider(pos);
eval_moves(pos, &moves, cache)
}
// Calculate the value function of a given position and a move which achieves that value
pub fn eval<M, P>(pos: &P) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> + Clone {
let mut cache = HashMap::new();
let mut pos = pos.clone();
eval_cache(&mut pos, &mut cache)
}
#[cfg(test)]
mod test {
use crate::eval::*;
use crate::examples::*;
use rand::{Rng, SeedableRng};
use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use std::cmp;
use time::Instant;
#[test]
fn eval_chain() {
for i in 1..10 {
let mut chain = make_chain(i);
let (val, _) = eval(&chain);
let expected_val = -(i as isize);
assert_eq!(expected_val, val, "Closed {}-chain", i);
chain.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&chain);
assert_eq!(-expected_val, val, "Opened {}-chain", i);
assert!(chain.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
}
}
#[test]
fn eval_double_chain() {
let (val, _) = eval(&double_chain(1));
assert_eq!(0, val);
for i in 2..10 {
let mut pos = double_chain(i);
let (val, _) = eval(&pos);
let expected_val = 4 - 2*(i as isize);
assert_eq!(expected_val, val, "Evaluation of double chain length {}", i);
pos.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&pos);
assert_eq!(-expected_val, val, "Evaluation of opened double chain length {}", i);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
}
}
#[test]
fn eval_multi_chains() {
let mut pos = multi_chains(3, 4);
let (val, _) = eval(&pos);
assert_eq!(-2, val);
pos.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&pos);
assert_eq!(2, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
pos.make_move(Move{x: 0, y: 0, side: Side::Right});
let (val, best_move) = eval(&pos);
assert_eq!(1, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 1, y: 0, side: Side::Right}));
pos.make_move(Move{x: 1, y: 0, side: Side::Right});
let (val, best_move) = eval(&pos);
assert_eq!(0, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 2, y: 0, side: Side::Right}));
pos.make_move(Move{x: 2, y: 0, side: Side::Right});
let (val, _) = eval(&pos);
assert_eq!(-1, val);
}
#[test]
fn eval_double_loop() {
for i in 2..8 {
let mut pos = double_loop(i);
let (val, _) = eval(&pos);
let expected_val = 8 - 4*(i as isize);
assert_eq!(expected_val, val, "Evaluation of double loop width {}", i);
pos.make_move(Move{x: 0, y: 0, side: Side::Right});
let (val, _) = eval(&pos);
assert_eq!(-expected_val, val, "Evaluation of opened double loop width {}", i);
}
}
#[test]
fn eval_ex3p1() {
let mut pos = ex3p1();
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
assert_eq!(3, val);
assert!(pos.moves_equivalent(best_move, Move{x: 2, y: 1, side: Side::Bottom}));
pos.make_move(Move{x: 2, y: 1, side: Side::Bottom});
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
assert_eq!(-3, val);
assert!(pos.moves_equivalent(best_move, Move{x: 0, y: 0, side: Side::Bottom}));
pos.make_move(Move{x: 0, y: 0, side: Side::Bottom});
let (val, _) = eval(&pos);
assert_eq!(3, val);
pos.undo_move(Move{x: 0, y: 0, side: Side::Bottom});
pos.make_move(Move{x: 0, y: 2, side: Side::Left});
let (val, _) = eval(&pos);
assert_eq!(5, val);
}
#[test]
fn eval_ex3p12() {
let mut pos = ex3p12();
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
let expected_val = 9;
assert_eq!(expected_val, val);
assert!(pos.moves_equivalent(best_move, Move{x: 4, y: 0, side: Side::Bottom}));
pos.make_move(Move{x: 4, y: 0, side: Side::Bottom});
let (val, _) = eval(&pos);
assert_eq!(-expected_val, val);
}
#[derive(Debug)]
struct OLMTCase {
i: usize,
k: usize,
exp_val: isize,
taking_optimal: bool,
ddeal_optimal: bool,
}
impl OLMTCase {
fn new(i: usize, k: usize, exp_val: isize,
taking_optimal: bool, ddeal_optimal: bool) -> OLMTCase {
OLMTCase{i: i, k: k, exp_val: exp_val,
taking_optimal: taking_optimal, ddeal_optimal: ddeal_optimal}
}
}
#[test]
fn eval_one_long_multi_three() {
// Check the P_{i,4} table from the paper
let cases = vec!(
OLMTCase::new(0, 4, -4, true, false),
OLMTCase::new(1, 4, -3, false, true),
OLMTCase::new(2, 4, -2, false, true),
OLMTCase::new(3, 4, -1, true, true),
OLMTCase::new(4, 4, -2, true, false),
OLMTCase::new(5, 4, -1, true, true),
OLMTCase::new(6, 4, -2, true, false),
OLMTCase::new(7, 4, -1, true, true),
OLMTCase::new(8, 4, -2, true, false),
);
for case in cases.iter() {
let mut pos = one_long_multi_three(case.i, case.k);
let (val, _) = eval(&pos);
assert_eq!(case.exp_val, val, "{:?}", case);
let part = if case.i == 0 { 0 } else { 1 };
let open = CPosMove::new(part, 0, 0, Side::Left);
pos.make_move(open);
// Once the first chain is opened, capturing the first coin
// is the only move to consider
assert_eq!(1, moves_to_consider(&mut pos).len());
let (val, best_move) = eval(&pos);
assert_eq!(-case.exp_val, val, "{:?}", case);
assert_eq!(1, pos.make_move(best_move.unwrap()).coins_captured);
let (val, best_move) = eval(&pos);
if case.i > 0 {
assert_eq!(2, moves_to_consider(&mut pos).len());
}
assert_eq!(-case.exp_val-1, val, "{:?}", case);
let mut ok_moves: Vec<CPosMove> = Vec::with_capacity(2);
if case.taking_optimal {
ok_moves.push(CPosMove::new(part, 1, 0, Side::Right));
}
if case.ddeal_optimal {
ok_moves.push(CPosMove::new(part, 2, 0, Side::Right));
}
assert!(ok_moves.iter().any(|&m| pos.moves_equivalent(m, best_move.unwrap())),
"{:?} {:?} {}", case, ok_moves, best_move.unwrap());
}
}
#[test]
fn multiple_loony_parts() {
let mut pos = CompoundPosition::new(vec!(make_chain(2), make_chain(2)));
pos.make_move(CPosMove::new(0, 0, 0, Side::Left));
pos.make_move(CPosMove::new(1, 0, 0, Side::Left));
assert_eq!(1, moves_to_consider(&mut pos).len());
}
// For use in generative tests
|
let mut pos = SimplePosition::new_game(width, height);
let mut moves = pos.legal_moves();
moves.as_mut_slice().shuffle(r);
let max_remaining_moves = 9; // Limits running cost of naive minimax
let min_move_count: usize = if moves.len() > max_remaining_moves {
moves.len() - max_remaining_moves
} else {
0
};
let move_count = r.gen_range(min_move_count..moves.len() + 1);
for i in 0..move_count {
let m = moves[i];
pos.make_move(m);
}
pos
}
// Dumb evaluation algorithm to compare to optimised one
fn naive_minimax(pos: &mut SimplePosition) -> isize {
let moves = pos.legal_moves();
if moves.is_empty() {
return 0;
}
let mut result = isize::MIN;
for &m in &moves {
let outcome = pos.make_move(m);
let captures = outcome.coins_captured as isize;
let m_val = if captures > 0 {
captures + naive_minimax(pos)
} else {
-naive_minimax(pos)
};
pos.undo_move(m);
result = cmp::max(result, m_val);
}
result
}
#[test]
fn matches_naive_minimax() {
let test_time_s = 10 as f64;
let mut seed: [u8; 32] = [0; 32];
seed[0] = 123;
let mut r: StdRng = SeedableRng::from_seed(seed);
let mut i = 0;
let start_time = Instant::now();
loop {
let mut pos = make_random_pos(&mut r);
let expected_val = naive_minimax(&mut pos);
let (val, best_move) = eval(&pos);
assert_eq!(expected_val, val, "SimplePosition {} value matches naive minimax", i);
if!pos.is_end_of_game() {
let best_move = best_move.unwrap();
let outcome = pos.make_move(best_move);
let captures = outcome.coins_captured as isize;
let (next_val, _) = eval(&pos);
let expected_next_val = if captures > 0 {
expected_val - captures
} else {
-expected_val
};
assert_eq!(expected_next_val, next_val);
}
let elapsed = start_time.elapsed();
if elapsed.as_seconds_f64() >= test_time_s {
break;
}
i += 1;
}
}
// TODO: Test that rotations and reflections do not affect the evaluation
// #[test]
// fn eval_p50() {
// let mut pos = p50();
// let (val, best_move) = eval(&pos);
// let best_move = best_move.unwrap();
// assert_eq!(4, val);
// assert!(pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Right})
// || pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Bottom})
// || pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Left}));
// }
}
|
fn make_random_pos(r: &mut StdRng) -> SimplePosition {
let width: usize = r.gen_range(1..4);
let height: usize = r.gen_range(1..4);
|
random_line_split
|
eval.rs
|
/*
Copyright 2017-2020 Andrew Medworth <[email protected]>
This file is part of Dots-and-Boxes Engine.
Dots-and-Boxes Engine is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Dots-and-Boxes Engine 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Dots-and-Boxes Engine. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::game::{Move, Position, SimplePosition, CompoundPosition, Side, CPosMove};
use crate::nimstring::{self, NimstringPosition};
use std::collections::HashMap;
use std::isize;
pub trait EvaluablePosition<M> : NimstringPosition<M> {
// Given a loony position and the capture, find the corresponding double-dealing move.
// Behaviour on a non-loony position is undefined.
fn find_ddeal_move(&self, m: M) -> M;
}
impl EvaluablePosition<Move> for SimplePosition {
fn find_ddeal_move(self: &SimplePosition, capture: Move) -> Move {
// (capture.x, capture.y) might be the valency-1 coin or the valency-2 one
let (v2_x, v2_y, excl_side) = if self.valency(capture.x, capture.y) == 1 {
let (x, y) = self.offset(capture.x, capture.y, capture.side).unwrap();
(x, y, capture.side.opposite())
} else {
(capture.x, capture.y, capture.side)
};
if self.valency(v2_x, v2_y)!= 2 {
panic!("Expected ({},{}) to have valency 2, found {} in {}",
v2_x, v2_y, self.valency(v2_x, v2_y), self);
}
for s in Side::all_except(excl_side) {
if self.is_legal_move(Move{x: v2_x, y: v2_y, side: s}) {
return Move{x: v2_x, y: v2_y, side: s};
}
}
panic!("Could not find double-dealing move corresponding to {} in {}", capture, self);
}
}
impl EvaluablePosition<CPosMove> for CompoundPosition {
fn find_ddeal_move(self: &CompoundPosition, capture: CPosMove) -> CPosMove {
CPosMove{part: capture.part, m: self.parts[capture.part].find_ddeal_move(capture.m)}
}
}
// Evaluate a position given a set of moves to consider
fn eval_moves<M, P>(pos: &mut P, moves: &Vec<M>,
cache: &mut HashMap<usize, (isize, M)>) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> {
if moves.is_empty() {
return (0, None);
}
let mut value = isize::MIN;
let mut best_move = moves[0];
for &m in moves {
let outcome = pos.make_move(m);
let sign = if outcome.coins_captured > 0 { 1 } else { -1 };
let (next_val, _) = eval_cache(pos, cache);
let sub_val = (outcome.coins_captured as isize) + sign * next_val;
pos.undo_move(m);
if sub_val > value {
value = sub_val;
best_move = m;
}
}
cache.insert(pos.zhash(), (value, best_move));
(value, Some(best_move))
}
// Determine what moves deserve consideration in a given position
fn moves_to_consider<M, P>(pos: &mut P) -> Vec<M>
where M: Copy, P: EvaluablePosition<M> {
let legal_moves = pos.legal_moves();
// If there are any captures which don't affect looniness, just go ahead and make those
let is_loony = pos.is_loony();
let mut capture: Option<M> = None;
for &m in &legal_moves {
let captures = pos.would_capture(m);
if captures == 0 {
continue;
}
capture = Some(m);
if!is_loony || nimstring::would_be_loony(pos, m)
|
}
// Consider only capturing all and double-dealing in the loony case
// TODO: Use other canonical play results to further reduce the set of moves considered
if is_loony {
let capture = capture.unwrap();
let ddeal_move = pos.find_ddeal_move(capture);
vec!(capture, ddeal_move)
} else {
legal_moves
}
}
fn eval_cache<M, P>(pos: &mut P, cache: &mut HashMap<usize, (isize, M)>) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> {
if let Some(&(val, best_move)) = cache.get(&pos.zhash()) {
return (val, Some(best_move));
}
let moves = moves_to_consider(pos);
eval_moves(pos, &moves, cache)
}
// Calculate the value function of a given position and a move which achieves that value
pub fn eval<M, P>(pos: &P) -> (isize, Option<M>)
where M: Copy, P: EvaluablePosition<M> + Clone {
let mut cache = HashMap::new();
let mut pos = pos.clone();
eval_cache(&mut pos, &mut cache)
}
#[cfg(test)]
mod test {
use crate::eval::*;
use crate::examples::*;
use rand::{Rng, SeedableRng};
use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use std::cmp;
use time::Instant;
#[test]
fn eval_chain() {
for i in 1..10 {
let mut chain = make_chain(i);
let (val, _) = eval(&chain);
let expected_val = -(i as isize);
assert_eq!(expected_val, val, "Closed {}-chain", i);
chain.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&chain);
assert_eq!(-expected_val, val, "Opened {}-chain", i);
assert!(chain.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
}
}
#[test]
fn eval_double_chain() {
let (val, _) = eval(&double_chain(1));
assert_eq!(0, val);
for i in 2..10 {
let mut pos = double_chain(i);
let (val, _) = eval(&pos);
let expected_val = 4 - 2*(i as isize);
assert_eq!(expected_val, val, "Evaluation of double chain length {}", i);
pos.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&pos);
assert_eq!(-expected_val, val, "Evaluation of opened double chain length {}", i);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
}
}
#[test]
fn eval_multi_chains() {
let mut pos = multi_chains(3, 4);
let (val, _) = eval(&pos);
assert_eq!(-2, val);
pos.make_move(Move{x: 0, y: 0, side: Side::Left});
let (val, best_move) = eval(&pos);
assert_eq!(2, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 0, y: 0, side: Side::Right}));
pos.make_move(Move{x: 0, y: 0, side: Side::Right});
let (val, best_move) = eval(&pos);
assert_eq!(1, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 1, y: 0, side: Side::Right}));
pos.make_move(Move{x: 1, y: 0, side: Side::Right});
let (val, best_move) = eval(&pos);
assert_eq!(0, val);
assert!(pos.moves_equivalent(best_move.unwrap(), Move{x: 2, y: 0, side: Side::Right}));
pos.make_move(Move{x: 2, y: 0, side: Side::Right});
let (val, _) = eval(&pos);
assert_eq!(-1, val);
}
#[test]
fn eval_double_loop() {
for i in 2..8 {
let mut pos = double_loop(i);
let (val, _) = eval(&pos);
let expected_val = 8 - 4*(i as isize);
assert_eq!(expected_val, val, "Evaluation of double loop width {}", i);
pos.make_move(Move{x: 0, y: 0, side: Side::Right});
let (val, _) = eval(&pos);
assert_eq!(-expected_val, val, "Evaluation of opened double loop width {}", i);
}
}
#[test]
fn eval_ex3p1() {
let mut pos = ex3p1();
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
assert_eq!(3, val);
assert!(pos.moves_equivalent(best_move, Move{x: 2, y: 1, side: Side::Bottom}));
pos.make_move(Move{x: 2, y: 1, side: Side::Bottom});
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
assert_eq!(-3, val);
assert!(pos.moves_equivalent(best_move, Move{x: 0, y: 0, side: Side::Bottom}));
pos.make_move(Move{x: 0, y: 0, side: Side::Bottom});
let (val, _) = eval(&pos);
assert_eq!(3, val);
pos.undo_move(Move{x: 0, y: 0, side: Side::Bottom});
pos.make_move(Move{x: 0, y: 2, side: Side::Left});
let (val, _) = eval(&pos);
assert_eq!(5, val);
}
#[test]
fn eval_ex3p12() {
let mut pos = ex3p12();
let (val, best_move) = eval(&pos);
let best_move = best_move.unwrap();
let expected_val = 9;
assert_eq!(expected_val, val);
assert!(pos.moves_equivalent(best_move, Move{x: 4, y: 0, side: Side::Bottom}));
pos.make_move(Move{x: 4, y: 0, side: Side::Bottom});
let (val, _) = eval(&pos);
assert_eq!(-expected_val, val);
}
#[derive(Debug)]
struct OLMTCase {
i: usize,
k: usize,
exp_val: isize,
taking_optimal: bool,
ddeal_optimal: bool,
}
impl OLMTCase {
fn new(i: usize, k: usize, exp_val: isize,
taking_optimal: bool, ddeal_optimal: bool) -> OLMTCase {
OLMTCase{i: i, k: k, exp_val: exp_val,
taking_optimal: taking_optimal, ddeal_optimal: ddeal_optimal}
}
}
#[test]
fn eval_one_long_multi_three() {
// Check the P_{i,4} table from the paper
let cases = vec!(
OLMTCase::new(0, 4, -4, true, false),
OLMTCase::new(1, 4, -3, false, true),
OLMTCase::new(2, 4, -2, false, true),
OLMTCase::new(3, 4, -1, true, true),
OLMTCase::new(4, 4, -2, true, false),
OLMTCase::new(5, 4, -1, true, true),
OLMTCase::new(6, 4, -2, true, false),
OLMTCase::new(7, 4, -1, true, true),
OLMTCase::new(8, 4, -2, true, false),
);
for case in cases.iter() {
let mut pos = one_long_multi_three(case.i, case.k);
let (val, _) = eval(&pos);
assert_eq!(case.exp_val, val, "{:?}", case);
let part = if case.i == 0 { 0 } else { 1 };
let open = CPosMove::new(part, 0, 0, Side::Left);
pos.make_move(open);
// Once the first chain is opened, capturing the first coin
// is the only move to consider
assert_eq!(1, moves_to_consider(&mut pos).len());
let (val, best_move) = eval(&pos);
assert_eq!(-case.exp_val, val, "{:?}", case);
assert_eq!(1, pos.make_move(best_move.unwrap()).coins_captured);
let (val, best_move) = eval(&pos);
if case.i > 0 {
assert_eq!(2, moves_to_consider(&mut pos).len());
}
assert_eq!(-case.exp_val-1, val, "{:?}", case);
let mut ok_moves: Vec<CPosMove> = Vec::with_capacity(2);
if case.taking_optimal {
ok_moves.push(CPosMove::new(part, 1, 0, Side::Right));
}
if case.ddeal_optimal {
ok_moves.push(CPosMove::new(part, 2, 0, Side::Right));
}
assert!(ok_moves.iter().any(|&m| pos.moves_equivalent(m, best_move.unwrap())),
"{:?} {:?} {}", case, ok_moves, best_move.unwrap());
}
}
#[test]
fn multiple_loony_parts() {
let mut pos = CompoundPosition::new(vec!(make_chain(2), make_chain(2)));
pos.make_move(CPosMove::new(0, 0, 0, Side::Left));
pos.make_move(CPosMove::new(1, 0, 0, Side::Left));
assert_eq!(1, moves_to_consider(&mut pos).len());
}
// For use in generative tests
fn make_random_pos(r: &mut StdRng) -> SimplePosition {
let width: usize = r.gen_range(1..4);
let height: usize = r.gen_range(1..4);
let mut pos = SimplePosition::new_game(width, height);
let mut moves = pos.legal_moves();
moves.as_mut_slice().shuffle(r);
let max_remaining_moves = 9; // Limits running cost of naive minimax
let min_move_count: usize = if moves.len() > max_remaining_moves {
moves.len() - max_remaining_moves
} else {
0
};
let move_count = r.gen_range(min_move_count..moves.len() + 1);
for i in 0..move_count {
let m = moves[i];
pos.make_move(m);
}
pos
}
// Dumb evaluation algorithm to compare to optimised one
fn naive_minimax(pos: &mut SimplePosition) -> isize {
let moves = pos.legal_moves();
if moves.is_empty() {
return 0;
}
let mut result = isize::MIN;
for &m in &moves {
let outcome = pos.make_move(m);
let captures = outcome.coins_captured as isize;
let m_val = if captures > 0 {
captures + naive_minimax(pos)
} else {
-naive_minimax(pos)
};
pos.undo_move(m);
result = cmp::max(result, m_val);
}
result
}
#[test]
fn matches_naive_minimax() {
let test_time_s = 10 as f64;
let mut seed: [u8; 32] = [0; 32];
seed[0] = 123;
let mut r: StdRng = SeedableRng::from_seed(seed);
let mut i = 0;
let start_time = Instant::now();
loop {
let mut pos = make_random_pos(&mut r);
let expected_val = naive_minimax(&mut pos);
let (val, best_move) = eval(&pos);
assert_eq!(expected_val, val, "SimplePosition {} value matches naive minimax", i);
if!pos.is_end_of_game() {
let best_move = best_move.unwrap();
let outcome = pos.make_move(best_move);
let captures = outcome.coins_captured as isize;
let (next_val, _) = eval(&pos);
let expected_next_val = if captures > 0 {
expected_val - captures
} else {
-expected_val
};
assert_eq!(expected_next_val, next_val);
}
let elapsed = start_time.elapsed();
if elapsed.as_seconds_f64() >= test_time_s {
break;
}
i += 1;
}
}
// TODO: Test that rotations and reflections do not affect the evaluation
// #[test]
// fn eval_p50() {
// let mut pos = p50();
// let (val, best_move) = eval(&pos);
// let best_move = best_move.unwrap();
// assert_eq!(4, val);
// assert!(pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Right})
// || pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Bottom})
// || pos.moves_equivalent(best_move, Move{x: 0, y: 3, side: Side::Left}));
// }
}
|
{
return vec!(m);
}
|
conditional_block
|
monitor.rs
|
use winapi::{
shared::{
minwindef::{BOOL, DWORD, LPARAM, TRUE, WORD},
windef::{HDC, HMONITOR, HWND, LPRECT, POINT},
},
um::{wingdi, winuser},
};
use std::{
collections::{BTreeSet, VecDeque},
io, mem, ptr,
};
use super::util;
use crate::{
dpi::{PhysicalPosition, PhysicalSize},
monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode},
platform_impl::platform::{
dpi::{dpi_to_scale_factor, get_monitor_dpi},
window::Window,
},
};
#[derive(Clone)]
pub struct VideoMode {
pub(crate) size: (u32, u32),
pub(crate) bit_depth: u16,
pub(crate) refresh_rate: u16,
pub(crate) monitor: MonitorHandle,
pub(crate) native_video_mode: wingdi::DEVMODEW,
}
impl PartialEq for VideoMode {
fn eq(&self, other: &Self) -> bool {
self.size == other.size
&& self.bit_depth == other.bit_depth
&& self.refresh_rate == other.refresh_rate
&& self.monitor == other.monitor
}
}
impl Eq for VideoMode {}
impl std::hash::Hash for VideoMode {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.size.hash(state);
self.bit_depth.hash(state);
self.refresh_rate.hash(state);
self.monitor.hash(state);
}
}
impl std::fmt::Debug for VideoMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VideoMode")
.field("size", &self.size)
.field("bit_depth", &self.bit_depth)
.field("refresh_rate", &self.refresh_rate)
.field("monitor", &self.monitor)
.finish()
}
}
impl VideoMode {
pub fn size(&self) -> PhysicalSize<u32> {
self.size.into()
}
pub fn bit_depth(&self) -> u16 {
self.bit_depth
}
pub fn refresh_rate(&self) -> u16 {
self.refresh_rate
}
pub fn monitor(&self) -> RootMonitorHandle {
RootMonitorHandle {
inner: self.monitor.clone(),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct MonitorHandle(HMONITOR);
// Send is not implemented for HMONITOR, we have to wrap it and implement it manually.
// For more info see:
// https://github.com/retep998/winapi-rs/issues/360
// https://github.com/retep998/winapi-rs/issues/396
unsafe impl Send for MonitorHandle {}
unsafe extern "system" fn monitor_enum_proc(
hmonitor: HMONITOR,
_hdc: HDC,
_place: LPRECT,
data: LPARAM,
) -> BOOL {
let monitors = data as *mut VecDeque<MonitorHandle>;
(*monitors).push_back(MonitorHandle::new(hmonitor));
TRUE // continue enumeration
}
pub fn available_monitors() -> VecDeque<MonitorHandle> {
let mut monitors: VecDeque<MonitorHandle> = VecDeque::new();
unsafe {
winuser::EnumDisplayMonitors(
ptr::null_mut(),
ptr::null_mut(),
Some(monitor_enum_proc),
&mut monitors as *mut _ as LPARAM,
);
}
monitors
}
pub fn primary_monitor() -> MonitorHandle {
const ORIGIN: POINT = POINT { x: 0, y: 0 };
let hmonitor = unsafe { winuser::MonitorFromPoint(ORIGIN, winuser::MONITOR_DEFAULTTOPRIMARY) };
MonitorHandle::new(hmonitor)
}
pub fn current_monitor(hwnd: HWND) -> MonitorHandle {
let hmonitor = unsafe { winuser::MonitorFromWindow(hwnd, winuser::MONITOR_DEFAULTTONEAREST) };
MonitorHandle::new(hmonitor)
}
impl Window {
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
available_monitors()
}
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
let monitor = primary_monitor();
Some(RootMonitorHandle { inner: monitor })
}
}
pub(crate) fn get_monitor_info(hmonitor: HMONITOR) -> Result<winuser::MONITORINFOEXW, io::Error> {
let mut monitor_info: winuser::MONITORINFOEXW = unsafe { mem::zeroed() };
monitor_info.cbSize = mem::size_of::<winuser::MONITORINFOEXW>() as DWORD;
let status = unsafe {
winuser::GetMonitorInfoW(
hmonitor,
&mut monitor_info as *mut winuser::MONITORINFOEXW as *mut winuser::MONITORINFO,
)
};
if status == 0 {
Err(io::Error::last_os_error())
} else {
Ok(monitor_info)
}
}
impl MonitorHandle {
pub(crate) fn new(hmonitor: HMONITOR) -> Self
|
#[inline]
pub fn name(&self) -> Option<String> {
let monitor_info = get_monitor_info(self.0).unwrap();
Some(util::wchar_ptr_to_string(monitor_info.szDevice.as_ptr()))
}
#[inline]
pub fn native_identifier(&self) -> String {
self.name().unwrap()
}
#[inline]
pub fn hmonitor(&self) -> HMONITOR {
self.0
}
#[inline]
pub fn size(&self) -> PhysicalSize<u32> {
let monitor_info = get_monitor_info(self.0).unwrap();
PhysicalSize {
width: (monitor_info.rcMonitor.right - monitor_info.rcMonitor.left) as u32,
height: (monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top) as u32,
}
}
#[inline]
pub fn position(&self) -> PhysicalPosition<i32> {
let monitor_info = get_monitor_info(self.0).unwrap();
PhysicalPosition {
x: monitor_info.rcMonitor.left,
y: monitor_info.rcMonitor.top,
}
}
#[inline]
pub fn scale_factor(&self) -> f64 {
dpi_to_scale_factor(get_monitor_dpi(self.0).unwrap_or(96))
}
#[inline]
pub fn video_modes(&self) -> impl Iterator<Item = RootVideoMode> {
// EnumDisplaySettingsExW can return duplicate values (or some of the
// fields are probably changing, but we aren't looking at those fields
// anyway), so we're using a BTreeSet deduplicate
let mut modes = BTreeSet::new();
let mut i = 0;
loop {
unsafe {
let monitor_info = get_monitor_info(self.0).unwrap();
let device_name = monitor_info.szDevice.as_ptr();
let mut mode: wingdi::DEVMODEW = mem::zeroed();
mode.dmSize = mem::size_of_val(&mode) as WORD;
if winuser::EnumDisplaySettingsExW(device_name, i, &mut mode, 0) == 0 {
break;
}
i += 1;
const REQUIRED_FIELDS: DWORD = wingdi::DM_BITSPERPEL
| wingdi::DM_PELSWIDTH
| wingdi::DM_PELSHEIGHT
| wingdi::DM_DISPLAYFREQUENCY;
assert!(mode.dmFields & REQUIRED_FIELDS == REQUIRED_FIELDS);
modes.insert(RootVideoMode {
video_mode: VideoMode {
size: (mode.dmPelsWidth, mode.dmPelsHeight),
bit_depth: mode.dmBitsPerPel as u16,
refresh_rate: mode.dmDisplayFrequency as u16,
monitor: self.clone(),
native_video_mode: mode,
},
});
}
}
modes.into_iter()
}
}
|
{
MonitorHandle(hmonitor)
}
|
identifier_body
|
monitor.rs
|
use winapi::{
shared::{
minwindef::{BOOL, DWORD, LPARAM, TRUE, WORD},
windef::{HDC, HMONITOR, HWND, LPRECT, POINT},
},
um::{wingdi, winuser},
};
use std::{
collections::{BTreeSet, VecDeque},
io, mem, ptr,
};
use super::util;
use crate::{
dpi::{PhysicalPosition, PhysicalSize},
monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode},
platform_impl::platform::{
dpi::{dpi_to_scale_factor, get_monitor_dpi},
window::Window,
},
};
#[derive(Clone)]
pub struct VideoMode {
pub(crate) size: (u32, u32),
pub(crate) bit_depth: u16,
pub(crate) refresh_rate: u16,
pub(crate) monitor: MonitorHandle,
|
}
impl PartialEq for VideoMode {
fn eq(&self, other: &Self) -> bool {
self.size == other.size
&& self.bit_depth == other.bit_depth
&& self.refresh_rate == other.refresh_rate
&& self.monitor == other.monitor
}
}
impl Eq for VideoMode {}
impl std::hash::Hash for VideoMode {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.size.hash(state);
self.bit_depth.hash(state);
self.refresh_rate.hash(state);
self.monitor.hash(state);
}
}
impl std::fmt::Debug for VideoMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VideoMode")
.field("size", &self.size)
.field("bit_depth", &self.bit_depth)
.field("refresh_rate", &self.refresh_rate)
.field("monitor", &self.monitor)
.finish()
}
}
impl VideoMode {
pub fn size(&self) -> PhysicalSize<u32> {
self.size.into()
}
pub fn bit_depth(&self) -> u16 {
self.bit_depth
}
pub fn refresh_rate(&self) -> u16 {
self.refresh_rate
}
pub fn monitor(&self) -> RootMonitorHandle {
RootMonitorHandle {
inner: self.monitor.clone(),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct MonitorHandle(HMONITOR);
// Send is not implemented for HMONITOR, we have to wrap it and implement it manually.
// For more info see:
// https://github.com/retep998/winapi-rs/issues/360
// https://github.com/retep998/winapi-rs/issues/396
unsafe impl Send for MonitorHandle {}
unsafe extern "system" fn monitor_enum_proc(
hmonitor: HMONITOR,
_hdc: HDC,
_place: LPRECT,
data: LPARAM,
) -> BOOL {
let monitors = data as *mut VecDeque<MonitorHandle>;
(*monitors).push_back(MonitorHandle::new(hmonitor));
TRUE // continue enumeration
}
pub fn available_monitors() -> VecDeque<MonitorHandle> {
let mut monitors: VecDeque<MonitorHandle> = VecDeque::new();
unsafe {
winuser::EnumDisplayMonitors(
ptr::null_mut(),
ptr::null_mut(),
Some(monitor_enum_proc),
&mut monitors as *mut _ as LPARAM,
);
}
monitors
}
pub fn primary_monitor() -> MonitorHandle {
const ORIGIN: POINT = POINT { x: 0, y: 0 };
let hmonitor = unsafe { winuser::MonitorFromPoint(ORIGIN, winuser::MONITOR_DEFAULTTOPRIMARY) };
MonitorHandle::new(hmonitor)
}
pub fn current_monitor(hwnd: HWND) -> MonitorHandle {
let hmonitor = unsafe { winuser::MonitorFromWindow(hwnd, winuser::MONITOR_DEFAULTTONEAREST) };
MonitorHandle::new(hmonitor)
}
impl Window {
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
available_monitors()
}
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
let monitor = primary_monitor();
Some(RootMonitorHandle { inner: monitor })
}
}
pub(crate) fn get_monitor_info(hmonitor: HMONITOR) -> Result<winuser::MONITORINFOEXW, io::Error> {
let mut monitor_info: winuser::MONITORINFOEXW = unsafe { mem::zeroed() };
monitor_info.cbSize = mem::size_of::<winuser::MONITORINFOEXW>() as DWORD;
let status = unsafe {
winuser::GetMonitorInfoW(
hmonitor,
&mut monitor_info as *mut winuser::MONITORINFOEXW as *mut winuser::MONITORINFO,
)
};
if status == 0 {
Err(io::Error::last_os_error())
} else {
Ok(monitor_info)
}
}
impl MonitorHandle {
pub(crate) fn new(hmonitor: HMONITOR) -> Self {
MonitorHandle(hmonitor)
}
#[inline]
pub fn name(&self) -> Option<String> {
let monitor_info = get_monitor_info(self.0).unwrap();
Some(util::wchar_ptr_to_string(monitor_info.szDevice.as_ptr()))
}
#[inline]
pub fn native_identifier(&self) -> String {
self.name().unwrap()
}
#[inline]
pub fn hmonitor(&self) -> HMONITOR {
self.0
}
#[inline]
pub fn size(&self) -> PhysicalSize<u32> {
let monitor_info = get_monitor_info(self.0).unwrap();
PhysicalSize {
width: (monitor_info.rcMonitor.right - monitor_info.rcMonitor.left) as u32,
height: (monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top) as u32,
}
}
#[inline]
pub fn position(&self) -> PhysicalPosition<i32> {
let monitor_info = get_monitor_info(self.0).unwrap();
PhysicalPosition {
x: monitor_info.rcMonitor.left,
y: monitor_info.rcMonitor.top,
}
}
#[inline]
pub fn scale_factor(&self) -> f64 {
dpi_to_scale_factor(get_monitor_dpi(self.0).unwrap_or(96))
}
#[inline]
pub fn video_modes(&self) -> impl Iterator<Item = RootVideoMode> {
// EnumDisplaySettingsExW can return duplicate values (or some of the
// fields are probably changing, but we aren't looking at those fields
// anyway), so we're using a BTreeSet deduplicate
let mut modes = BTreeSet::new();
let mut i = 0;
loop {
unsafe {
let monitor_info = get_monitor_info(self.0).unwrap();
let device_name = monitor_info.szDevice.as_ptr();
let mut mode: wingdi::DEVMODEW = mem::zeroed();
mode.dmSize = mem::size_of_val(&mode) as WORD;
if winuser::EnumDisplaySettingsExW(device_name, i, &mut mode, 0) == 0 {
break;
}
i += 1;
const REQUIRED_FIELDS: DWORD = wingdi::DM_BITSPERPEL
| wingdi::DM_PELSWIDTH
| wingdi::DM_PELSHEIGHT
| wingdi::DM_DISPLAYFREQUENCY;
assert!(mode.dmFields & REQUIRED_FIELDS == REQUIRED_FIELDS);
modes.insert(RootVideoMode {
video_mode: VideoMode {
size: (mode.dmPelsWidth, mode.dmPelsHeight),
bit_depth: mode.dmBitsPerPel as u16,
refresh_rate: mode.dmDisplayFrequency as u16,
monitor: self.clone(),
native_video_mode: mode,
},
});
}
}
modes.into_iter()
}
}
|
pub(crate) native_video_mode: wingdi::DEVMODEW,
|
random_line_split
|
monitor.rs
|
use winapi::{
shared::{
minwindef::{BOOL, DWORD, LPARAM, TRUE, WORD},
windef::{HDC, HMONITOR, HWND, LPRECT, POINT},
},
um::{wingdi, winuser},
};
use std::{
collections::{BTreeSet, VecDeque},
io, mem, ptr,
};
use super::util;
use crate::{
dpi::{PhysicalPosition, PhysicalSize},
monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode},
platform_impl::platform::{
dpi::{dpi_to_scale_factor, get_monitor_dpi},
window::Window,
},
};
#[derive(Clone)]
pub struct VideoMode {
pub(crate) size: (u32, u32),
pub(crate) bit_depth: u16,
pub(crate) refresh_rate: u16,
pub(crate) monitor: MonitorHandle,
pub(crate) native_video_mode: wingdi::DEVMODEW,
}
impl PartialEq for VideoMode {
fn
|
(&self, other: &Self) -> bool {
self.size == other.size
&& self.bit_depth == other.bit_depth
&& self.refresh_rate == other.refresh_rate
&& self.monitor == other.monitor
}
}
impl Eq for VideoMode {}
impl std::hash::Hash for VideoMode {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.size.hash(state);
self.bit_depth.hash(state);
self.refresh_rate.hash(state);
self.monitor.hash(state);
}
}
impl std::fmt::Debug for VideoMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VideoMode")
.field("size", &self.size)
.field("bit_depth", &self.bit_depth)
.field("refresh_rate", &self.refresh_rate)
.field("monitor", &self.monitor)
.finish()
}
}
impl VideoMode {
pub fn size(&self) -> PhysicalSize<u32> {
self.size.into()
}
pub fn bit_depth(&self) -> u16 {
self.bit_depth
}
pub fn refresh_rate(&self) -> u16 {
self.refresh_rate
}
pub fn monitor(&self) -> RootMonitorHandle {
RootMonitorHandle {
inner: self.monitor.clone(),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct MonitorHandle(HMONITOR);
// Send is not implemented for HMONITOR, we have to wrap it and implement it manually.
// For more info see:
// https://github.com/retep998/winapi-rs/issues/360
// https://github.com/retep998/winapi-rs/issues/396
unsafe impl Send for MonitorHandle {}
unsafe extern "system" fn monitor_enum_proc(
hmonitor: HMONITOR,
_hdc: HDC,
_place: LPRECT,
data: LPARAM,
) -> BOOL {
let monitors = data as *mut VecDeque<MonitorHandle>;
(*monitors).push_back(MonitorHandle::new(hmonitor));
TRUE // continue enumeration
}
pub fn available_monitors() -> VecDeque<MonitorHandle> {
let mut monitors: VecDeque<MonitorHandle> = VecDeque::new();
unsafe {
winuser::EnumDisplayMonitors(
ptr::null_mut(),
ptr::null_mut(),
Some(monitor_enum_proc),
&mut monitors as *mut _ as LPARAM,
);
}
monitors
}
pub fn primary_monitor() -> MonitorHandle {
const ORIGIN: POINT = POINT { x: 0, y: 0 };
let hmonitor = unsafe { winuser::MonitorFromPoint(ORIGIN, winuser::MONITOR_DEFAULTTOPRIMARY) };
MonitorHandle::new(hmonitor)
}
pub fn current_monitor(hwnd: HWND) -> MonitorHandle {
let hmonitor = unsafe { winuser::MonitorFromWindow(hwnd, winuser::MONITOR_DEFAULTTONEAREST) };
MonitorHandle::new(hmonitor)
}
impl Window {
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
available_monitors()
}
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
let monitor = primary_monitor();
Some(RootMonitorHandle { inner: monitor })
}
}
pub(crate) fn get_monitor_info(hmonitor: HMONITOR) -> Result<winuser::MONITORINFOEXW, io::Error> {
let mut monitor_info: winuser::MONITORINFOEXW = unsafe { mem::zeroed() };
monitor_info.cbSize = mem::size_of::<winuser::MONITORINFOEXW>() as DWORD;
let status = unsafe {
winuser::GetMonitorInfoW(
hmonitor,
&mut monitor_info as *mut winuser::MONITORINFOEXW as *mut winuser::MONITORINFO,
)
};
if status == 0 {
Err(io::Error::last_os_error())
} else {
Ok(monitor_info)
}
}
impl MonitorHandle {
pub(crate) fn new(hmonitor: HMONITOR) -> Self {
MonitorHandle(hmonitor)
}
#[inline]
pub fn name(&self) -> Option<String> {
let monitor_info = get_monitor_info(self.0).unwrap();
Some(util::wchar_ptr_to_string(monitor_info.szDevice.as_ptr()))
}
#[inline]
pub fn native_identifier(&self) -> String {
self.name().unwrap()
}
#[inline]
pub fn hmonitor(&self) -> HMONITOR {
self.0
}
#[inline]
pub fn size(&self) -> PhysicalSize<u32> {
let monitor_info = get_monitor_info(self.0).unwrap();
PhysicalSize {
width: (monitor_info.rcMonitor.right - monitor_info.rcMonitor.left) as u32,
height: (monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top) as u32,
}
}
#[inline]
pub fn position(&self) -> PhysicalPosition<i32> {
let monitor_info = get_monitor_info(self.0).unwrap();
PhysicalPosition {
x: monitor_info.rcMonitor.left,
y: monitor_info.rcMonitor.top,
}
}
#[inline]
pub fn scale_factor(&self) -> f64 {
dpi_to_scale_factor(get_monitor_dpi(self.0).unwrap_or(96))
}
#[inline]
pub fn video_modes(&self) -> impl Iterator<Item = RootVideoMode> {
// EnumDisplaySettingsExW can return duplicate values (or some of the
// fields are probably changing, but we aren't looking at those fields
// anyway), so we're using a BTreeSet deduplicate
let mut modes = BTreeSet::new();
let mut i = 0;
loop {
unsafe {
let monitor_info = get_monitor_info(self.0).unwrap();
let device_name = monitor_info.szDevice.as_ptr();
let mut mode: wingdi::DEVMODEW = mem::zeroed();
mode.dmSize = mem::size_of_val(&mode) as WORD;
if winuser::EnumDisplaySettingsExW(device_name, i, &mut mode, 0) == 0 {
break;
}
i += 1;
const REQUIRED_FIELDS: DWORD = wingdi::DM_BITSPERPEL
| wingdi::DM_PELSWIDTH
| wingdi::DM_PELSHEIGHT
| wingdi::DM_DISPLAYFREQUENCY;
assert!(mode.dmFields & REQUIRED_FIELDS == REQUIRED_FIELDS);
modes.insert(RootVideoMode {
video_mode: VideoMode {
size: (mode.dmPelsWidth, mode.dmPelsHeight),
bit_depth: mode.dmBitsPerPel as u16,
refresh_rate: mode.dmDisplayFrequency as u16,
monitor: self.clone(),
native_video_mode: mode,
},
});
}
}
modes.into_iter()
}
}
|
eq
|
identifier_name
|
monitor.rs
|
use winapi::{
shared::{
minwindef::{BOOL, DWORD, LPARAM, TRUE, WORD},
windef::{HDC, HMONITOR, HWND, LPRECT, POINT},
},
um::{wingdi, winuser},
};
use std::{
collections::{BTreeSet, VecDeque},
io, mem, ptr,
};
use super::util;
use crate::{
dpi::{PhysicalPosition, PhysicalSize},
monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode},
platform_impl::platform::{
dpi::{dpi_to_scale_factor, get_monitor_dpi},
window::Window,
},
};
#[derive(Clone)]
pub struct VideoMode {
pub(crate) size: (u32, u32),
pub(crate) bit_depth: u16,
pub(crate) refresh_rate: u16,
pub(crate) monitor: MonitorHandle,
pub(crate) native_video_mode: wingdi::DEVMODEW,
}
impl PartialEq for VideoMode {
fn eq(&self, other: &Self) -> bool {
self.size == other.size
&& self.bit_depth == other.bit_depth
&& self.refresh_rate == other.refresh_rate
&& self.monitor == other.monitor
}
}
impl Eq for VideoMode {}
impl std::hash::Hash for VideoMode {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.size.hash(state);
self.bit_depth.hash(state);
self.refresh_rate.hash(state);
self.monitor.hash(state);
}
}
impl std::fmt::Debug for VideoMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VideoMode")
.field("size", &self.size)
.field("bit_depth", &self.bit_depth)
.field("refresh_rate", &self.refresh_rate)
.field("monitor", &self.monitor)
.finish()
}
}
impl VideoMode {
pub fn size(&self) -> PhysicalSize<u32> {
self.size.into()
}
pub fn bit_depth(&self) -> u16 {
self.bit_depth
}
pub fn refresh_rate(&self) -> u16 {
self.refresh_rate
}
pub fn monitor(&self) -> RootMonitorHandle {
RootMonitorHandle {
inner: self.monitor.clone(),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct MonitorHandle(HMONITOR);
// Send is not implemented for HMONITOR, we have to wrap it and implement it manually.
// For more info see:
// https://github.com/retep998/winapi-rs/issues/360
// https://github.com/retep998/winapi-rs/issues/396
unsafe impl Send for MonitorHandle {}
unsafe extern "system" fn monitor_enum_proc(
hmonitor: HMONITOR,
_hdc: HDC,
_place: LPRECT,
data: LPARAM,
) -> BOOL {
let monitors = data as *mut VecDeque<MonitorHandle>;
(*monitors).push_back(MonitorHandle::new(hmonitor));
TRUE // continue enumeration
}
pub fn available_monitors() -> VecDeque<MonitorHandle> {
let mut monitors: VecDeque<MonitorHandle> = VecDeque::new();
unsafe {
winuser::EnumDisplayMonitors(
ptr::null_mut(),
ptr::null_mut(),
Some(monitor_enum_proc),
&mut monitors as *mut _ as LPARAM,
);
}
monitors
}
pub fn primary_monitor() -> MonitorHandle {
const ORIGIN: POINT = POINT { x: 0, y: 0 };
let hmonitor = unsafe { winuser::MonitorFromPoint(ORIGIN, winuser::MONITOR_DEFAULTTOPRIMARY) };
MonitorHandle::new(hmonitor)
}
pub fn current_monitor(hwnd: HWND) -> MonitorHandle {
let hmonitor = unsafe { winuser::MonitorFromWindow(hwnd, winuser::MONITOR_DEFAULTTONEAREST) };
MonitorHandle::new(hmonitor)
}
impl Window {
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
available_monitors()
}
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
let monitor = primary_monitor();
Some(RootMonitorHandle { inner: monitor })
}
}
pub(crate) fn get_monitor_info(hmonitor: HMONITOR) -> Result<winuser::MONITORINFOEXW, io::Error> {
let mut monitor_info: winuser::MONITORINFOEXW = unsafe { mem::zeroed() };
monitor_info.cbSize = mem::size_of::<winuser::MONITORINFOEXW>() as DWORD;
let status = unsafe {
winuser::GetMonitorInfoW(
hmonitor,
&mut monitor_info as *mut winuser::MONITORINFOEXW as *mut winuser::MONITORINFO,
)
};
if status == 0 {
Err(io::Error::last_os_error())
} else
|
}
impl MonitorHandle {
pub(crate) fn new(hmonitor: HMONITOR) -> Self {
MonitorHandle(hmonitor)
}
#[inline]
pub fn name(&self) -> Option<String> {
let monitor_info = get_monitor_info(self.0).unwrap();
Some(util::wchar_ptr_to_string(monitor_info.szDevice.as_ptr()))
}
#[inline]
pub fn native_identifier(&self) -> String {
self.name().unwrap()
}
#[inline]
pub fn hmonitor(&self) -> HMONITOR {
self.0
}
#[inline]
pub fn size(&self) -> PhysicalSize<u32> {
let monitor_info = get_monitor_info(self.0).unwrap();
PhysicalSize {
width: (monitor_info.rcMonitor.right - monitor_info.rcMonitor.left) as u32,
height: (monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top) as u32,
}
}
#[inline]
pub fn position(&self) -> PhysicalPosition<i32> {
let monitor_info = get_monitor_info(self.0).unwrap();
PhysicalPosition {
x: monitor_info.rcMonitor.left,
y: monitor_info.rcMonitor.top,
}
}
#[inline]
pub fn scale_factor(&self) -> f64 {
dpi_to_scale_factor(get_monitor_dpi(self.0).unwrap_or(96))
}
#[inline]
pub fn video_modes(&self) -> impl Iterator<Item = RootVideoMode> {
// EnumDisplaySettingsExW can return duplicate values (or some of the
// fields are probably changing, but we aren't looking at those fields
// anyway), so we're using a BTreeSet deduplicate
let mut modes = BTreeSet::new();
let mut i = 0;
loop {
unsafe {
let monitor_info = get_monitor_info(self.0).unwrap();
let device_name = monitor_info.szDevice.as_ptr();
let mut mode: wingdi::DEVMODEW = mem::zeroed();
mode.dmSize = mem::size_of_val(&mode) as WORD;
if winuser::EnumDisplaySettingsExW(device_name, i, &mut mode, 0) == 0 {
break;
}
i += 1;
const REQUIRED_FIELDS: DWORD = wingdi::DM_BITSPERPEL
| wingdi::DM_PELSWIDTH
| wingdi::DM_PELSHEIGHT
| wingdi::DM_DISPLAYFREQUENCY;
assert!(mode.dmFields & REQUIRED_FIELDS == REQUIRED_FIELDS);
modes.insert(RootVideoMode {
video_mode: VideoMode {
size: (mode.dmPelsWidth, mode.dmPelsHeight),
bit_depth: mode.dmBitsPerPel as u16,
refresh_rate: mode.dmDisplayFrequency as u16,
monitor: self.clone(),
native_video_mode: mode,
},
});
}
}
modes.into_iter()
}
}
|
{
Ok(monitor_info)
}
|
conditional_block
|
divide.rs
|
use crate::Processor;
use crate::executor::{ExecuteSuccess, ExecutorHelper};
use super::ExecuteResult;
use crate::core::instruction::Reg3NoSetFlagsParams;
use crate::core::{fault::Fault, register::BaseReg};
/// Divide operations
pub trait IsaDivide {
fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult;
fn exec_sdiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult;
}
impl IsaDivide for Processor {
fn exec_sdiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult {
if self.condition_passed() {
let rm = self.get_r(params.rm);
let result = if rm == 0 {
if self.integer_zero_divide_trapping_enabled() {
return Err(Fault::DivByZero);
}
0
} else {
let rn = self.get_r(params.rn);
(rn as i32) / (rm as i32)
};
self.set_r(params.rd, result as u32);
return Ok(ExecuteSuccess::Taken { cycles: 2 });
}
Ok(ExecuteSuccess::NotTaken)
}
fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult {
if self.condition_passed() {
let rm = self.get_r(params.rm);
let result = if rm == 0
|
else {
let rn = self.get_r(params.rn);
rn / rm
};
self.set_r(params.rd, result);
return Ok(ExecuteSuccess::Taken { cycles: 2 });
}
Ok(ExecuteSuccess::NotTaken)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{instruction::Instruction, register::Reg};
#[test]
fn test_udiv() {
// arrange
let mut core = Processor::new();
core.set_r(Reg::R0, 0x7d0);
core.set_r(Reg::R1, 0x3);
core.psr.value = 0;
let instruction = Instruction::UDIV {
params: Reg3NoSetFlagsParams {
rd: Reg::R0,
rn: Reg::R0,
rm: Reg::R1,
},
};
// act
let result = core.execute_internal(&instruction);
assert_eq!(result, Ok(ExecuteSuccess::Taken { cycles: 2 }));
assert_eq!(core.get_r(Reg::R0), 0x29a);
assert_eq!(core.get_r(Reg::R1), 0x3);
}
}
|
{
if self.integer_zero_divide_trapping_enabled() {
return Err(Fault::DivByZero);
}
0
}
|
conditional_block
|
divide.rs
|
use crate::Processor;
use crate::executor::{ExecuteSuccess, ExecutorHelper};
use super::ExecuteResult;
use crate::core::instruction::Reg3NoSetFlagsParams;
use crate::core::{fault::Fault, register::BaseReg};
/// Divide operations
pub trait IsaDivide {
fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult;
fn exec_sdiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult;
}
impl IsaDivide for Processor {
fn exec_sdiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult
|
fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult {
if self.condition_passed() {
let rm = self.get_r(params.rm);
let result = if rm == 0 {
if self.integer_zero_divide_trapping_enabled() {
return Err(Fault::DivByZero);
}
0
} else {
let rn = self.get_r(params.rn);
rn / rm
};
self.set_r(params.rd, result);
return Ok(ExecuteSuccess::Taken { cycles: 2 });
}
Ok(ExecuteSuccess::NotTaken)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{instruction::Instruction, register::Reg};
#[test]
fn test_udiv() {
// arrange
let mut core = Processor::new();
core.set_r(Reg::R0, 0x7d0);
core.set_r(Reg::R1, 0x3);
core.psr.value = 0;
let instruction = Instruction::UDIV {
params: Reg3NoSetFlagsParams {
rd: Reg::R0,
rn: Reg::R0,
rm: Reg::R1,
},
};
// act
let result = core.execute_internal(&instruction);
assert_eq!(result, Ok(ExecuteSuccess::Taken { cycles: 2 }));
assert_eq!(core.get_r(Reg::R0), 0x29a);
assert_eq!(core.get_r(Reg::R1), 0x3);
}
}
|
{
if self.condition_passed() {
let rm = self.get_r(params.rm);
let result = if rm == 0 {
if self.integer_zero_divide_trapping_enabled() {
return Err(Fault::DivByZero);
}
0
} else {
let rn = self.get_r(params.rn);
(rn as i32) / (rm as i32)
};
self.set_r(params.rd, result as u32);
return Ok(ExecuteSuccess::Taken { cycles: 2 });
}
Ok(ExecuteSuccess::NotTaken)
}
|
identifier_body
|
divide.rs
|
use crate::Processor;
use crate::executor::{ExecuteSuccess, ExecutorHelper};
use super::ExecuteResult;
use crate::core::instruction::Reg3NoSetFlagsParams;
use crate::core::{fault::Fault, register::BaseReg};
/// Divide operations
pub trait IsaDivide {
fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult;
fn exec_sdiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult;
}
impl IsaDivide for Processor {
fn exec_sdiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult {
if self.condition_passed() {
let rm = self.get_r(params.rm);
let result = if rm == 0 {
if self.integer_zero_divide_trapping_enabled() {
return Err(Fault::DivByZero);
}
0
} else {
let rn = self.get_r(params.rn);
(rn as i32) / (rm as i32)
};
self.set_r(params.rd, result as u32);
return Ok(ExecuteSuccess::Taken { cycles: 2 });
}
Ok(ExecuteSuccess::NotTaken)
}
fn
|
(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult {
if self.condition_passed() {
let rm = self.get_r(params.rm);
let result = if rm == 0 {
if self.integer_zero_divide_trapping_enabled() {
return Err(Fault::DivByZero);
}
0
} else {
let rn = self.get_r(params.rn);
rn / rm
};
self.set_r(params.rd, result);
return Ok(ExecuteSuccess::Taken { cycles: 2 });
}
Ok(ExecuteSuccess::NotTaken)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{instruction::Instruction, register::Reg};
#[test]
fn test_udiv() {
// arrange
let mut core = Processor::new();
core.set_r(Reg::R0, 0x7d0);
core.set_r(Reg::R1, 0x3);
core.psr.value = 0;
let instruction = Instruction::UDIV {
params: Reg3NoSetFlagsParams {
rd: Reg::R0,
rn: Reg::R0,
rm: Reg::R1,
},
};
// act
let result = core.execute_internal(&instruction);
assert_eq!(result, Ok(ExecuteSuccess::Taken { cycles: 2 }));
assert_eq!(core.get_r(Reg::R0), 0x29a);
assert_eq!(core.get_r(Reg::R1), 0x3);
}
}
|
exec_udiv
|
identifier_name
|
divide.rs
|
use crate::Processor;
use crate::executor::{ExecuteSuccess, ExecutorHelper};
use super::ExecuteResult;
use crate::core::instruction::Reg3NoSetFlagsParams;
use crate::core::{fault::Fault, register::BaseReg};
/// Divide operations
pub trait IsaDivide {
fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult;
fn exec_sdiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult;
}
impl IsaDivide for Processor {
fn exec_sdiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult {
if self.condition_passed() {
let rm = self.get_r(params.rm);
let result = if rm == 0 {
if self.integer_zero_divide_trapping_enabled() {
return Err(Fault::DivByZero);
}
0
} else {
let rn = self.get_r(params.rn);
(rn as i32) / (rm as i32)
};
self.set_r(params.rd, result as u32);
|
Ok(ExecuteSuccess::NotTaken)
}
fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult {
if self.condition_passed() {
let rm = self.get_r(params.rm);
let result = if rm == 0 {
if self.integer_zero_divide_trapping_enabled() {
return Err(Fault::DivByZero);
}
0
} else {
let rn = self.get_r(params.rn);
rn / rm
};
self.set_r(params.rd, result);
return Ok(ExecuteSuccess::Taken { cycles: 2 });
}
Ok(ExecuteSuccess::NotTaken)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{instruction::Instruction, register::Reg};
#[test]
fn test_udiv() {
// arrange
let mut core = Processor::new();
core.set_r(Reg::R0, 0x7d0);
core.set_r(Reg::R1, 0x3);
core.psr.value = 0;
let instruction = Instruction::UDIV {
params: Reg3NoSetFlagsParams {
rd: Reg::R0,
rn: Reg::R0,
rm: Reg::R1,
},
};
// act
let result = core.execute_internal(&instruction);
assert_eq!(result, Ok(ExecuteSuccess::Taken { cycles: 2 }));
assert_eq!(core.get_r(Reg::R0), 0x29a);
assert_eq!(core.get_r(Reg::R1), 0x3);
}
}
|
return Ok(ExecuteSuccess::Taken { cycles: 2 });
}
|
random_line_split
|
mod.rs
|
//! A Collection of Header implementations for common HTTP Headers.
//!
//! ## Mime
//!
//! Several header fields use MIME values for their contents. Keeping with the
//! strongly-typed theme, the [mime](http://seanmonstar.github.io/mime.rs) crate
//! is used, such as `ContentType(pub Mime)`.
pub use self::accept::Accept;
pub use self::allow::Allow;
pub use self::authorization::Authorization;
pub use self::cache_control::CacheControl;
pub use self::cookie::Cookies;
pub use self::connection::Connection;
pub use self::content_length::ContentLength;
pub use self::content_type::ContentType;
pub use self::date::Date;
pub use self::etag::Etag;
pub use self::expires::Expires;
pub use self::host::Host;
pub use self::last_modified::LastModified;
pub use self::if_modified_since::IfModifiedSince;
pub use self::location::Location;
pub use self::transfer_encoding::TransferEncoding;
pub use self::upgrade::Upgrade;
pub use self::user_agent::UserAgent;
pub use self::server::Server;
pub use self::set_cookie::SetCookie;
macro_rules! bench_header(
($name:ident, $ty:ty, $value:expr) => {
#[cfg(test)]
mod $name {
use test::Bencher;
use super::*;
use header::{Header, HeaderFormatter};
#[bench]
fn bench_parse(b: &mut Bencher) {
let val = $value;
b.iter(|| {
let _: $ty = Header::parse_header(val[]).unwrap();
});
}
#[bench]
|
b.iter(|| {
format!("{}", fmt);
});
}
}
}
)
macro_rules! deref(
($from:ty -> $to:ty) => {
impl Deref<$to> for $from {
fn deref<'a>(&'a self) -> &'a $to {
&self.0
}
}
impl DerefMut<$to> for $from {
fn deref_mut<'a>(&'a mut self) -> &'a mut $to {
&mut self.0
}
}
}
)
/// Exposes the Accept header.
pub mod accept;
/// Exposes the Allow header.
pub mod allow;
/// Exposes the Authorization header.
pub mod authorization;
/// Exposes the CacheControl header.
pub mod cache_control;
/// Exposes the Cookie header.
pub mod cookie;
/// Exposes the Connection header.
pub mod connection;
/// Exposes the ContentLength header.
pub mod content_length;
/// Exposes the ContentType header.
pub mod content_type;
/// Exposes the Date header.
pub mod date;
/// Exposes the Etag header.
pub mod etag;
/// Exposes the Expires header.
pub mod expires;
/// Exposes the Host header.
pub mod host;
/// Exposes the LastModified header.
pub mod last_modified;
/// Exposes the If-Modified-Since header.
pub mod if_modified_since;
/// Exposes the Location header.
pub mod location;
/// Exposes the Server header.
pub mod server;
/// Exposes the Set-Cookie header.
pub mod set_cookie;
/// Exposes the TransferEncoding header.
pub mod transfer_encoding;
/// Exposes the Upgrade header.
pub mod upgrade;
/// Exposes the UserAgent header.
pub mod user_agent;
pub mod util;
|
fn bench_format(b: &mut Bencher) {
let val: $ty = Header::parse_header($value[]).unwrap();
let fmt = HeaderFormatter(&val);
|
random_line_split
|
texture.rs
|
//! Utilities for loading and using textures
use std::io;
use std::ptr;
use std::fmt;
use std::error;
use std::path::Path;
use std::borrow::Cow;
use std::fs::File;
use png;
use gl;
use gl::types::*;
/// A wraper around a OpenGL texture object which can be modified
#[derive(Debug)]
pub struct Texture {
texture: GLuint,
pub format: TextureFormat,
pub width: u32,
pub height: u32,
}
impl Texture {
|
texture: texture,
format: format,
width: width,
height: height,
}
}
/// Creates a texture from a image file.
pub fn from_file<P>(path: P) -> Result<Texture, TextureError> where P: AsRef<Path> {
let mut texture = Texture::new();
texture.load_file(path)?;
Ok(texture)
}
/// Creates a texturer from the bytes in a image file. The bytes can be sourced with the
/// `include_bytes!` macro. `source` is only used for context in error messages.
pub fn from_bytes(bytes: &[u8], source: &str) -> Result<Texture, TextureError> {
let mut texture = Texture::new();
let data = RawImageData::from_bytes(bytes, source)?;
texture.load_raw_image_data(data)?;
Ok(texture)
}
/// Creates a new texture without any ascociated data. Use can use [`load_file`],
/// [`load_raw_image_data`] and [`load_data`] to set the data to be used used
/// with this texture.
///
/// [`load_file`]: struct.Texture.html#method.load_file
/// [`load_raw_image_data`]: struct.Texture.html#method.load_raw_image_data
/// [`load_data`]: struct.Texture.html#method.load_data
pub fn new() -> Texture {
let mut texture = 0;
unsafe {
gl::GenTextures(1, &mut texture);
gl::BindTexture(gl::TEXTURE_2D, texture);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);
}
Texture {
texture: texture,
format: TextureFormat::RGB_8,
width: 0,
height: 0,
}
}
/// Attempts to load data from the given image file into this texture. Note that
/// it is usually more convenient to create a new texture directly from a file using
/// [`from_file(path)`](struct.Texture.html#method.from_file).
///
/// # Example
/// ```rust,no_run
/// use gondola::texture::Texture;
///
/// let mut texture = Texture::new();
/// texture.load_file("assets/test.png").expect("Failed to load texture");
/// ```
pub fn load_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), TextureError> {
let path = path.as_ref();
let RawImageData { info, buf } = RawImageData::from_file(path)?;
let texture_format = match (info.color_type, info.bit_depth) {
(png::ColorType::RGBA, png::BitDepth::Eight) => TextureFormat::RGBA_8,
(png::ColorType::RGB, png::BitDepth::Eight) => TextureFormat::RGB_8,
other => {
let message = format!(
"Unsuported texture format ({:?}, {:?}) in \"{}\" ({}:{})",
other.0, other.1,
path.to_string_lossy(),
file!(), line!()
);
return Err(TextureError {
source: Some(path.to_string_lossy().into()),
error: io::Error::new(io::ErrorKind::Other, message)
});
}
};
self.load_data(&buf, info.width, info.height, texture_format);
Ok(())
}
/// Attempts to load the given raw image data into this texture. For more info see
/// [`RawImageData`].
///
/// [`RawImageData`]: struct.RawImageData.html
pub fn load_raw_image_data(&mut self, data: RawImageData) -> Result<(), TextureError> {
let texture_format = match (data.info.color_type, data.info.bit_depth) {
(png::ColorType::RGBA, png::BitDepth::Eight) => TextureFormat::RGBA_8,
(png::ColorType::RGB, png::BitDepth::Eight) => TextureFormat::RGB_8,
other => {
let message = format!(
"Unsuported texture format ({:?}, {:?}) ({}:{})",
other.0, other.1, file!(), line!()
);
return Err(TextureError { source: None, error: io::Error::new(io::ErrorKind::Other, message) });
}
};
self.load_data(&data.buf, data.info.width, data.info.height, texture_format);
Ok(())
}
/// Directly loads some color data into a texture. This function does not check to ensure that
/// the data is in the correct format, so you have to manually ensure that it is valid. This
/// function is intended for creating small debug textures.
pub fn load_data(&mut self, data: &[u8], width: u32, height: u32, format: TextureFormat) {
unsafe {
gl::BindTexture(gl::TEXTURE_2D, self.texture);
gl::TexImage2D(gl::TEXTURE_2D, 0, // Mipmap level
format as GLint, // Internal format
width as GLsizei, height as GLsizei, 0, // Size and border
format.unsized_format(), // Data format
gl::UNSIGNED_BYTE, data.as_ptr() as *const GLvoid);
}
self.width = width;
self.height = height;
self.format = format;
}
/// Sets the data in a sub-region of this texture. The data is expected to be in the
/// format this texture was initialized to. This texture needs to be initialized
/// before this method can be used.
/// Note that there is a debug assertion in place to ensure that the given region
/// is within the bounds of this texture. If debug assertions are not enabled this
/// function will return without taking any action.
pub fn load_data_to_region(&mut self, data: &[u8], x: u32, y: u32, width: u32, height: u32) {
if x + width > self.width && y + height > self.height {
debug_assert!(false, "Invalid region passed ({}:{}) Region: (x: {}, y: {}, width: {}, height: {})",
file!(), line!(),
x, y, width, height);
return;
}
unsafe {
// OpenGL is allowed to expect rows in pixel data to be aligned
// at powers of two. This ensures that any data will be accepted.
gl::PixelStorei(gl::PACK_ALIGNMENT, 1);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::BindTexture(gl::TEXTURE_2D, self.texture);
gl::TexSubImage2D(gl::TEXTURE_2D, 0,
x as GLint, y as GLint,
width as GLsizei, height as GLsizei,
self.format.unsized_format(), // It is unclear whether opengl allows a different format here
gl::UNSIGNED_BYTE, data.as_ptr() as *const GLvoid);
}
}
/// Converts this texture to a empty texture of the given size. The contents
/// of the texture after this operation are undefined.
pub fn initialize(&mut self, width: u32, height: u32, format: TextureFormat) {
unsafe {
gl::BindTexture(gl::TEXTURE_2D, self.texture);
gl::TexImage2D(gl::TEXTURE_2D, 0, // Mipmap level
format as GLint, // Internal format
width as GLsizei, height as GLsizei, 0, // Size and border
format.unsized_format(), // Data format
gl::UNSIGNED_BYTE, ptr::null());
}
self.width = width;
self.height = height;
self.format = format;
}
/// Binds this texture to the given texture unit.
pub fn bind(&self, unit: u32) {
unsafe {
gl::ActiveTexture(gl::TEXTURE0 + unit);
gl::BindTexture(gl::TEXTURE_2D, self.texture);
}
}
/// Unbinds the texture at the given texture unit.
pub fn unbind(unit: u32) {
unsafe {
gl::ActiveTexture(gl::TEXTURE0 + unit);
gl::BindTexture(gl::TEXTURE_2D, 0);
}
}
/// Sets the filter that is applied when this texture is rendered at a size larger
/// or smaller sizes than the native size of the texture. A separate filter can be
/// set for magnification and minification.
pub fn set_filter(&mut self, mag: TextureFilter, min: TextureFilter) {
unsafe {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, mag as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, min as GLint);
}
}
/// Sets the texture filter, allowing for a separate filter to be used when mipmapping
pub fn set_mipmap_filter(&mut self, mag: TextureFilter, mipmap_mag: TextureFilter,
min: TextureFilter, mipmap_min: TextureFilter) {
unsafe {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, TextureFilter::mipmap_filter(mag, mipmap_mag) as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, TextureFilter::mipmap_filter(min, mipmap_min) as GLint);
}
}
/// Sets the swizzle mask of this texture. The swizzle mask specifies how data stored
/// in this texture is seen by other parts of OpenGL. This includes texture samplers
/// in shaders. This is usefull when using textures with only one or two components
/// per pixel.
///
/// For example, given a texture with only a red component (That is, its
/// format is `TextureFormat::R_8` or similar), a texture sampler in a shader will
/// normaly get a value of type `(r, 0.0, 0.0, 1.0)`. By setting the swizzle mask
/// to `(SwizzleComp::One, SwizzleComp::One, SwizzleComp::One, SwizzleComp::Red)`
/// shaders will now see `(1.0, 1.0, 1.0, r)`.
pub fn set_swizzle_mask(&mut self, masks: (SwizzleComp, SwizzleComp, SwizzleComp, SwizzleComp)) {
unsafe {
let masks = [masks.0 as GLint, masks.1 as GLint, masks.2 as GLint, masks.3 as GLint];
gl::TexParameteriv(gl::TEXTURE_2D, gl::TEXTURE_SWIZZLE_RGBA, &masks as *const _);
}
}
}
impl Drop for Texture {
fn drop(&mut self) {
unsafe {
gl::DeleteTextures(1, &self.texture);
}
}
}
/// Raw image data loaded from a png file. This data can then be loaded into a texture
/// using [`Texture::load_raw_image_data`]. When loading very large textures it can be
/// beneficial to load the raw image data from the texture on a separate thread, and then
/// pass it to a texture in the main thread for performance reasons.
///
/// Note that textures must allways be created in the same thread as they are used in, because
/// of OpenGL limitations. You can call [`RawImageData::from_file`] from anywhere, but only
/// ever create textures in the rendering tread (usually the main thread).
///
/// [`Texture::load_raw_image_data`]: struct.Texture.html#method.load_raw_image_data
/// [`RawImageData::from_file`]: struct.RawImageData.html#method.from_file
pub struct RawImageData {
info: png::OutputInfo,
buf: Vec<u8>,
}
impl RawImageData {
/// Does not invoke any OpenGL functions, and can thus be called from any thread.
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<RawImageData, TextureError> {
let path = path.as_ref();
// Open file
let file = match File::open(path) {
Ok(file) => file,
Err(err) => return Err(TextureError {
source: Some(path.to_string_lossy().into()),
error: err
}),
};
let decoder = png::Decoder::new(file);
RawImageData::from_decoder(decoder, path.to_string_lossy().into())
}
/// Can be used in conjunction with the `include_bytes!(..)` in std.
pub fn from_bytes(bytes: &[u8], source: &str) -> Result<RawImageData, TextureError> {
RawImageData::from_decoder(png::Decoder::new(bytes), source.into())
}
fn from_decoder<R: io::Read>(
decoder: png::Decoder<R>,
source: Cow<str>,
) -> Result<RawImageData, TextureError>
{
let (info, mut reader) = match decoder.read_info() {
Ok(result) => result,
Err(err) => return Err(TextureError {
source: Some(source.into()),
error: err.into()
}),
};
// Read data into buffer (This is what makes texture loading slow)
let mut buf = vec![0; info.buffer_size()];
match reader.next_frame(&mut buf) {
Ok(()) => {},
Err(err) => return Err(TextureError {
source: Some(source.into()),
error: err.into()
}),
};
Ok(RawImageData {
info: info,
buf: buf,
})
}
}
/// Represents an OpenGL texture filter.
#[repr(u32)] // GLenum is u32
#[derive(Debug, Copy, Clone)]
pub enum TextureFilter {
Nearest = gl::NEAREST,
Linear = gl::LINEAR
}
impl TextureFilter {
/// Retrieves a OpenGL mipmap filter for mipmaping. The returned `GLenum` can
/// be used in the same scenarios as ´TextureFilter::* as GLenum´
fn mipmap_filter(normal: TextureFilter, mipmap: TextureFilter) -> GLenum {
match normal {
TextureFilter::Nearest => match mipmap {
TextureFilter::Nearest => gl::NEAREST_MIPMAP_NEAREST,
TextureFilter::Linear => gl::NEAREST_MIPMAP_LINEAR,
},
TextureFilter::Linear => match mipmap {
TextureFilter::Nearest => gl::LINEAR_MIPMAP_NEAREST,
TextureFilter::Linear => gl::LINEAR_MIPMAP_LINEAR,
},
}
}
}
/// Represents a OpenGL texture format.
#[repr(u32)] // GLenum is u32
#[allow(non_camel_case_types, dead_code)]
#[derive(Debug, Copy, Clone)]
pub enum TextureFormat {
RGBA_F32 = gl::RGBA32F,
RGBA_F16 = gl::RGBA16F,
RGB_F32 = gl::RGB32F,
RGB_F16 = gl::RGB16F,
R_F32 = gl::R32F,
R_F16 = gl::R16F,
RGBA_8 = gl::RGBA8,
RGB_8 = gl::RGB8,
R_8 = gl::R8,
}
impl TextureFormat {
/// Retrieves the unsized version of the given format
pub fn unsized_format(&self) -> GLenum {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGBA_F16 | TextureFormat::RGBA_8 => gl::RGBA,
TextureFormat::RGB_F32 | TextureFormat::RGB_F16 | TextureFormat::RGB_8 => gl::RGB,
TextureFormat::R_F32 | TextureFormat::R_F16 | TextureFormat::R_8 => gl::RED,
}
}
/// The OpenGL primitive associated with this color format.
pub fn gl_primitive_enum(&self) -> GLenum {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGB_F32 | TextureFormat::R_F32 => gl::FLOAT,
TextureFormat::RGBA_F16 | TextureFormat::RGB_F16 | TextureFormat::R_F16 => gl::FLOAT,
TextureFormat::RGBA_8 | TextureFormat::RGB_8 | TextureFormat::R_8 => gl::UNSIGNED_BYTE,
}
}
/// The name of the OpenGL primitive associated with this color format.
pub fn gl_primitive_enum_name(&self) -> &'static str {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGB_F32 | TextureFormat::R_F32 => "GLfloat",
TextureFormat::RGBA_F16 | TextureFormat::RGB_F16 | TextureFormat::R_F16 => "GLfloat",
TextureFormat::RGBA_8 | TextureFormat::RGB_8 | TextureFormat::R_8 => "GLbyte",
}
}
/// The number of components this color format has. For example, `RGB_8` has 3 components.
pub fn components(&self) -> usize {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGBA_F16 | TextureFormat::RGBA_8 => 4,
TextureFormat::RGB_F32 | TextureFormat::RGB_F16 | TextureFormat::RGB_8 => 3,
TextureFormat::R_F32 | TextureFormat::R_F16 | TextureFormat::R_8 => 1,
}
}
}
/// Components that a texture can be mapped to through swizzling. See
/// [`set_swizzle_mask`](struct.Texture.html#method.set_swizzle_mask)
/// for more info.
#[repr(u32)] // GLenum is u32
#[derive(Debug, Copy, Clone)]
pub enum SwizzleComp {
Red = gl::RED,
Green = gl::GREEN,
Blue = gl::BLUE,
Alpha = gl::ALPHA,
One = gl::ONE,
Zero = gl::ZERO,
}
/// A error which can occur during texture loading and creation.
#[derive(Debug)]
pub struct TextureError {
source: Option<String>,
error: io::Error,
}
impl error::Error for TextureError {
fn description(&self) -> &str {
self.error.description()
}
fn cause(&self) -> Option<&error::Error> {
self.error.cause()
}
}
impl fmt::Display for TextureError {
fn fmt(&self, mut f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref source) = self.source {
write!(f, "For texture \"{}\": ", source)?;
}
self.error.fmt(&mut f)?;
Ok(())
}
}
impl From<TextureError> for io::Error {
fn from(err: TextureError) -> io::Error {
io::Error::new(io::ErrorKind::Other, err)
}
}
|
/// Creates a texture from a raw OpenGL handle and some additional data. Intended for internal
/// use only, use with care!
pub fn wrap_gl_texture(texture: GLuint, format: TextureFormat, width: u32, height: u32) -> Texture {
Texture {
|
random_line_split
|
texture.rs
|
//! Utilities for loading and using textures
use std::io;
use std::ptr;
use std::fmt;
use std::error;
use std::path::Path;
use std::borrow::Cow;
use std::fs::File;
use png;
use gl;
use gl::types::*;
/// A wraper around a OpenGL texture object which can be modified
#[derive(Debug)]
pub struct Texture {
texture: GLuint,
pub format: TextureFormat,
pub width: u32,
pub height: u32,
}
impl Texture {
/// Creates a texture from a raw OpenGL handle and some additional data. Intended for internal
/// use only, use with care!
pub fn wrap_gl_texture(texture: GLuint, format: TextureFormat, width: u32, height: u32) -> Texture {
Texture {
texture: texture,
format: format,
width: width,
height: height,
}
}
/// Creates a texture from a image file.
pub fn from_file<P>(path: P) -> Result<Texture, TextureError> where P: AsRef<Path> {
let mut texture = Texture::new();
texture.load_file(path)?;
Ok(texture)
}
/// Creates a texturer from the bytes in a image file. The bytes can be sourced with the
/// `include_bytes!` macro. `source` is only used for context in error messages.
pub fn from_bytes(bytes: &[u8], source: &str) -> Result<Texture, TextureError> {
let mut texture = Texture::new();
let data = RawImageData::from_bytes(bytes, source)?;
texture.load_raw_image_data(data)?;
Ok(texture)
}
/// Creates a new texture without any ascociated data. Use can use [`load_file`],
/// [`load_raw_image_data`] and [`load_data`] to set the data to be used used
/// with this texture.
///
/// [`load_file`]: struct.Texture.html#method.load_file
/// [`load_raw_image_data`]: struct.Texture.html#method.load_raw_image_data
/// [`load_data`]: struct.Texture.html#method.load_data
pub fn new() -> Texture {
let mut texture = 0;
unsafe {
gl::GenTextures(1, &mut texture);
gl::BindTexture(gl::TEXTURE_2D, texture);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);
}
Texture {
texture: texture,
format: TextureFormat::RGB_8,
width: 0,
height: 0,
}
}
/// Attempts to load data from the given image file into this texture. Note that
/// it is usually more convenient to create a new texture directly from a file using
/// [`from_file(path)`](struct.Texture.html#method.from_file).
///
/// # Example
/// ```rust,no_run
/// use gondola::texture::Texture;
///
/// let mut texture = Texture::new();
/// texture.load_file("assets/test.png").expect("Failed to load texture");
/// ```
pub fn load_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), TextureError> {
let path = path.as_ref();
let RawImageData { info, buf } = RawImageData::from_file(path)?;
let texture_format = match (info.color_type, info.bit_depth) {
(png::ColorType::RGBA, png::BitDepth::Eight) => TextureFormat::RGBA_8,
(png::ColorType::RGB, png::BitDepth::Eight) => TextureFormat::RGB_8,
other => {
let message = format!(
"Unsuported texture format ({:?}, {:?}) in \"{}\" ({}:{})",
other.0, other.1,
path.to_string_lossy(),
file!(), line!()
);
return Err(TextureError {
source: Some(path.to_string_lossy().into()),
error: io::Error::new(io::ErrorKind::Other, message)
});
}
};
self.load_data(&buf, info.width, info.height, texture_format);
Ok(())
}
/// Attempts to load the given raw image data into this texture. For more info see
/// [`RawImageData`].
///
/// [`RawImageData`]: struct.RawImageData.html
pub fn load_raw_image_data(&mut self, data: RawImageData) -> Result<(), TextureError> {
let texture_format = match (data.info.color_type, data.info.bit_depth) {
(png::ColorType::RGBA, png::BitDepth::Eight) => TextureFormat::RGBA_8,
(png::ColorType::RGB, png::BitDepth::Eight) => TextureFormat::RGB_8,
other => {
let message = format!(
"Unsuported texture format ({:?}, {:?}) ({}:{})",
other.0, other.1, file!(), line!()
);
return Err(TextureError { source: None, error: io::Error::new(io::ErrorKind::Other, message) });
}
};
self.load_data(&data.buf, data.info.width, data.info.height, texture_format);
Ok(())
}
/// Directly loads some color data into a texture. This function does not check to ensure that
/// the data is in the correct format, so you have to manually ensure that it is valid. This
/// function is intended for creating small debug textures.
pub fn load_data(&mut self, data: &[u8], width: u32, height: u32, format: TextureFormat) {
unsafe {
gl::BindTexture(gl::TEXTURE_2D, self.texture);
gl::TexImage2D(gl::TEXTURE_2D, 0, // Mipmap level
format as GLint, // Internal format
width as GLsizei, height as GLsizei, 0, // Size and border
format.unsized_format(), // Data format
gl::UNSIGNED_BYTE, data.as_ptr() as *const GLvoid);
}
self.width = width;
self.height = height;
self.format = format;
}
/// Sets the data in a sub-region of this texture. The data is expected to be in the
/// format this texture was initialized to. This texture needs to be initialized
/// before this method can be used.
/// Note that there is a debug assertion in place to ensure that the given region
/// is within the bounds of this texture. If debug assertions are not enabled this
/// function will return without taking any action.
pub fn load_data_to_region(&mut self, data: &[u8], x: u32, y: u32, width: u32, height: u32) {
if x + width > self.width && y + height > self.height {
debug_assert!(false, "Invalid region passed ({}:{}) Region: (x: {}, y: {}, width: {}, height: {})",
file!(), line!(),
x, y, width, height);
return;
}
unsafe {
// OpenGL is allowed to expect rows in pixel data to be aligned
// at powers of two. This ensures that any data will be accepted.
gl::PixelStorei(gl::PACK_ALIGNMENT, 1);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::BindTexture(gl::TEXTURE_2D, self.texture);
gl::TexSubImage2D(gl::TEXTURE_2D, 0,
x as GLint, y as GLint,
width as GLsizei, height as GLsizei,
self.format.unsized_format(), // It is unclear whether opengl allows a different format here
gl::UNSIGNED_BYTE, data.as_ptr() as *const GLvoid);
}
}
/// Converts this texture to a empty texture of the given size. The contents
/// of the texture after this operation are undefined.
pub fn initialize(&mut self, width: u32, height: u32, format: TextureFormat) {
unsafe {
gl::BindTexture(gl::TEXTURE_2D, self.texture);
gl::TexImage2D(gl::TEXTURE_2D, 0, // Mipmap level
format as GLint, // Internal format
width as GLsizei, height as GLsizei, 0, // Size and border
format.unsized_format(), // Data format
gl::UNSIGNED_BYTE, ptr::null());
}
self.width = width;
self.height = height;
self.format = format;
}
/// Binds this texture to the given texture unit.
pub fn bind(&self, unit: u32) {
unsafe {
gl::ActiveTexture(gl::TEXTURE0 + unit);
gl::BindTexture(gl::TEXTURE_2D, self.texture);
}
}
/// Unbinds the texture at the given texture unit.
pub fn unbind(unit: u32) {
unsafe {
gl::ActiveTexture(gl::TEXTURE0 + unit);
gl::BindTexture(gl::TEXTURE_2D, 0);
}
}
/// Sets the filter that is applied when this texture is rendered at a size larger
/// or smaller sizes than the native size of the texture. A separate filter can be
/// set for magnification and minification.
pub fn set_filter(&mut self, mag: TextureFilter, min: TextureFilter) {
unsafe {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, mag as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, min as GLint);
}
}
/// Sets the texture filter, allowing for a separate filter to be used when mipmapping
pub fn set_mipmap_filter(&mut self, mag: TextureFilter, mipmap_mag: TextureFilter,
min: TextureFilter, mipmap_min: TextureFilter) {
unsafe {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, TextureFilter::mipmap_filter(mag, mipmap_mag) as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, TextureFilter::mipmap_filter(min, mipmap_min) as GLint);
}
}
/// Sets the swizzle mask of this texture. The swizzle mask specifies how data stored
/// in this texture is seen by other parts of OpenGL. This includes texture samplers
/// in shaders. This is usefull when using textures with only one or two components
/// per pixel.
///
/// For example, given a texture with only a red component (That is, its
/// format is `TextureFormat::R_8` or similar), a texture sampler in a shader will
/// normaly get a value of type `(r, 0.0, 0.0, 1.0)`. By setting the swizzle mask
/// to `(SwizzleComp::One, SwizzleComp::One, SwizzleComp::One, SwizzleComp::Red)`
/// shaders will now see `(1.0, 1.0, 1.0, r)`.
pub fn set_swizzle_mask(&mut self, masks: (SwizzleComp, SwizzleComp, SwizzleComp, SwizzleComp)) {
unsafe {
let masks = [masks.0 as GLint, masks.1 as GLint, masks.2 as GLint, masks.3 as GLint];
gl::TexParameteriv(gl::TEXTURE_2D, gl::TEXTURE_SWIZZLE_RGBA, &masks as *const _);
}
}
}
impl Drop for Texture {
fn drop(&mut self) {
unsafe {
gl::DeleteTextures(1, &self.texture);
}
}
}
/// Raw image data loaded from a png file. This data can then be loaded into a texture
/// using [`Texture::load_raw_image_data`]. When loading very large textures it can be
/// beneficial to load the raw image data from the texture on a separate thread, and then
/// pass it to a texture in the main thread for performance reasons.
///
/// Note that textures must allways be created in the same thread as they are used in, because
/// of OpenGL limitations. You can call [`RawImageData::from_file`] from anywhere, but only
/// ever create textures in the rendering tread (usually the main thread).
///
/// [`Texture::load_raw_image_data`]: struct.Texture.html#method.load_raw_image_data
/// [`RawImageData::from_file`]: struct.RawImageData.html#method.from_file
pub struct RawImageData {
info: png::OutputInfo,
buf: Vec<u8>,
}
impl RawImageData {
/// Does not invoke any OpenGL functions, and can thus be called from any thread.
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<RawImageData, TextureError> {
let path = path.as_ref();
// Open file
let file = match File::open(path) {
Ok(file) => file,
Err(err) => return Err(TextureError {
source: Some(path.to_string_lossy().into()),
error: err
}),
};
let decoder = png::Decoder::new(file);
RawImageData::from_decoder(decoder, path.to_string_lossy().into())
}
/// Can be used in conjunction with the `include_bytes!(..)` in std.
pub fn
|
(bytes: &[u8], source: &str) -> Result<RawImageData, TextureError> {
RawImageData::from_decoder(png::Decoder::new(bytes), source.into())
}
fn from_decoder<R: io::Read>(
decoder: png::Decoder<R>,
source: Cow<str>,
) -> Result<RawImageData, TextureError>
{
let (info, mut reader) = match decoder.read_info() {
Ok(result) => result,
Err(err) => return Err(TextureError {
source: Some(source.into()),
error: err.into()
}),
};
// Read data into buffer (This is what makes texture loading slow)
let mut buf = vec![0; info.buffer_size()];
match reader.next_frame(&mut buf) {
Ok(()) => {},
Err(err) => return Err(TextureError {
source: Some(source.into()),
error: err.into()
}),
};
Ok(RawImageData {
info: info,
buf: buf,
})
}
}
/// Represents an OpenGL texture filter.
#[repr(u32)] // GLenum is u32
#[derive(Debug, Copy, Clone)]
pub enum TextureFilter {
Nearest = gl::NEAREST,
Linear = gl::LINEAR
}
impl TextureFilter {
/// Retrieves a OpenGL mipmap filter for mipmaping. The returned `GLenum` can
/// be used in the same scenarios as ´TextureFilter::* as GLenum´
fn mipmap_filter(normal: TextureFilter, mipmap: TextureFilter) -> GLenum {
match normal {
TextureFilter::Nearest => match mipmap {
TextureFilter::Nearest => gl::NEAREST_MIPMAP_NEAREST,
TextureFilter::Linear => gl::NEAREST_MIPMAP_LINEAR,
},
TextureFilter::Linear => match mipmap {
TextureFilter::Nearest => gl::LINEAR_MIPMAP_NEAREST,
TextureFilter::Linear => gl::LINEAR_MIPMAP_LINEAR,
},
}
}
}
/// Represents a OpenGL texture format.
#[repr(u32)] // GLenum is u32
#[allow(non_camel_case_types, dead_code)]
#[derive(Debug, Copy, Clone)]
pub enum TextureFormat {
RGBA_F32 = gl::RGBA32F,
RGBA_F16 = gl::RGBA16F,
RGB_F32 = gl::RGB32F,
RGB_F16 = gl::RGB16F,
R_F32 = gl::R32F,
R_F16 = gl::R16F,
RGBA_8 = gl::RGBA8,
RGB_8 = gl::RGB8,
R_8 = gl::R8,
}
impl TextureFormat {
/// Retrieves the unsized version of the given format
pub fn unsized_format(&self) -> GLenum {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGBA_F16 | TextureFormat::RGBA_8 => gl::RGBA,
TextureFormat::RGB_F32 | TextureFormat::RGB_F16 | TextureFormat::RGB_8 => gl::RGB,
TextureFormat::R_F32 | TextureFormat::R_F16 | TextureFormat::R_8 => gl::RED,
}
}
/// The OpenGL primitive associated with this color format.
pub fn gl_primitive_enum(&self) -> GLenum {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGB_F32 | TextureFormat::R_F32 => gl::FLOAT,
TextureFormat::RGBA_F16 | TextureFormat::RGB_F16 | TextureFormat::R_F16 => gl::FLOAT,
TextureFormat::RGBA_8 | TextureFormat::RGB_8 | TextureFormat::R_8 => gl::UNSIGNED_BYTE,
}
}
/// The name of the OpenGL primitive associated with this color format.
pub fn gl_primitive_enum_name(&self) -> &'static str {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGB_F32 | TextureFormat::R_F32 => "GLfloat",
TextureFormat::RGBA_F16 | TextureFormat::RGB_F16 | TextureFormat::R_F16 => "GLfloat",
TextureFormat::RGBA_8 | TextureFormat::RGB_8 | TextureFormat::R_8 => "GLbyte",
}
}
/// The number of components this color format has. For example, `RGB_8` has 3 components.
pub fn components(&self) -> usize {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGBA_F16 | TextureFormat::RGBA_8 => 4,
TextureFormat::RGB_F32 | TextureFormat::RGB_F16 | TextureFormat::RGB_8 => 3,
TextureFormat::R_F32 | TextureFormat::R_F16 | TextureFormat::R_8 => 1,
}
}
}
/// Components that a texture can be mapped to through swizzling. See
/// [`set_swizzle_mask`](struct.Texture.html#method.set_swizzle_mask)
/// for more info.
#[repr(u32)] // GLenum is u32
#[derive(Debug, Copy, Clone)]
pub enum SwizzleComp {
Red = gl::RED,
Green = gl::GREEN,
Blue = gl::BLUE,
Alpha = gl::ALPHA,
One = gl::ONE,
Zero = gl::ZERO,
}
/// A error which can occur during texture loading and creation.
#[derive(Debug)]
pub struct TextureError {
source: Option<String>,
error: io::Error,
}
impl error::Error for TextureError {
fn description(&self) -> &str {
self.error.description()
}
fn cause(&self) -> Option<&error::Error> {
self.error.cause()
}
}
impl fmt::Display for TextureError {
fn fmt(&self, mut f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref source) = self.source {
write!(f, "For texture \"{}\": ", source)?;
}
self.error.fmt(&mut f)?;
Ok(())
}
}
impl From<TextureError> for io::Error {
fn from(err: TextureError) -> io::Error {
io::Error::new(io::ErrorKind::Other, err)
}
}
|
from_bytes
|
identifier_name
|
texture.rs
|
//! Utilities for loading and using textures
use std::io;
use std::ptr;
use std::fmt;
use std::error;
use std::path::Path;
use std::borrow::Cow;
use std::fs::File;
use png;
use gl;
use gl::types::*;
/// A wraper around a OpenGL texture object which can be modified
#[derive(Debug)]
pub struct Texture {
texture: GLuint,
pub format: TextureFormat,
pub width: u32,
pub height: u32,
}
impl Texture {
/// Creates a texture from a raw OpenGL handle and some additional data. Intended for internal
/// use only, use with care!
pub fn wrap_gl_texture(texture: GLuint, format: TextureFormat, width: u32, height: u32) -> Texture {
Texture {
texture: texture,
format: format,
width: width,
height: height,
}
}
/// Creates a texture from a image file.
pub fn from_file<P>(path: P) -> Result<Texture, TextureError> where P: AsRef<Path> {
let mut texture = Texture::new();
texture.load_file(path)?;
Ok(texture)
}
/// Creates a texturer from the bytes in a image file. The bytes can be sourced with the
/// `include_bytes!` macro. `source` is only used for context in error messages.
pub fn from_bytes(bytes: &[u8], source: &str) -> Result<Texture, TextureError>
|
/// Creates a new texture without any ascociated data. Use can use [`load_file`],
/// [`load_raw_image_data`] and [`load_data`] to set the data to be used used
/// with this texture.
///
/// [`load_file`]: struct.Texture.html#method.load_file
/// [`load_raw_image_data`]: struct.Texture.html#method.load_raw_image_data
/// [`load_data`]: struct.Texture.html#method.load_data
pub fn new() -> Texture {
let mut texture = 0;
unsafe {
gl::GenTextures(1, &mut texture);
gl::BindTexture(gl::TEXTURE_2D, texture);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);
}
Texture {
texture: texture,
format: TextureFormat::RGB_8,
width: 0,
height: 0,
}
}
/// Attempts to load data from the given image file into this texture. Note that
/// it is usually more convenient to create a new texture directly from a file using
/// [`from_file(path)`](struct.Texture.html#method.from_file).
///
/// # Example
/// ```rust,no_run
/// use gondola::texture::Texture;
///
/// let mut texture = Texture::new();
/// texture.load_file("assets/test.png").expect("Failed to load texture");
/// ```
pub fn load_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), TextureError> {
let path = path.as_ref();
let RawImageData { info, buf } = RawImageData::from_file(path)?;
let texture_format = match (info.color_type, info.bit_depth) {
(png::ColorType::RGBA, png::BitDepth::Eight) => TextureFormat::RGBA_8,
(png::ColorType::RGB, png::BitDepth::Eight) => TextureFormat::RGB_8,
other => {
let message = format!(
"Unsuported texture format ({:?}, {:?}) in \"{}\" ({}:{})",
other.0, other.1,
path.to_string_lossy(),
file!(), line!()
);
return Err(TextureError {
source: Some(path.to_string_lossy().into()),
error: io::Error::new(io::ErrorKind::Other, message)
});
}
};
self.load_data(&buf, info.width, info.height, texture_format);
Ok(())
}
/// Attempts to load the given raw image data into this texture. For more info see
/// [`RawImageData`].
///
/// [`RawImageData`]: struct.RawImageData.html
pub fn load_raw_image_data(&mut self, data: RawImageData) -> Result<(), TextureError> {
let texture_format = match (data.info.color_type, data.info.bit_depth) {
(png::ColorType::RGBA, png::BitDepth::Eight) => TextureFormat::RGBA_8,
(png::ColorType::RGB, png::BitDepth::Eight) => TextureFormat::RGB_8,
other => {
let message = format!(
"Unsuported texture format ({:?}, {:?}) ({}:{})",
other.0, other.1, file!(), line!()
);
return Err(TextureError { source: None, error: io::Error::new(io::ErrorKind::Other, message) });
}
};
self.load_data(&data.buf, data.info.width, data.info.height, texture_format);
Ok(())
}
/// Directly loads some color data into a texture. This function does not check to ensure that
/// the data is in the correct format, so you have to manually ensure that it is valid. This
/// function is intended for creating small debug textures.
pub fn load_data(&mut self, data: &[u8], width: u32, height: u32, format: TextureFormat) {
unsafe {
gl::BindTexture(gl::TEXTURE_2D, self.texture);
gl::TexImage2D(gl::TEXTURE_2D, 0, // Mipmap level
format as GLint, // Internal format
width as GLsizei, height as GLsizei, 0, // Size and border
format.unsized_format(), // Data format
gl::UNSIGNED_BYTE, data.as_ptr() as *const GLvoid);
}
self.width = width;
self.height = height;
self.format = format;
}
/// Sets the data in a sub-region of this texture. The data is expected to be in the
/// format this texture was initialized to. This texture needs to be initialized
/// before this method can be used.
/// Note that there is a debug assertion in place to ensure that the given region
/// is within the bounds of this texture. If debug assertions are not enabled this
/// function will return without taking any action.
pub fn load_data_to_region(&mut self, data: &[u8], x: u32, y: u32, width: u32, height: u32) {
if x + width > self.width && y + height > self.height {
debug_assert!(false, "Invalid region passed ({}:{}) Region: (x: {}, y: {}, width: {}, height: {})",
file!(), line!(),
x, y, width, height);
return;
}
unsafe {
// OpenGL is allowed to expect rows in pixel data to be aligned
// at powers of two. This ensures that any data will be accepted.
gl::PixelStorei(gl::PACK_ALIGNMENT, 1);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::BindTexture(gl::TEXTURE_2D, self.texture);
gl::TexSubImage2D(gl::TEXTURE_2D, 0,
x as GLint, y as GLint,
width as GLsizei, height as GLsizei,
self.format.unsized_format(), // It is unclear whether opengl allows a different format here
gl::UNSIGNED_BYTE, data.as_ptr() as *const GLvoid);
}
}
/// Converts this texture to a empty texture of the given size. The contents
/// of the texture after this operation are undefined.
pub fn initialize(&mut self, width: u32, height: u32, format: TextureFormat) {
unsafe {
gl::BindTexture(gl::TEXTURE_2D, self.texture);
gl::TexImage2D(gl::TEXTURE_2D, 0, // Mipmap level
format as GLint, // Internal format
width as GLsizei, height as GLsizei, 0, // Size and border
format.unsized_format(), // Data format
gl::UNSIGNED_BYTE, ptr::null());
}
self.width = width;
self.height = height;
self.format = format;
}
/// Binds this texture to the given texture unit.
pub fn bind(&self, unit: u32) {
unsafe {
gl::ActiveTexture(gl::TEXTURE0 + unit);
gl::BindTexture(gl::TEXTURE_2D, self.texture);
}
}
/// Unbinds the texture at the given texture unit.
pub fn unbind(unit: u32) {
unsafe {
gl::ActiveTexture(gl::TEXTURE0 + unit);
gl::BindTexture(gl::TEXTURE_2D, 0);
}
}
/// Sets the filter that is applied when this texture is rendered at a size larger
/// or smaller sizes than the native size of the texture. A separate filter can be
/// set for magnification and minification.
pub fn set_filter(&mut self, mag: TextureFilter, min: TextureFilter) {
unsafe {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, mag as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, min as GLint);
}
}
/// Sets the texture filter, allowing for a separate filter to be used when mipmapping
pub fn set_mipmap_filter(&mut self, mag: TextureFilter, mipmap_mag: TextureFilter,
min: TextureFilter, mipmap_min: TextureFilter) {
unsafe {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, TextureFilter::mipmap_filter(mag, mipmap_mag) as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, TextureFilter::mipmap_filter(min, mipmap_min) as GLint);
}
}
/// Sets the swizzle mask of this texture. The swizzle mask specifies how data stored
/// in this texture is seen by other parts of OpenGL. This includes texture samplers
/// in shaders. This is usefull when using textures with only one or two components
/// per pixel.
///
/// For example, given a texture with only a red component (That is, its
/// format is `TextureFormat::R_8` or similar), a texture sampler in a shader will
/// normaly get a value of type `(r, 0.0, 0.0, 1.0)`. By setting the swizzle mask
/// to `(SwizzleComp::One, SwizzleComp::One, SwizzleComp::One, SwizzleComp::Red)`
/// shaders will now see `(1.0, 1.0, 1.0, r)`.
pub fn set_swizzle_mask(&mut self, masks: (SwizzleComp, SwizzleComp, SwizzleComp, SwizzleComp)) {
unsafe {
let masks = [masks.0 as GLint, masks.1 as GLint, masks.2 as GLint, masks.3 as GLint];
gl::TexParameteriv(gl::TEXTURE_2D, gl::TEXTURE_SWIZZLE_RGBA, &masks as *const _);
}
}
}
impl Drop for Texture {
fn drop(&mut self) {
unsafe {
gl::DeleteTextures(1, &self.texture);
}
}
}
/// Raw image data loaded from a png file. This data can then be loaded into a texture
/// using [`Texture::load_raw_image_data`]. When loading very large textures it can be
/// beneficial to load the raw image data from the texture on a separate thread, and then
/// pass it to a texture in the main thread for performance reasons.
///
/// Note that textures must allways be created in the same thread as they are used in, because
/// of OpenGL limitations. You can call [`RawImageData::from_file`] from anywhere, but only
/// ever create textures in the rendering tread (usually the main thread).
///
/// [`Texture::load_raw_image_data`]: struct.Texture.html#method.load_raw_image_data
/// [`RawImageData::from_file`]: struct.RawImageData.html#method.from_file
pub struct RawImageData {
info: png::OutputInfo,
buf: Vec<u8>,
}
impl RawImageData {
/// Does not invoke any OpenGL functions, and can thus be called from any thread.
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<RawImageData, TextureError> {
let path = path.as_ref();
// Open file
let file = match File::open(path) {
Ok(file) => file,
Err(err) => return Err(TextureError {
source: Some(path.to_string_lossy().into()),
error: err
}),
};
let decoder = png::Decoder::new(file);
RawImageData::from_decoder(decoder, path.to_string_lossy().into())
}
/// Can be used in conjunction with the `include_bytes!(..)` in std.
pub fn from_bytes(bytes: &[u8], source: &str) -> Result<RawImageData, TextureError> {
RawImageData::from_decoder(png::Decoder::new(bytes), source.into())
}
fn from_decoder<R: io::Read>(
decoder: png::Decoder<R>,
source: Cow<str>,
) -> Result<RawImageData, TextureError>
{
let (info, mut reader) = match decoder.read_info() {
Ok(result) => result,
Err(err) => return Err(TextureError {
source: Some(source.into()),
error: err.into()
}),
};
// Read data into buffer (This is what makes texture loading slow)
let mut buf = vec![0; info.buffer_size()];
match reader.next_frame(&mut buf) {
Ok(()) => {},
Err(err) => return Err(TextureError {
source: Some(source.into()),
error: err.into()
}),
};
Ok(RawImageData {
info: info,
buf: buf,
})
}
}
/// Represents an OpenGL texture filter.
#[repr(u32)] // GLenum is u32
#[derive(Debug, Copy, Clone)]
pub enum TextureFilter {
Nearest = gl::NEAREST,
Linear = gl::LINEAR
}
impl TextureFilter {
/// Retrieves a OpenGL mipmap filter for mipmaping. The returned `GLenum` can
/// be used in the same scenarios as ´TextureFilter::* as GLenum´
fn mipmap_filter(normal: TextureFilter, mipmap: TextureFilter) -> GLenum {
match normal {
TextureFilter::Nearest => match mipmap {
TextureFilter::Nearest => gl::NEAREST_MIPMAP_NEAREST,
TextureFilter::Linear => gl::NEAREST_MIPMAP_LINEAR,
},
TextureFilter::Linear => match mipmap {
TextureFilter::Nearest => gl::LINEAR_MIPMAP_NEAREST,
TextureFilter::Linear => gl::LINEAR_MIPMAP_LINEAR,
},
}
}
}
/// Represents a OpenGL texture format.
#[repr(u32)] // GLenum is u32
#[allow(non_camel_case_types, dead_code)]
#[derive(Debug, Copy, Clone)]
pub enum TextureFormat {
RGBA_F32 = gl::RGBA32F,
RGBA_F16 = gl::RGBA16F,
RGB_F32 = gl::RGB32F,
RGB_F16 = gl::RGB16F,
R_F32 = gl::R32F,
R_F16 = gl::R16F,
RGBA_8 = gl::RGBA8,
RGB_8 = gl::RGB8,
R_8 = gl::R8,
}
impl TextureFormat {
/// Retrieves the unsized version of the given format
pub fn unsized_format(&self) -> GLenum {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGBA_F16 | TextureFormat::RGBA_8 => gl::RGBA,
TextureFormat::RGB_F32 | TextureFormat::RGB_F16 | TextureFormat::RGB_8 => gl::RGB,
TextureFormat::R_F32 | TextureFormat::R_F16 | TextureFormat::R_8 => gl::RED,
}
}
/// The OpenGL primitive associated with this color format.
pub fn gl_primitive_enum(&self) -> GLenum {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGB_F32 | TextureFormat::R_F32 => gl::FLOAT,
TextureFormat::RGBA_F16 | TextureFormat::RGB_F16 | TextureFormat::R_F16 => gl::FLOAT,
TextureFormat::RGBA_8 | TextureFormat::RGB_8 | TextureFormat::R_8 => gl::UNSIGNED_BYTE,
}
}
/// The name of the OpenGL primitive associated with this color format.
pub fn gl_primitive_enum_name(&self) -> &'static str {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGB_F32 | TextureFormat::R_F32 => "GLfloat",
TextureFormat::RGBA_F16 | TextureFormat::RGB_F16 | TextureFormat::R_F16 => "GLfloat",
TextureFormat::RGBA_8 | TextureFormat::RGB_8 | TextureFormat::R_8 => "GLbyte",
}
}
/// The number of components this color format has. For example, `RGB_8` has 3 components.
pub fn components(&self) -> usize {
match *self {
TextureFormat::RGBA_F32 | TextureFormat::RGBA_F16 | TextureFormat::RGBA_8 => 4,
TextureFormat::RGB_F32 | TextureFormat::RGB_F16 | TextureFormat::RGB_8 => 3,
TextureFormat::R_F32 | TextureFormat::R_F16 | TextureFormat::R_8 => 1,
}
}
}
/// Components that a texture can be mapped to through swizzling. See
/// [`set_swizzle_mask`](struct.Texture.html#method.set_swizzle_mask)
/// for more info.
#[repr(u32)] // GLenum is u32
#[derive(Debug, Copy, Clone)]
pub enum SwizzleComp {
Red = gl::RED,
Green = gl::GREEN,
Blue = gl::BLUE,
Alpha = gl::ALPHA,
One = gl::ONE,
Zero = gl::ZERO,
}
/// A error which can occur during texture loading and creation.
#[derive(Debug)]
pub struct TextureError {
source: Option<String>,
error: io::Error,
}
impl error::Error for TextureError {
fn description(&self) -> &str {
self.error.description()
}
fn cause(&self) -> Option<&error::Error> {
self.error.cause()
}
}
impl fmt::Display for TextureError {
fn fmt(&self, mut f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref source) = self.source {
write!(f, "For texture \"{}\": ", source)?;
}
self.error.fmt(&mut f)?;
Ok(())
}
}
impl From<TextureError> for io::Error {
fn from(err: TextureError) -> io::Error {
io::Error::new(io::ErrorKind::Other, err)
}
}
|
{
let mut texture = Texture::new();
let data = RawImageData::from_bytes(bytes, source)?;
texture.load_raw_image_data(data)?;
Ok(texture)
}
|
identifier_body
|
client.rs
|
extern crate env_logger;
extern crate mio;
extern crate tick;
use std::io::{self, Read, Write, stdout};
type Tcp = mio::tcp::TcpStream;
struct Client {
msg: &'static [u8],
pos: usize,
eof: bool,
}
impl Client {
fn
|
() -> Client {
Client {
msg: b"GET / HTTP/1.1\r\n\r\n",
pos: 0,
eof: false,
}
}
}
impl Client {
fn interest(&self) -> tick::Interest {
if self.eof {
tick::Interest::Remove
} else if self.pos < self.msg.len() {
tick::Interest::ReadWrite
} else {
tick::Interest::Read
}
}
}
impl tick::Protocol<Tcp> for Client {
fn on_readable(&mut self, transport: &mut Tcp) -> tick::Interest {
let mut buf = [0u8; 4096];
loop {
match transport.read(&mut buf) {
Ok(0) => {
self.eof = true;
break;
}
Ok(n) => {
stdout().write_all(&buf[..n]).unwrap();
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => break,
Err(_) => return tick::Interest::Remove,
}
}
self.interest()
}
fn on_writable(&mut self, transport: &mut Tcp) -> tick::Interest {
while self.pos < self.msg.len() {
match transport.write(&self.msg[self.pos..]) {
Ok(0) => return tick::Interest::Remove,
Ok(n) => self.pos += n,
Err(e) => match e.kind() {
io::ErrorKind::WouldBlock => break,
_ => {
return tick::Interest::Remove;
}
}
}
}
self.interest()
}
fn on_error(&mut self, err: tick::Error) {
self.eof = true;
println!("on_error: {:?}", err);
}
}
fn main() {
env_logger::init().unwrap();
let mut tick = tick::Tick::<mio::tcp::TcpListener, _>::new(|_| (Client::new(), tick::Interest::Write));
let sock = mio::tcp::TcpStream::connect(&"127.0.0.1:1337".parse().unwrap()).unwrap();
let id = tick.stream(sock).unwrap();
println!("Connecting to 127.0.0.1:1337");
tick.run_until_complete(id).unwrap();
}
|
new
|
identifier_name
|
client.rs
|
extern crate env_logger;
extern crate mio;
extern crate tick;
use std::io::{self, Read, Write, stdout};
type Tcp = mio::tcp::TcpStream;
struct Client {
msg: &'static [u8],
pos: usize,
eof: bool,
}
impl Client {
fn new() -> Client {
Client {
msg: b"GET / HTTP/1.1\r\n\r\n",
pos: 0,
eof: false,
}
}
}
impl Client {
fn interest(&self) -> tick::Interest {
if self.eof {
tick::Interest::Remove
} else if self.pos < self.msg.len() {
tick::Interest::ReadWrite
} else {
tick::Interest::Read
}
}
}
impl tick::Protocol<Tcp> for Client {
fn on_readable(&mut self, transport: &mut Tcp) -> tick::Interest {
let mut buf = [0u8; 4096];
loop {
match transport.read(&mut buf) {
Ok(0) => {
self.eof = true;
break;
}
Ok(n) => {
stdout().write_all(&buf[..n]).unwrap();
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => break,
Err(_) => return tick::Interest::Remove,
}
}
self.interest()
}
fn on_writable(&mut self, transport: &mut Tcp) -> tick::Interest {
while self.pos < self.msg.len() {
match transport.write(&self.msg[self.pos..]) {
Ok(0) => return tick::Interest::Remove,
Ok(n) => self.pos += n,
Err(e) => match e.kind() {
io::ErrorKind::WouldBlock => break,
_ => {
return tick::Interest::Remove;
}
|
}
}
}
self.interest()
}
fn on_error(&mut self, err: tick::Error) {
self.eof = true;
println!("on_error: {:?}", err);
}
}
fn main() {
env_logger::init().unwrap();
let mut tick = tick::Tick::<mio::tcp::TcpListener, _>::new(|_| (Client::new(), tick::Interest::Write));
let sock = mio::tcp::TcpStream::connect(&"127.0.0.1:1337".parse().unwrap()).unwrap();
let id = tick.stream(sock).unwrap();
println!("Connecting to 127.0.0.1:1337");
tick.run_until_complete(id).unwrap();
}
|
random_line_split
|
|
client.rs
|
extern crate env_logger;
extern crate mio;
extern crate tick;
use std::io::{self, Read, Write, stdout};
type Tcp = mio::tcp::TcpStream;
struct Client {
msg: &'static [u8],
pos: usize,
eof: bool,
}
impl Client {
fn new() -> Client {
Client {
msg: b"GET / HTTP/1.1\r\n\r\n",
pos: 0,
eof: false,
}
}
}
impl Client {
fn interest(&self) -> tick::Interest {
if self.eof {
tick::Interest::Remove
} else if self.pos < self.msg.len() {
tick::Interest::ReadWrite
} else {
tick::Interest::Read
}
}
}
impl tick::Protocol<Tcp> for Client {
fn on_readable(&mut self, transport: &mut Tcp) -> tick::Interest {
let mut buf = [0u8; 4096];
loop {
match transport.read(&mut buf) {
Ok(0) => {
self.eof = true;
break;
}
Ok(n) => {
stdout().write_all(&buf[..n]).unwrap();
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => break,
Err(_) => return tick::Interest::Remove,
}
}
self.interest()
}
fn on_writable(&mut self, transport: &mut Tcp) -> tick::Interest {
while self.pos < self.msg.len() {
match transport.write(&self.msg[self.pos..]) {
Ok(0) => return tick::Interest::Remove,
Ok(n) => self.pos += n,
Err(e) => match e.kind() {
io::ErrorKind::WouldBlock => break,
_ => {
return tick::Interest::Remove;
}
}
}
}
self.interest()
}
fn on_error(&mut self, err: tick::Error) {
self.eof = true;
println!("on_error: {:?}", err);
}
}
fn main()
|
{
env_logger::init().unwrap();
let mut tick = tick::Tick::<mio::tcp::TcpListener, _>::new(|_| (Client::new(), tick::Interest::Write));
let sock = mio::tcp::TcpStream::connect(&"127.0.0.1:1337".parse().unwrap()).unwrap();
let id = tick.stream(sock).unwrap();
println!("Connecting to 127.0.0.1:1337");
tick.run_until_complete(id).unwrap();
}
|
identifier_body
|
|
extern-call-indirect.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::libc;
mod rustrt {
use std::libc;
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
fact(data - 1u) * data
}
}
#[fixed_stack_segment] #[inline(never)]
fn fact(n: uint) -> uint {
unsafe {
info!("n = %?", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn
|
() {
let result = fact(10u);
info!("result = %?", result);
assert_eq!(result, 3628800u);
}
|
main
|
identifier_name
|
extern-call-indirect.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::libc;
mod rustrt {
use std::libc;
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
fact(data - 1u) * data
}
}
#[fixed_stack_segment] #[inline(never)]
fn fact(n: uint) -> uint
|
pub fn main() {
let result = fact(10u);
info!("result = %?", result);
assert_eq!(result, 3628800u);
}
|
{
unsafe {
info!("n = %?", n);
rustrt::rust_dbg_call(cb, n)
}
}
|
identifier_body
|
extern-call-indirect.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::libc;
mod rustrt {
use std::libc;
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u
|
else {
fact(data - 1u) * data
}
}
#[fixed_stack_segment] #[inline(never)]
fn fact(n: uint) -> uint {
unsafe {
info!("n = %?", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
let result = fact(10u);
info!("result = %?", result);
assert_eq!(result, 3628800u);
}
|
{
data
}
|
conditional_block
|
extern-call-indirect.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::libc;
mod rustrt {
use std::libc;
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
fact(data - 1u) * data
}
}
#[fixed_stack_segment] #[inline(never)]
fn fact(n: uint) -> uint {
unsafe {
|
}
pub fn main() {
let result = fact(10u);
info!("result = %?", result);
assert_eq!(result, 3628800u);
}
|
info!("n = %?", n);
rustrt::rust_dbg_call(cb, n)
}
|
random_line_split
|
assets.rs
|
// Copyright (C) 2013 - 2021 Tim Düsterhus
// Copyright (C) 2021 Maximilian Mader
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later
use crate::http::{
error::{Error, Error::FileNotFound},
header::not_modified,
};
use actix_web::{
get,
|
#[get("/favicon.ico")]
pub async fn favicon(req: HttpRequest) -> impl Responder {
serve_asset(req, "favicon.ico")
}
#[get("/static/{filename:.+}")]
pub async fn assets(req: HttpRequest, filename: web::Path<String>) -> impl Responder {
serve_asset(req, &filename)
}
fn serve_asset(req: HttpRequest, filename: &str) -> Result<impl Responder, Error> {
let file = format!("assets/static/{}", filename);
crate::SOURCE_FILES
.get(file.as_str())
.map(|source_file| {
let etag = ETag::from(source_file);
if not_modified(&req, Some(&etag), None) {
return HttpResponse::NotModified()
.insert_header(etag)
.insert_header(CacheControl(vec![CacheDirective::Public]))
.body(()); // None
}
let content_type = if filename.ends_with(".js.map") {
"application/json".to_owned()
} else {
mime_guess::from_path(filename)
.first_or_octet_stream()
.to_string()
};
HttpResponse::Ok()
.insert_header(etag)
.insert_header(CacheControl(vec![CacheDirective::Public]))
.content_type(content_type)
.body(source_file.contents)
})
.ok_or(FileNotFound(req, file))
}
|
http::header::{CacheControl, CacheDirective, ETag},
web, HttpRequest, HttpResponse, Responder,
};
|
random_line_split
|
assets.rs
|
// Copyright (C) 2013 - 2021 Tim Düsterhus
// Copyright (C) 2021 Maximilian Mader
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later
use crate::http::{
error::{Error, Error::FileNotFound},
header::not_modified,
};
use actix_web::{
get,
http::header::{CacheControl, CacheDirective, ETag},
web, HttpRequest, HttpResponse, Responder,
};
#[get("/favicon.ico")]
pub async fn favicon(req: HttpRequest) -> impl Responder {
serve_asset(req, "favicon.ico")
}
#[get("/static/{filename:.+}")]
pub async fn assets(req: HttpRequest, filename: web::Path<String>) -> impl Responder {
serve_asset(req, &filename)
}
fn serve_asset(req: HttpRequest, filename: &str) -> Result<impl Responder, Error> {
|
.to_string()
};
HttpResponse::Ok()
.insert_header(etag)
.insert_header(CacheControl(vec![CacheDirective::Public]))
.content_type(content_type)
.body(source_file.contents)
})
.ok_or(FileNotFound(req, file))
}
|
let file = format!("assets/static/{}", filename);
crate::SOURCE_FILES
.get(file.as_str())
.map(|source_file| {
let etag = ETag::from(source_file);
if not_modified(&req, Some(&etag), None) {
return HttpResponse::NotModified()
.insert_header(etag)
.insert_header(CacheControl(vec![CacheDirective::Public]))
.body(()); // None
}
let content_type = if filename.ends_with(".js.map") {
"application/json".to_owned()
} else {
mime_guess::from_path(filename)
.first_or_octet_stream()
|
identifier_body
|
assets.rs
|
// Copyright (C) 2013 - 2021 Tim Düsterhus
// Copyright (C) 2021 Maximilian Mader
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later
use crate::http::{
error::{Error, Error::FileNotFound},
header::not_modified,
};
use actix_web::{
get,
http::header::{CacheControl, CacheDirective, ETag},
web, HttpRequest, HttpResponse, Responder,
};
#[get("/favicon.ico")]
pub async fn favicon(req: HttpRequest) -> impl Responder {
serve_asset(req, "favicon.ico")
}
#[get("/static/{filename:.+}")]
pub async fn assets(req: HttpRequest, filename: web::Path<String>) -> impl Responder {
serve_asset(req, &filename)
}
fn serve_asset(req: HttpRequest, filename: &str) -> Result<impl Responder, Error> {
let file = format!("assets/static/{}", filename);
crate::SOURCE_FILES
.get(file.as_str())
.map(|source_file| {
let etag = ETag::from(source_file);
if not_modified(&req, Some(&etag), None) {
|
let content_type = if filename.ends_with(".js.map") {
"application/json".to_owned()
} else {
mime_guess::from_path(filename)
.first_or_octet_stream()
.to_string()
};
HttpResponse::Ok()
.insert_header(etag)
.insert_header(CacheControl(vec![CacheDirective::Public]))
.content_type(content_type)
.body(source_file.contents)
})
.ok_or(FileNotFound(req, file))
}
|
return HttpResponse::NotModified()
.insert_header(etag)
.insert_header(CacheControl(vec![CacheDirective::Public]))
.body(()); // None
}
|
conditional_block
|
assets.rs
|
// Copyright (C) 2013 - 2021 Tim Düsterhus
// Copyright (C) 2021 Maximilian Mader
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later
use crate::http::{
error::{Error, Error::FileNotFound},
header::not_modified,
};
use actix_web::{
get,
http::header::{CacheControl, CacheDirective, ETag},
web, HttpRequest, HttpResponse, Responder,
};
#[get("/favicon.ico")]
pub async fn favicon(req: HttpRequest) -> impl Responder {
serve_asset(req, "favicon.ico")
}
#[get("/static/{filename:.+}")]
pub async fn assets(req: HttpRequest, filename: web::Path<String>) -> impl Responder {
serve_asset(req, &filename)
}
fn s
|
req: HttpRequest, filename: &str) -> Result<impl Responder, Error> {
let file = format!("assets/static/{}", filename);
crate::SOURCE_FILES
.get(file.as_str())
.map(|source_file| {
let etag = ETag::from(source_file);
if not_modified(&req, Some(&etag), None) {
return HttpResponse::NotModified()
.insert_header(etag)
.insert_header(CacheControl(vec![CacheDirective::Public]))
.body(()); // None
}
let content_type = if filename.ends_with(".js.map") {
"application/json".to_owned()
} else {
mime_guess::from_path(filename)
.first_or_octet_stream()
.to_string()
};
HttpResponse::Ok()
.insert_header(etag)
.insert_header(CacheControl(vec![CacheDirective::Public]))
.content_type(content_type)
.body(source_file.contents)
})
.ok_or(FileNotFound(req, file))
}
|
erve_asset(
|
identifier_name
|
http_loader.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt};
use log;
use std::collections::HashSet;
use http::client::{RequestWriter, NetworkStream};
use http::headers::HeaderEnum;
use std::io::Reader;
use servo_util::task::spawn_named;
use url::Url;
pub fn factory(load_data: LoadData, start_chan: Sender<LoadResponse>) {
spawn_named("http_loader", proc() load(load_data, start_chan))
}
fn send_error(url: Url, err: String, start_chan: Sender<LoadResponse>) {
match start_sending_opt(start_chan, Metadata::default(url), None) {
Ok(p) => p.send(Done(Err(err))),
_ => {}
};
}
pub fn
|
(load_data: LoadData, start_chan: Sender<LoadResponse>) {
// FIXME: At the time of writing this FIXME, servo didn't have any central
// location for configuration. If you're reading this and such a
// repository DOES exist, please update this constant to use it.
let max_redirects = 50u;
let mut iters = 0u;
let mut url = load_data.url.clone();
let mut redirected_to = HashSet::new();
// Loop to handle redirects.
loop {
iters = iters + 1;
if iters > max_redirects {
send_error(url, "too many redirects".to_string(), start_chan);
return;
}
if redirected_to.contains(&url) {
send_error(url, "redirect loop".to_string(), start_chan);
return;
}
redirected_to.insert(url.clone());
match url.scheme.as_slice() {
"http" | "https" => {}
_ => {
let s = format!("{:s} request, but we don't support that scheme", url.scheme);
send_error(url, s, start_chan);
return;
}
}
info!("requesting {:s}", url.serialize());
let request = RequestWriter::<NetworkStream>::new(load_data.method.clone(), url.clone());
let mut writer = match request {
Ok(w) => box w,
Err(e) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
};
// Preserve the `host` header set automatically by RequestWriter.
let host = writer.headers.host.clone();
writer.headers = load_data.headers.clone();
writer.headers.host = host;
if writer.headers.accept_encoding.is_none() {
// We currently don't support HTTP Compression (FIXME #2587)
writer.headers.accept_encoding = Some(String::from_str("identity".as_slice()))
}
match load_data.data {
Some(ref data) => {
writer.headers.content_length = Some(data.len());
match writer.write(data.as_slice()) {
Err(e) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
_ => {}
}
},
_ => {}
}
let mut response = match writer.read_response() {
Ok(r) => r,
Err((_, e)) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
};
/*
We are currently unable to test this due to the stream member of ResponseReader being private in rust-http
let tcpstream: TcpStream = match response.stream.wrapped {
NormalStream(TcpStream) => TcpStream.clone(),
SslProtectedStream(SslStream<TcpStream>) => panic!("invalid network stream")
};
*/
// Dump headers, but only do the iteration if info!() is enabled.
info!("got HTTP response {:s}, headers:", response.status.to_string());
if log_enabled!(log::INFO) {
for header in response.headers.iter() {
info!(" - {:s}: {:s}", header.header_name(), header.header_value());
}
}
if 3 == (response.status.code() / 100) {
match response.headers.location {
Some(new_url) => {
// CORS (http://fetch.spec.whatwg.org/#http-fetch, status section, point 9, 10)
match load_data.cors {
Some(ref c) => {
if c.preflight {
// The preflight lied
send_error(url, "Preflight fetch inconsistent with main fetch".to_string(), start_chan);
return;
} else {
// XXXManishearth There are some CORS-related steps here,
// but they don't seem necessary until credentials are implemented
}
}
_ => {}
}
info!("redirecting to {:s}", new_url.serialize());
url = new_url;
continue;
}
None => ()
}
}
let mut metadata = Metadata::default(url);
metadata.set_content_type(&response.headers.content_type);
metadata.headers = Some(response.headers.clone());
metadata.status = response.status.clone();
/*
Once the stream is made public in ResponseReader, change None in the function below to tcpstream variable created above after the changes are tested.
*/
let progress_chan = match start_sending_opt(start_chan, metadata, None) {
Ok(p) => p,
_ => return
};
loop {
let mut buf = Vec::with_capacity(1024);
unsafe { buf.set_len(1024); }
match response.read(buf.as_mut_slice()) {
Ok(len) => {
unsafe { buf.set_len(len); }
if progress_chan.send_opt(Payload(buf)).is_err() {
// The send errors when the receiver is out of scope,
// which will happen if the fetch has timed out (or has been aborted)
// so we don't need to continue with the loading of the file here.
return;
}
}
Err(_) => {
let _ = progress_chan.send_opt(Done(Ok(())));
break;
}
}
}
// We didn't get redirected.
break;
}
}
|
load
|
identifier_name
|
http_loader.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt};
use log;
use std::collections::HashSet;
use http::client::{RequestWriter, NetworkStream};
use http::headers::HeaderEnum;
use std::io::Reader;
|
}
fn send_error(url: Url, err: String, start_chan: Sender<LoadResponse>) {
match start_sending_opt(start_chan, Metadata::default(url), None) {
Ok(p) => p.send(Done(Err(err))),
_ => {}
};
}
pub fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
// FIXME: At the time of writing this FIXME, servo didn't have any central
// location for configuration. If you're reading this and such a
// repository DOES exist, please update this constant to use it.
let max_redirects = 50u;
let mut iters = 0u;
let mut url = load_data.url.clone();
let mut redirected_to = HashSet::new();
// Loop to handle redirects.
loop {
iters = iters + 1;
if iters > max_redirects {
send_error(url, "too many redirects".to_string(), start_chan);
return;
}
if redirected_to.contains(&url) {
send_error(url, "redirect loop".to_string(), start_chan);
return;
}
redirected_to.insert(url.clone());
match url.scheme.as_slice() {
"http" | "https" => {}
_ => {
let s = format!("{:s} request, but we don't support that scheme", url.scheme);
send_error(url, s, start_chan);
return;
}
}
info!("requesting {:s}", url.serialize());
let request = RequestWriter::<NetworkStream>::new(load_data.method.clone(), url.clone());
let mut writer = match request {
Ok(w) => box w,
Err(e) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
};
// Preserve the `host` header set automatically by RequestWriter.
let host = writer.headers.host.clone();
writer.headers = load_data.headers.clone();
writer.headers.host = host;
if writer.headers.accept_encoding.is_none() {
// We currently don't support HTTP Compression (FIXME #2587)
writer.headers.accept_encoding = Some(String::from_str("identity".as_slice()))
}
match load_data.data {
Some(ref data) => {
writer.headers.content_length = Some(data.len());
match writer.write(data.as_slice()) {
Err(e) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
_ => {}
}
},
_ => {}
}
let mut response = match writer.read_response() {
Ok(r) => r,
Err((_, e)) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
};
/*
We are currently unable to test this due to the stream member of ResponseReader being private in rust-http
let tcpstream: TcpStream = match response.stream.wrapped {
NormalStream(TcpStream) => TcpStream.clone(),
SslProtectedStream(SslStream<TcpStream>) => panic!("invalid network stream")
};
*/
// Dump headers, but only do the iteration if info!() is enabled.
info!("got HTTP response {:s}, headers:", response.status.to_string());
if log_enabled!(log::INFO) {
for header in response.headers.iter() {
info!(" - {:s}: {:s}", header.header_name(), header.header_value());
}
}
if 3 == (response.status.code() / 100) {
match response.headers.location {
Some(new_url) => {
// CORS (http://fetch.spec.whatwg.org/#http-fetch, status section, point 9, 10)
match load_data.cors {
Some(ref c) => {
if c.preflight {
// The preflight lied
send_error(url, "Preflight fetch inconsistent with main fetch".to_string(), start_chan);
return;
} else {
// XXXManishearth There are some CORS-related steps here,
// but they don't seem necessary until credentials are implemented
}
}
_ => {}
}
info!("redirecting to {:s}", new_url.serialize());
url = new_url;
continue;
}
None => ()
}
}
let mut metadata = Metadata::default(url);
metadata.set_content_type(&response.headers.content_type);
metadata.headers = Some(response.headers.clone());
metadata.status = response.status.clone();
/*
Once the stream is made public in ResponseReader, change None in the function below to tcpstream variable created above after the changes are tested.
*/
let progress_chan = match start_sending_opt(start_chan, metadata, None) {
Ok(p) => p,
_ => return
};
loop {
let mut buf = Vec::with_capacity(1024);
unsafe { buf.set_len(1024); }
match response.read(buf.as_mut_slice()) {
Ok(len) => {
unsafe { buf.set_len(len); }
if progress_chan.send_opt(Payload(buf)).is_err() {
// The send errors when the receiver is out of scope,
// which will happen if the fetch has timed out (or has been aborted)
// so we don't need to continue with the loading of the file here.
return;
}
}
Err(_) => {
let _ = progress_chan.send_opt(Done(Ok(())));
break;
}
}
}
// We didn't get redirected.
break;
}
}
|
use servo_util::task::spawn_named;
use url::Url;
pub fn factory(load_data: LoadData, start_chan: Sender<LoadResponse>) {
spawn_named("http_loader", proc() load(load_data, start_chan))
|
random_line_split
|
http_loader.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt};
use log;
use std::collections::HashSet;
use http::client::{RequestWriter, NetworkStream};
use http::headers::HeaderEnum;
use std::io::Reader;
use servo_util::task::spawn_named;
use url::Url;
pub fn factory(load_data: LoadData, start_chan: Sender<LoadResponse>) {
spawn_named("http_loader", proc() load(load_data, start_chan))
}
fn send_error(url: Url, err: String, start_chan: Sender<LoadResponse>) {
match start_sending_opt(start_chan, Metadata::default(url), None) {
Ok(p) => p.send(Done(Err(err))),
_ => {}
};
}
pub fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
// FIXME: At the time of writing this FIXME, servo didn't have any central
// location for configuration. If you're reading this and such a
// repository DOES exist, please update this constant to use it.
let max_redirects = 50u;
let mut iters = 0u;
let mut url = load_data.url.clone();
let mut redirected_to = HashSet::new();
// Loop to handle redirects.
loop {
iters = iters + 1;
if iters > max_redirects {
send_error(url, "too many redirects".to_string(), start_chan);
return;
}
if redirected_to.contains(&url) {
send_error(url, "redirect loop".to_string(), start_chan);
return;
}
redirected_to.insert(url.clone());
match url.scheme.as_slice() {
"http" | "https" => {}
_ => {
let s = format!("{:s} request, but we don't support that scheme", url.scheme);
send_error(url, s, start_chan);
return;
}
}
info!("requesting {:s}", url.serialize());
let request = RequestWriter::<NetworkStream>::new(load_data.method.clone(), url.clone());
let mut writer = match request {
Ok(w) => box w,
Err(e) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
};
// Preserve the `host` header set automatically by RequestWriter.
let host = writer.headers.host.clone();
writer.headers = load_data.headers.clone();
writer.headers.host = host;
if writer.headers.accept_encoding.is_none() {
// We currently don't support HTTP Compression (FIXME #2587)
writer.headers.accept_encoding = Some(String::from_str("identity".as_slice()))
}
match load_data.data {
Some(ref data) => {
writer.headers.content_length = Some(data.len());
match writer.write(data.as_slice()) {
Err(e) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
_ =>
|
}
},
_ => {}
}
let mut response = match writer.read_response() {
Ok(r) => r,
Err((_, e)) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
};
/*
We are currently unable to test this due to the stream member of ResponseReader being private in rust-http
let tcpstream: TcpStream = match response.stream.wrapped {
NormalStream(TcpStream) => TcpStream.clone(),
SslProtectedStream(SslStream<TcpStream>) => panic!("invalid network stream")
};
*/
// Dump headers, but only do the iteration if info!() is enabled.
info!("got HTTP response {:s}, headers:", response.status.to_string());
if log_enabled!(log::INFO) {
for header in response.headers.iter() {
info!(" - {:s}: {:s}", header.header_name(), header.header_value());
}
}
if 3 == (response.status.code() / 100) {
match response.headers.location {
Some(new_url) => {
// CORS (http://fetch.spec.whatwg.org/#http-fetch, status section, point 9, 10)
match load_data.cors {
Some(ref c) => {
if c.preflight {
// The preflight lied
send_error(url, "Preflight fetch inconsistent with main fetch".to_string(), start_chan);
return;
} else {
// XXXManishearth There are some CORS-related steps here,
// but they don't seem necessary until credentials are implemented
}
}
_ => {}
}
info!("redirecting to {:s}", new_url.serialize());
url = new_url;
continue;
}
None => ()
}
}
let mut metadata = Metadata::default(url);
metadata.set_content_type(&response.headers.content_type);
metadata.headers = Some(response.headers.clone());
metadata.status = response.status.clone();
/*
Once the stream is made public in ResponseReader, change None in the function below to tcpstream variable created above after the changes are tested.
*/
let progress_chan = match start_sending_opt(start_chan, metadata, None) {
Ok(p) => p,
_ => return
};
loop {
let mut buf = Vec::with_capacity(1024);
unsafe { buf.set_len(1024); }
match response.read(buf.as_mut_slice()) {
Ok(len) => {
unsafe { buf.set_len(len); }
if progress_chan.send_opt(Payload(buf)).is_err() {
// The send errors when the receiver is out of scope,
// which will happen if the fetch has timed out (or has been aborted)
// so we don't need to continue with the loading of the file here.
return;
}
}
Err(_) => {
let _ = progress_chan.send_opt(Done(Ok(())));
break;
}
}
}
// We didn't get redirected.
break;
}
}
|
{}
|
conditional_block
|
http_loader.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt};
use log;
use std::collections::HashSet;
use http::client::{RequestWriter, NetworkStream};
use http::headers::HeaderEnum;
use std::io::Reader;
use servo_util::task::spawn_named;
use url::Url;
pub fn factory(load_data: LoadData, start_chan: Sender<LoadResponse>) {
spawn_named("http_loader", proc() load(load_data, start_chan))
}
fn send_error(url: Url, err: String, start_chan: Sender<LoadResponse>) {
match start_sending_opt(start_chan, Metadata::default(url), None) {
Ok(p) => p.send(Done(Err(err))),
_ => {}
};
}
pub fn load(load_data: LoadData, start_chan: Sender<LoadResponse>)
|
return;
}
redirected_to.insert(url.clone());
match url.scheme.as_slice() {
"http" | "https" => {}
_ => {
let s = format!("{:s} request, but we don't support that scheme", url.scheme);
send_error(url, s, start_chan);
return;
}
}
info!("requesting {:s}", url.serialize());
let request = RequestWriter::<NetworkStream>::new(load_data.method.clone(), url.clone());
let mut writer = match request {
Ok(w) => box w,
Err(e) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
};
// Preserve the `host` header set automatically by RequestWriter.
let host = writer.headers.host.clone();
writer.headers = load_data.headers.clone();
writer.headers.host = host;
if writer.headers.accept_encoding.is_none() {
// We currently don't support HTTP Compression (FIXME #2587)
writer.headers.accept_encoding = Some(String::from_str("identity".as_slice()))
}
match load_data.data {
Some(ref data) => {
writer.headers.content_length = Some(data.len());
match writer.write(data.as_slice()) {
Err(e) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
_ => {}
}
},
_ => {}
}
let mut response = match writer.read_response() {
Ok(r) => r,
Err((_, e)) => {
send_error(url, e.desc.to_string(), start_chan);
return;
}
};
/*
We are currently unable to test this due to the stream member of ResponseReader being private in rust-http
let tcpstream: TcpStream = match response.stream.wrapped {
NormalStream(TcpStream) => TcpStream.clone(),
SslProtectedStream(SslStream<TcpStream>) => panic!("invalid network stream")
};
*/
// Dump headers, but only do the iteration if info!() is enabled.
info!("got HTTP response {:s}, headers:", response.status.to_string());
if log_enabled!(log::INFO) {
for header in response.headers.iter() {
info!(" - {:s}: {:s}", header.header_name(), header.header_value());
}
}
if 3 == (response.status.code() / 100) {
match response.headers.location {
Some(new_url) => {
// CORS (http://fetch.spec.whatwg.org/#http-fetch, status section, point 9, 10)
match load_data.cors {
Some(ref c) => {
if c.preflight {
// The preflight lied
send_error(url, "Preflight fetch inconsistent with main fetch".to_string(), start_chan);
return;
} else {
// XXXManishearth There are some CORS-related steps here,
// but they don't seem necessary until credentials are implemented
}
}
_ => {}
}
info!("redirecting to {:s}", new_url.serialize());
url = new_url;
continue;
}
None => ()
}
}
let mut metadata = Metadata::default(url);
metadata.set_content_type(&response.headers.content_type);
metadata.headers = Some(response.headers.clone());
metadata.status = response.status.clone();
/*
Once the stream is made public in ResponseReader, change None in the function below to tcpstream variable created above after the changes are tested.
*/
let progress_chan = match start_sending_opt(start_chan, metadata, None) {
Ok(p) => p,
_ => return
};
loop {
let mut buf = Vec::with_capacity(1024);
unsafe { buf.set_len(1024); }
match response.read(buf.as_mut_slice()) {
Ok(len) => {
unsafe { buf.set_len(len); }
if progress_chan.send_opt(Payload(buf)).is_err() {
// The send errors when the receiver is out of scope,
// which will happen if the fetch has timed out (or has been aborted)
// so we don't need to continue with the loading of the file here.
return;
}
}
Err(_) => {
let _ = progress_chan.send_opt(Done(Ok(())));
break;
}
}
}
// We didn't get redirected.
break;
}
}
|
{
// FIXME: At the time of writing this FIXME, servo didn't have any central
// location for configuration. If you're reading this and such a
// repository DOES exist, please update this constant to use it.
let max_redirects = 50u;
let mut iters = 0u;
let mut url = load_data.url.clone();
let mut redirected_to = HashSet::new();
// Loop to handle redirects.
loop {
iters = iters + 1;
if iters > max_redirects {
send_error(url, "too many redirects".to_string(), start_chan);
return;
}
if redirected_to.contains(&url) {
send_error(url, "redirect loop".to_string(), start_chan);
|
identifier_body
|
procfs.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Measurement based on procfs (/proc)
use super::Bytes;
use super::Measure;
|
/// Measure IO.
pub struct IO {
rchar: u64,
wchar: u64,
}
#[derive(Debug)]
struct IOSnapshot {
rchar: u64,
wchar: u64,
rchar_overhead: u64,
}
fn read_io() -> Result<IOSnapshot, String> {
let io_str = std::fs::read_to_string("/proc/self/io").map_err(|_| "(no data)".to_string())?;
let mut rchar: u64 = 0;
let mut wchar: u64 = 0;
const RCHAR_PREFIX: &str = "rchar: ";
const WCHAR_PREFIX: &str = "wchar: ";
for line in io_str.lines() {
if line.starts_with(RCHAR_PREFIX) {
rchar += line[RCHAR_PREFIX.len()..]
.parse::<u64>()
.map_err(|_| "unexpected rchar".to_string())?;
} else if line.starts_with(WCHAR_PREFIX) {
wchar += line[WCHAR_PREFIX.len()..]
.parse::<u64>()
.map_err(|_| "unexpected wchar".to_string())?;
}
}
// Reading io has side effect on rchar. Record it.
let rchar_overhead = io_str.len() as u64;
Ok(IOSnapshot {
rchar,
wchar,
rchar_overhead,
})
}
impl Measure for IO {
type FuncOutput = ();
fn measure(mut func: impl FnMut()) -> Result<Self, String> {
let before = read_io()?;
func();
let after = read_io()?;
let rchar = after.rchar - before.rchar - before.rchar_overhead;
let wchar = after.wchar - before.wchar;
Ok(Self { rchar, wchar })
}
fn merge(self, rhs: Self) -> Self {
Self {
rchar: self.rchar.max(rhs.rchar),
wchar: self.wchar.max(rhs.wchar),
}
}
fn need_more(&self) -> bool {
false
}
fn to_string(&self) -> String {
format!(
"{}/{}",
Bytes(self.rchar).to_string(),
Bytes(self.wchar).to_string()
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_io() {
if let Ok(io) = IO::measure(|| {}) {
// The test runner can run things in multi-thread and breaks the measurement here :/
if io.rchar == 0 && io.wchar == 0 {
assert_eq!(io.to_string(), " 0 B / 0 B ");
}
}
}
}
|
random_line_split
|
|
procfs.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Measurement based on procfs (/proc)
use super::Bytes;
use super::Measure;
/// Measure IO.
pub struct IO {
rchar: u64,
wchar: u64,
}
#[derive(Debug)]
struct IOSnapshot {
rchar: u64,
wchar: u64,
rchar_overhead: u64,
}
fn read_io() -> Result<IOSnapshot, String> {
let io_str = std::fs::read_to_string("/proc/self/io").map_err(|_| "(no data)".to_string())?;
let mut rchar: u64 = 0;
let mut wchar: u64 = 0;
const RCHAR_PREFIX: &str = "rchar: ";
const WCHAR_PREFIX: &str = "wchar: ";
for line in io_str.lines() {
if line.starts_with(RCHAR_PREFIX) {
rchar += line[RCHAR_PREFIX.len()..]
.parse::<u64>()
.map_err(|_| "unexpected rchar".to_string())?;
} else if line.starts_with(WCHAR_PREFIX) {
wchar += line[WCHAR_PREFIX.len()..]
.parse::<u64>()
.map_err(|_| "unexpected wchar".to_string())?;
}
}
// Reading io has side effect on rchar. Record it.
let rchar_overhead = io_str.len() as u64;
Ok(IOSnapshot {
rchar,
wchar,
rchar_overhead,
})
}
impl Measure for IO {
type FuncOutput = ();
fn measure(mut func: impl FnMut()) -> Result<Self, String> {
let before = read_io()?;
func();
let after = read_io()?;
let rchar = after.rchar - before.rchar - before.rchar_overhead;
let wchar = after.wchar - before.wchar;
Ok(Self { rchar, wchar })
}
fn merge(self, rhs: Self) -> Self {
Self {
rchar: self.rchar.max(rhs.rchar),
wchar: self.wchar.max(rhs.wchar),
}
}
fn need_more(&self) -> bool {
false
}
fn to_string(&self) -> String
|
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_io() {
if let Ok(io) = IO::measure(|| {}) {
// The test runner can run things in multi-thread and breaks the measurement here :/
if io.rchar == 0 && io.wchar == 0 {
assert_eq!(io.to_string(), " 0 B / 0 B ");
}
}
}
}
|
{
format!(
"{}/{}",
Bytes(self.rchar).to_string(),
Bytes(self.wchar).to_string()
)
}
|
identifier_body
|
procfs.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Measurement based on procfs (/proc)
use super::Bytes;
use super::Measure;
/// Measure IO.
pub struct IO {
rchar: u64,
wchar: u64,
}
#[derive(Debug)]
struct
|
{
rchar: u64,
wchar: u64,
rchar_overhead: u64,
}
fn read_io() -> Result<IOSnapshot, String> {
let io_str = std::fs::read_to_string("/proc/self/io").map_err(|_| "(no data)".to_string())?;
let mut rchar: u64 = 0;
let mut wchar: u64 = 0;
const RCHAR_PREFIX: &str = "rchar: ";
const WCHAR_PREFIX: &str = "wchar: ";
for line in io_str.lines() {
if line.starts_with(RCHAR_PREFIX) {
rchar += line[RCHAR_PREFIX.len()..]
.parse::<u64>()
.map_err(|_| "unexpected rchar".to_string())?;
} else if line.starts_with(WCHAR_PREFIX) {
wchar += line[WCHAR_PREFIX.len()..]
.parse::<u64>()
.map_err(|_| "unexpected wchar".to_string())?;
}
}
// Reading io has side effect on rchar. Record it.
let rchar_overhead = io_str.len() as u64;
Ok(IOSnapshot {
rchar,
wchar,
rchar_overhead,
})
}
impl Measure for IO {
type FuncOutput = ();
fn measure(mut func: impl FnMut()) -> Result<Self, String> {
let before = read_io()?;
func();
let after = read_io()?;
let rchar = after.rchar - before.rchar - before.rchar_overhead;
let wchar = after.wchar - before.wchar;
Ok(Self { rchar, wchar })
}
fn merge(self, rhs: Self) -> Self {
Self {
rchar: self.rchar.max(rhs.rchar),
wchar: self.wchar.max(rhs.wchar),
}
}
fn need_more(&self) -> bool {
false
}
fn to_string(&self) -> String {
format!(
"{}/{}",
Bytes(self.rchar).to_string(),
Bytes(self.wchar).to_string()
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_io() {
if let Ok(io) = IO::measure(|| {}) {
// The test runner can run things in multi-thread and breaks the measurement here :/
if io.rchar == 0 && io.wchar == 0 {
assert_eq!(io.to_string(), " 0 B / 0 B ");
}
}
}
}
|
IOSnapshot
|
identifier_name
|
procfs.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Measurement based on procfs (/proc)
use super::Bytes;
use super::Measure;
/// Measure IO.
pub struct IO {
rchar: u64,
wchar: u64,
}
#[derive(Debug)]
struct IOSnapshot {
rchar: u64,
wchar: u64,
rchar_overhead: u64,
}
fn read_io() -> Result<IOSnapshot, String> {
let io_str = std::fs::read_to_string("/proc/self/io").map_err(|_| "(no data)".to_string())?;
let mut rchar: u64 = 0;
let mut wchar: u64 = 0;
const RCHAR_PREFIX: &str = "rchar: ";
const WCHAR_PREFIX: &str = "wchar: ";
for line in io_str.lines() {
if line.starts_with(RCHAR_PREFIX) {
rchar += line[RCHAR_PREFIX.len()..]
.parse::<u64>()
.map_err(|_| "unexpected rchar".to_string())?;
} else if line.starts_with(WCHAR_PREFIX) {
wchar += line[WCHAR_PREFIX.len()..]
.parse::<u64>()
.map_err(|_| "unexpected wchar".to_string())?;
}
}
// Reading io has side effect on rchar. Record it.
let rchar_overhead = io_str.len() as u64;
Ok(IOSnapshot {
rchar,
wchar,
rchar_overhead,
})
}
impl Measure for IO {
type FuncOutput = ();
fn measure(mut func: impl FnMut()) -> Result<Self, String> {
let before = read_io()?;
func();
let after = read_io()?;
let rchar = after.rchar - before.rchar - before.rchar_overhead;
let wchar = after.wchar - before.wchar;
Ok(Self { rchar, wchar })
}
fn merge(self, rhs: Self) -> Self {
Self {
rchar: self.rchar.max(rhs.rchar),
wchar: self.wchar.max(rhs.wchar),
}
}
fn need_more(&self) -> bool {
false
}
fn to_string(&self) -> String {
format!(
"{}/{}",
Bytes(self.rchar).to_string(),
Bytes(self.wchar).to_string()
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_io() {
if let Ok(io) = IO::measure(|| {}) {
// The test runner can run things in multi-thread and breaks the measurement here :/
if io.rchar == 0 && io.wchar == 0
|
}
}
}
|
{
assert_eq!(io.to_string(), " 0 B / 0 B ");
}
|
conditional_block
|
day25.rs
|
use std::collections::HashMap;
use std::io::Read;
use crate::common::from_lines;
use crate::Solution;
const MOD_BASE: u32 = 20201227;
const SUBJECT_NUMBER: u32 = 7;
fn loop_count(public_key: u32) -> u64 {
discrete_log(SUBJECT_NUMBER, public_key, MOD_BASE).unwrap() as u64
}
// Implementation of the baby-step giant-step algorithm
//
// Based on:https://en.wikipedia.org/wiki/Baby-step_giant-step#C++_algorithm_(C++17)
fn
|
(g: u32, h: u32, mod_base: u32) -> Option<u32> {
let m = (mod_base as f64).sqrt().ceil() as u32;
let mut table = HashMap::with_capacity(m as usize);
let mut e: u32 = 1;
for i in 0..m {
table.insert(e, i);
e = ((e as u64 * g as u64) % mod_base as u64) as u32;
}
let factor = mod_exp(g as u64, (mod_base - m - 1) as u64, mod_base as u64);
e = h;
for i in 0..m {
if let Some(&val) = table.get(&e) {
return Some(i * m + val);
}
e = ((e as u64 * factor) % mod_base as u64) as u32;
}
None
}
#[inline]
fn mod_exp(base: u64, mut power: u64, mod_base: u64) -> u64 {
let mut result = 1;
let mut cur = base;
while power > 0 {
if power % 2 == 1 {
result *= cur;
result %= mod_base;
}
cur *= cur;
cur %= mod_base;
power /= 2;
}
result
}
#[derive(Default)]
pub struct Day25;
impl Solution for Day25 {
fn part1(&mut self, input: &mut dyn Read) -> String {
let nums: Vec<_> = from_lines(input);
let key_exponent = loop_count(nums[0]);
mod_exp(nums[1] as u64, key_exponent, MOD_BASE as u64).to_string()
}
fn part2(&mut self, _input: &mut dyn Read) -> String {
"Part 2 is free!".to_string()
}
}
#[cfg(test)]
mod tests {
use crate::test_implementation;
use super::*;
const SAMPLE: &[u8] = include_bytes!("../samples/25.txt");
#[test]
fn test_loop_count() {
assert_eq!(8, loop_count(5764801));
assert_eq!(11, loop_count(17807724));
}
#[test]
fn sample_part1() {
test_implementation(Day25, 1, SAMPLE, 14897079);
}
}
|
discrete_log
|
identifier_name
|
day25.rs
|
use std::collections::HashMap;
use std::io::Read;
use crate::common::from_lines;
use crate::Solution;
const MOD_BASE: u32 = 20201227;
const SUBJECT_NUMBER: u32 = 7;
fn loop_count(public_key: u32) -> u64 {
discrete_log(SUBJECT_NUMBER, public_key, MOD_BASE).unwrap() as u64
}
// Implementation of the baby-step giant-step algorithm
//
// Based on:https://en.wikipedia.org/wiki/Baby-step_giant-step#C++_algorithm_(C++17)
fn discrete_log(g: u32, h: u32, mod_base: u32) -> Option<u32> {
let m = (mod_base as f64).sqrt().ceil() as u32;
let mut table = HashMap::with_capacity(m as usize);
let mut e: u32 = 1;
for i in 0..m {
table.insert(e, i);
e = ((e as u64 * g as u64) % mod_base as u64) as u32;
}
let factor = mod_exp(g as u64, (mod_base - m - 1) as u64, mod_base as u64);
e = h;
for i in 0..m {
if let Some(&val) = table.get(&e) {
return Some(i * m + val);
}
e = ((e as u64 * factor) % mod_base as u64) as u32;
}
None
}
#[inline]
fn mod_exp(base: u64, mut power: u64, mod_base: u64) -> u64 {
let mut result = 1;
let mut cur = base;
while power > 0 {
if power % 2 == 1 {
result *= cur;
result %= mod_base;
}
cur *= cur;
cur %= mod_base;
power /= 2;
}
result
}
#[derive(Default)]
pub struct Day25;
impl Solution for Day25 {
fn part1(&mut self, input: &mut dyn Read) -> String {
let nums: Vec<_> = from_lines(input);
let key_exponent = loop_count(nums[0]);
mod_exp(nums[1] as u64, key_exponent, MOD_BASE as u64).to_string()
}
fn part2(&mut self, _input: &mut dyn Read) -> String {
"Part 2 is free!".to_string()
}
}
#[cfg(test)]
mod tests {
use crate::test_implementation;
use super::*;
const SAMPLE: &[u8] = include_bytes!("../samples/25.txt");
#[test]
fn test_loop_count() {
assert_eq!(8, loop_count(5764801));
assert_eq!(11, loop_count(17807724));
}
#[test]
fn sample_part1()
|
}
|
{
test_implementation(Day25, 1, SAMPLE, 14897079);
}
|
identifier_body
|
day25.rs
|
use std::collections::HashMap;
use std::io::Read;
use crate::common::from_lines;
use crate::Solution;
const MOD_BASE: u32 = 20201227;
const SUBJECT_NUMBER: u32 = 7;
fn loop_count(public_key: u32) -> u64 {
discrete_log(SUBJECT_NUMBER, public_key, MOD_BASE).unwrap() as u64
}
// Implementation of the baby-step giant-step algorithm
//
// Based on:https://en.wikipedia.org/wiki/Baby-step_giant-step#C++_algorithm_(C++17)
fn discrete_log(g: u32, h: u32, mod_base: u32) -> Option<u32> {
let m = (mod_base as f64).sqrt().ceil() as u32;
let mut table = HashMap::with_capacity(m as usize);
let mut e: u32 = 1;
for i in 0..m {
table.insert(e, i);
e = ((e as u64 * g as u64) % mod_base as u64) as u32;
}
let factor = mod_exp(g as u64, (mod_base - m - 1) as u64, mod_base as u64);
e = h;
for i in 0..m {
if let Some(&val) = table.get(&e)
|
e = ((e as u64 * factor) % mod_base as u64) as u32;
}
None
}
#[inline]
fn mod_exp(base: u64, mut power: u64, mod_base: u64) -> u64 {
let mut result = 1;
let mut cur = base;
while power > 0 {
if power % 2 == 1 {
result *= cur;
result %= mod_base;
}
cur *= cur;
cur %= mod_base;
power /= 2;
}
result
}
#[derive(Default)]
pub struct Day25;
impl Solution for Day25 {
fn part1(&mut self, input: &mut dyn Read) -> String {
let nums: Vec<_> = from_lines(input);
let key_exponent = loop_count(nums[0]);
mod_exp(nums[1] as u64, key_exponent, MOD_BASE as u64).to_string()
}
fn part2(&mut self, _input: &mut dyn Read) -> String {
"Part 2 is free!".to_string()
}
}
#[cfg(test)]
mod tests {
use crate::test_implementation;
use super::*;
const SAMPLE: &[u8] = include_bytes!("../samples/25.txt");
#[test]
fn test_loop_count() {
assert_eq!(8, loop_count(5764801));
assert_eq!(11, loop_count(17807724));
}
#[test]
fn sample_part1() {
test_implementation(Day25, 1, SAMPLE, 14897079);
}
}
|
{
return Some(i * m + val);
}
|
conditional_block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.