text stringlengths 8 4.13M |
|---|
use crate::key_code::KeyCode;
use num_enum::TryFromPrimitive;
#[derive(Debug, Clone, Copy)]
#[repr(u8)]
pub enum DescriptorType {
Hid = 0x21,
Report = 0x22,
_Physical = 0x23,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(u8)]
pub enum Request {
GetReport = 0x01,
GetIdle = 0x02,
GetProtocol = 0x03,
SetReport = 0x09,
SetIdle = 0x0a,
SetProtocol = 0x0b,
}
impl Request {
pub fn new(u: u8) -> Option<Request> {
use Request::*;
match u {
0x01 => Some(GetReport),
0x02 => Some(GetIdle),
0x03 => Some(GetProtocol),
0x09 => Some(SetReport),
0x0a => Some(SetIdle),
0x0b => Some(SetProtocol),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ReportType {
Input,
Output,
Feature,
Reserved(u8),
}
impl From<u8> for ReportType {
fn from(val: u8) -> Self {
match val {
1 => ReportType::Input,
2 => ReportType::Output,
3 => ReportType::Feature,
_ => ReportType::Reserved(val),
}
}
}
#[derive(Debug, TryFromPrimitive)]
#[repr(u8)]
pub enum VendorCommand {
Set1 = 1,
Set2,
Set3,
Save,
}
#[derive(Debug, Copy, Clone)]
pub enum AppCommand {
Set1(KeyCode),
Set2(KeyCode),
Set3(KeyCode),
Save,
}
impl AppCommand {
pub fn from_req_value(req: VendorCommand, value: KeyCode) -> Self {
match req {
VendorCommand::Set1 => AppCommand::Set1(value),
VendorCommand::Set2 => AppCommand::Set2(value),
VendorCommand::Set3 => AppCommand::Set3(value),
VendorCommand::Save => AppCommand::Save,
}
}
}
|
/// A trait describing a buffer that is interleaved.
///
/// This allows for accessing the raw underlying interleaved buffer.
pub trait AsInterleaved<T> {
/// Access the underlying raw interleaved buffer.
///
/// # Examples
///
/// ```rust
/// use audio::AsInterleaved;
///
/// fn test<B>(buffer: B) where B: AsInterleaved<i16> {
/// assert_eq!(buffer.as_interleaved(), &[1, 1, 2, 2, 3, 3, 4, 4]);
/// }
///
/// test(audio::interleaved![[1, 2, 3, 4]; 2]);
/// ```
fn as_interleaved(&self) -> &[T];
}
impl<B, T> AsInterleaved<T> for &B
where
B: ?Sized + AsInterleaved<T>,
{
fn as_interleaved(&self) -> &[T] {
(**self).as_interleaved()
}
}
impl<B, T> AsInterleaved<T> for &mut B
where
B: ?Sized + AsInterleaved<T>,
{
fn as_interleaved(&self) -> &[T] {
(**self).as_interleaved()
}
}
|
use crate::parser::stream::Stream;
use crate::parser::*;
use crate::token::Token;
use anyhow::Result;
use trace;
type RHS = (Op, Expr);
pub fn parse_op(stream: &mut Stream) -> Result<Option<RHS>> {
trace!(stream, "parse_op", {
parse_op_bool(stream)
.or_else(|| parse_op_eq(stream))
.or_else(|| parse_op_cmp(stream))
.or_else(|| parse_op_add(stream))
.or_else(|| parse_op_mul(stream))
.transpose()
});
}
fn extract_op(token: Token, stream: &mut Stream, expected_ops: &[Op], msg: &str) -> Result<Op> {
token
.symbol()
.map(|sym| {
Op::parse(sym)
.filter(|op| expected_ops.iter().any(|eop| op == eop))
.ok_or_else(|| stream.unexpected_token_err(msg))
})
.unwrap_or_else(|| stream.unexpected_token_result(msg))
}
fn parse_op_bool(stream: &mut Stream) -> Option<Result<RHS>> {
trace!(stream, "parse_op_bool", {
stream.consume_if_symbols(&['|', '&']).map(|t| {
extract_op(
t,
stream,
&[Op::Or, Op::And],
"expected boolean operator('|', '&')",
)
.and_then(|op| expr::parse_expr_or_die(stream).map(|rhs| (op, rhs)))
})
});
}
fn parse_op_eq(stream: &mut Stream) -> Option<Result<RHS>> {
trace!(stream, "parse_op_eq", {
stream.consume_if_symbol('=').map(|t| {
extract_op(t, stream, &[Op::Eq], "expected eq operator('=')")
.and_then(|op| expr::parse_expr_or_die(stream).map(|rhs| (op, rhs)))
})
});
}
fn parse_op_cmp(stream: &mut Stream) -> Option<Result<RHS>> {
trace!(stream, "parse_op_cmp", {
stream.consume_if_symbols(&['<', '>']).map(|t| {
extract_op(
t,
stream,
&[Op::Lt, Op::Gt],
"expected cmp operator('<', '>')",
)
.and_then(|op| expr::parse_expr_or_die(stream).map(|rhs| (op, rhs)))
})
});
}
fn parse_op_add(stream: &mut Stream) -> Option<Result<RHS>> {
trace!(stream, "parse_op_add", {
stream.consume_if_symbols(&['+', '-']).map(|t| {
extract_op(
t,
stream,
&[Op::Add, Op::Sub],
"expected add or sub operator('+', '-')",
)
.and_then(|op| expr::parse_expr_or_die(stream).map(|rhs| (op, rhs)))
})
});
}
fn parse_op_mul(stream: &mut Stream) -> Option<Result<RHS>> {
trace!(stream, "parse_op_mul", {
stream.consume_if_symbols(&['*', '/']).map(|t| {
extract_op(
t,
stream,
&[Op::Mul, Op::Div],
"expected mul or div operator('*', '/')",
)
.and_then(|op| expr::parse_expr_or_die(stream).map(|rhs| (op, rhs)))
})
});
}
|
use super::util::{linecross, Point, Polygon};
use std::collections::HashMap;
///-----------------------------TODO-------------------------------------------
///
/// make a function that generates polygon type from grid.
///
///---------------------------------------------------------------------------
pub struct Pointbox {
pub pos: (i32, i32),
//first value in edges is with
in_edges: Vec<Vec<(usize, usize)>>,
out_edges: Vec<Vec<(usize, usize)>>,
pub points: Vec<Vec<usize>>,
}
impl Pointbox {
pub fn new (pos: (i32,i32), num_of_poly: usize) -> Self {
let mut in_edges = Vec::new();
let mut out_edges = Vec::new();
let mut points = Vec::new();
(0..num_of_poly).for_each(|_i| {
in_edges.push(vec![]);
out_edges.push(vec![]);
points.push(vec![]);
});
//println!("lenght of edges {}", edges.len());
Self {
pos: pos,
in_edges: in_edges,
out_edges: out_edges,
points: points,
}
}
fn get_in_edges(&self) -> Vec<(u8, &(usize, usize))> {
let mut poly: u8 = 0;
self.in_edges
.iter()
.map(|v| {
poly += 1;
v.iter()
.map(|u| (poly -1, u))
.collect::<Vec<(u8, &(usize, usize))>>()
})
.flatten()
.collect()
}
fn get_all_edges(&self) -> Vec<(u8, &(usize, usize))> {
let mut poly: u8 = 0;
let mut a_edges : Vec<(u8, &(usize, usize))>= self.in_edges
.iter()
.map(|v| {
poly += 1;
v.iter()
.map(|u| (poly -1, u))
.collect::<Vec<(u8, &(usize, usize))>>()
})
.flatten()
.collect();
let mut poly: u8 = 0;
let mut o_edges : Vec<(u8, &(usize, usize))> = self.out_edges
.iter()
.map(|v| {
poly += 1;
v.iter()
.map(|u| (poly -1, u))
.collect::<Vec<(u8, &(usize, usize))>>()
})
.flatten()
.collect();
a_edges.append(&mut o_edges);
return a_edges
}
fn contains_elements_of_poly (&self, poly: usize) -> bool {
! self.points[poly].is_empty()
}
fn len(&self) -> usize {
self.points.iter().fold(0, |acc, vec| acc + vec.len())
}
fn consume(self) -> Vec<Vec<(usize, usize)>> {
self.in_edges
}
}
/// The problems with previous polygon generation is that each time we add a new
/// edge, we have to check all the existing edges.
/// The new structure that inplements neighbor regions such that we only have to
/// check the edges in the neighborhood.
///
/// boxes: the neighborhood we divide the plane into.
/// alive: is a hashmap that has a reference to wich boxes still have space for more point. the
/// tuple is (poly, pos)
/// hmap: given a koordinate gives the index in the boxes vec.
/// limit:
/// num_of_poly: number of polygons to create
pub struct Grid {
pub boxes: Vec<Pointbox>,
pub alive: HashMap<(i32, i32), usize>,
pub hmap: HashMap<(i32,i32), usize>,
pub points: Vec<Vec<Point>>,
capacity: usize,
num_of_poly: usize,
}
impl Grid {
/// Construcktor for Grid
pub fn new(capacity: usize, num_of_poly: usize) -> Self {
Self {
boxes: Vec::new(),
alive: HashMap::new(),
hmap: HashMap::new(),
points: Vec::new(),
capacity: capacity,
num_of_poly: num_of_poly,
}
}
// adds new box to grid, and updates hashmap and alivemap
pub fn push(&mut self, pbox: Pointbox) -> &mut Self {
self.hmap.insert(pbox.pos, self.boxes.len());
self.alive.insert(pbox.pos, self.boxes.len());
self.boxes.push(pbox);
self
}
/// Figures out if a pointbox is alive or never constructed.
fn is_dead(&self, coord: (i32, i32)) -> bool {
match (self.hmap.get(&coord), self.alive.get(&coord)) {
| (Some(_), None) => true,
| _ => false,
}
}
/// lists the alive Pointbox's that also include a point from a given
pub fn alive_and_poly(&self, poly: usize) -> Vec<(i32,i32)> {
self.alive.iter()
.map(|(_, i)| &self.boxes[*i])
.filter(|b| b.contains_elements_of_poly(poly))
.map(|b| b.pos)
.collect::<Vec<_>>()
}
pub fn alive_neighbours(&self, coord: (i32, i32)) -> Vec<(i32, i32)> {
let relative_neighbours = vec![
(0, 0),
(1, 0),
(1, 1),
(0, 1),
(-1, 1),
(-1, 0),
(-1, -1),
(0, -1),
(1, -1),
];
relative_neighbours.into_iter()
.filter(|n| !self.is_dead((n.0 + coord.0, n.1 + coord.1)))
.collect::<Vec<_>>()
}
// note that neighbours include self
fn neighbours(&self, coord: (i32, i32)) -> Vec<&usize> {
let relative_neighbours = vec![
(0, 0),
(1, 0),
(1, 1),
(0, 1),
(-1, 1),
(-1, 0),
(-1, -1),
(0, -1),
(1, -1),
];
relative_neighbours.into_iter()
.filter_map(|n| self.hmap.get(&(&n.0 + coord.0, &n.1 + coord.1)))
.collect::<Vec<&usize>>()
}
fn check_neighbours<F>(&self, coord: (i32, i32), f: F) -> bool where
F: Fn((u8, &(usize, usize))) -> bool {
let edges = self.neighbours(coord).iter()
.cloned()
.flat_map(|i| self.boxes[*i].get_all_edges())
.collect::<Vec<_>>();
if edges.is_empty() {
return true
} else {
// println! ("edges {:?}", edges);
return !edges.iter().any(|u| f(*u))
}
}
/// Checks wether a linesection (newp, oldp) cross's a linesection in the
/// box or its neighbours.
fn does_not_cross (&self, coord: (i32,i32), newp: Point, oldp_index: usize, poly: usize) -> bool {
//println!("self.points: {:?}", self.points);
//println!("oldp_index: {:?}", oldp_index);
self.check_neighbours(coord, |uu| {
//linecross return true if a line crosses
linecross(self.points[uu.0 as usize][uu.1.0],
self.points[uu.0 as usize][uu.1.1],
self.points[poly as usize][oldp_index],
newp)
})
}
/// used to limit amount of points each polygon has in a box
fn is_boxed_filled(&self, pbox_index: &usize, poly: usize) -> bool {
if self.boxes[*pbox_index].points.is_empty() {
true
} else {
self.boxes[*pbox_index].points[poly].len() < self.capacity
}
}
fn add_point (&mut self, newp: Point, oldp_index: usize, pboxes: (usize, usize),
poly: usize) -> &mut Self {
//push newp to points of gird
self.points[poly].push(newp);
//push newp to points of pointbox
self.boxes[pboxes.0].points[poly].push(self.points.len()-1);
//push (oldp, newp) to in_edges of destination pointbox
self.boxes[pboxes.0].in_edges[poly].push((oldp_index, self.points[poly].len()-1));
//push (oldp, newp) to out_edges of from pointbox
self.boxes[pboxes.1].out_edges[poly].push((oldp_index, self.points[poly].len()-1));
if self.boxes[pboxes.0].points[poly].len() == self.capacity {
self.alive.remove(&self.boxes[pboxes.0].pos);
}
self
}
pub fn can_add_point (&mut self, newp: Point, oldp_index: usize, from_pbox: usize, poly: usize) -> bool {
// find witch box newp is in
let coordinates: (i32, i32) =
((newp.x / 100.0).floor() as i32, (newp.y / 100.0).floor() as i32);
//println!("{},{}",coordinates.0, coordinates.1);
match self.hmap.get(&coordinates) {
| None if self.does_not_cross(coordinates, newp, oldp_index, poly) => {
self.push(Pointbox::new(coordinates, self.num_of_poly));
self.add_point(newp, oldp_index, (self.boxes.len() - 1, from_pbox) , poly);
return true;
}
// if pbox with coordniates exist, isnt filed and our new line doesn't cross
| Some(i) if self.does_not_cross(coordinates, newp, oldp_index, poly) => {
let dst_pbox_index = *i;
self.add_point(newp, oldp_index, (dst_pbox_index, from_pbox), poly);
return true;
}
| _ => return false,
// Check line crosses
}
}
/// Cosumes self and converts into the type Polygon
pub fn into_polys(self, polynr: usize) -> Vec<Polygon> {
// Collect all the edges in all the boxes
let mut edges: Vec<Vec<(usize, usize)>> = Vec::new();
let iter_b = self.boxes.into_iter();
iter_b.for_each(|b| b.consume().into_iter().for_each(|e| edges.push(e)));
//format the edges vec such that edges[0] is the edges of poly 0
let ite = edges.into_iter();
let mut p_edges: Vec<Vec<(usize, usize)>> =
(0..polynr).map(|i| {
ite.clone()
.skip(i)
.step_by(polynr)
//.inspect(|x| println!("after skip: {:?}", x))
.fold(vec![], |mut vec, mut x| {
vec.append(&mut x);
vec
})
})
.collect();
//println!("hele p_edges: {:?}", p_edges);
// returns vec of poly.
// obs reverts the order of both points and edges such as poly[0].edges
// equals p_edges.last
let mut points = self.points;
(0..polynr).map(|_i| Polygon {
points: points.pop().unwrap(),
edges: p_edges.pop().unwrap(),})
.collect::<Vec<Polygon>>()
}
}
#[test]
fn grid_into_polys() {
let mut points: Vec<Vec<Point>> = Vec::new();
points.push(vec![
Point { x: 0.0, y: 0.0 },
Point { x: 1.0, y: 1.0 },
Point { x: 2.0, y: 2.0 },
Point { x: 3.0, y: 3.0 },
]);
points.push(vec![
Point { x: 4.0, y: 4.0 },
Point { x: 5.0, y: 5.0 },
Point { x: 6.0, y: 6.0 },
Point { x: 7.0, y: 7.0 },
]);
let mut grid = Grid {
boxes: Vec::new(),
alive: HashMap::new(),
hmap: HashMap::new(),
points: points,
capacity: 3,
num_of_poly: 2,
};
let mut a = Pointbox::new((0, 0), 2);
a.in_edges.append(&mut vec![
vec![(0, 1), (0, 2), (1, 3)],
vec![(1, 1), (1, 2), (1, 3)],
]);
let mut b = Pointbox::new((1, 1), 2);
b.in_edges.append(&mut vec![
vec![(2, 1), (2, 2), (2, 3)],
vec![(3, 1), (3, 2), (0, 3)],
]);
grid.push(a);
grid.push(b);
let polys = grid.into_polys(2);
assert_eq!(polys.len(), 2);
//since
assert_eq!(
polys[1].edges,
vec![(0, 1), (0, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
);
assert_eq!(polys[0].points.len(), 4);
}
#[test]
fn grid_can_cross() {
let mut points: Vec<Vec<Point>> = Vec::new();
let mut grid = Grid::new(4, 2);
grid.push(Pointbox::new((0,0), 2));
grid.points.push(vec![Point {x: 1.0, y: 99.0}]);
grid.points.push(vec![Point {x: 1.0, y: 1.0}]);
grid.boxes[0].points[0].push(0);
grid.boxes[0].points[1].push(0);
assert_eq!(true, grid.does_not_cross((0,1), Point{x: 101.0, y: 1.0}, 0, 0));
assert!(grid.can_add_point (Point{x: 101.0, y: 1.0}, 0, 0, 0));
assert_eq!(2, grid.boxes.len());
println! ("neighbours of (0,1) {:?}", grid.neighbours((0,1)));
assert!(linecross(grid.points[0][0], grid.points[0][1],
grid.points[1][0], Point{x: 101.0, y: 99.0}));
assert_eq!(false, grid.does_not_cross((0,1), Point{x: 101.0, y: 99.0}, 0, 1));
assert!(!grid.can_add_point (Point{x: 101.0, y: 99.0}, 0, 0, 1));
assert!(grid.can_add_point (Point{x: 1.0, y: -99.0}, 0, 0, 1));
println! ("neighbours of (0,1) {:?}", grid.neighbours((0,0)));
}
/// Not needed because of hashmap. keeping it in here maybe i am wrong an will need it
///
///
///
/// This is from https://math.stackexchange.com/questions/163080/on-a-two-dimensional-grid-is-there-a-formula-i-can-use-to-spiral-coordinates-in
/// It maps the natural numbers to Z x Z in a spiral pattern.
/// And i didn't do a very nice job of porting it to rust
fn spiral(n: usize) -> (i32, i32) {
let k = (((n as f64).sqrt() - 1.0) / 2.0).ceil() as i32;
let mut t = 2 * k + 1;
let mut m = t.pow(2);
t = t - 1;
let mut done = false;
let mut res: (i32, i32) = (0, 0);
if n as i32 >= m - t {
res = (k - (m - n as i32), -k);
done = true;
} else {
m = m - t;
}
if n as i32 >= m - t && !done {
res = (-k as i32, (-k as i32) + (m - n as i32));
done = true;
} else {
m = m - t;
}
if n as i32 >= m - t && !done {
res = ((-k) + (m - n as i32), k);
} else if !done {
res = (k, (k - (m - n as i32 - t)));
}
return res;
}
/// 17--16--15--14--13
/// | |
/// 18 5--4--3 12
/// | | | |
/// 19 6 1--2 11
/// | | |
/// 20 7--8--9--10
/// |
/// 21--22--23--24--25--26
///
/// zxz is the inverse funktion off spiral
/// it uses the that uneven squares are lokalted on 9 is on (1,-1), 25 is on (2,-2), 49 is (3,-3).
/// the same can be said off the even squares the are lokated on 4 is on (0,1), 16 is on (-1,2), 36 is on (-2, 3).
pub fn zxz_to_n(x: i32, y: i32) -> usize {
if (x == 0) && (y == 0) {
1
} else {
let max = if x.abs() >= y.abs() { x } else { y };
match (x == max, max > 0) {
//right column
(true, true) => {
if x == y.abs() && y < 0 {
(2 * max.abs() + 1).pow(2) as usize
} else {
((2 * max.abs() - 1).pow(2) + (max + y)) as usize
}
}
//top row
(false, true) => ((2 * max).pow(2) - (max - 1 + x)) as usize,
//left column
(true, false) => ((2 * max).pow(2) + (max.abs() - y + 1)) as usize,
//bottom row
(false, false) => ((2 * max.abs() + 1).pow(2) + (x - max.abs())) as usize,
}
}
}
#[test]
fn grid_neigbours() {
let mut grid = Grid {
boxes: Vec::new(),
alive: HashMap::new(),
hmap: HashMap::new(),
points: Vec::new(),
capacity: 3,
num_of_poly: 2,
};
grid.push(Pointbox::new((0, 0), 2));
grid.push(Pointbox::new((2, 2), 2));
grid.push(Pointbox::new((-1, 0), 2));
assert_eq!(grid.neighbours((0, 0)), vec![&0, &2]);
}
#[test]
fn grid_add_points() {
let mut grid = Grid {
boxes: Vec::new(),
alive: HashMap::new(),
hmap: HashMap::new(),
points: Vec::new(),
capacity: 3,
num_of_poly: 2,
};
grid.push(Pointbox::new((0, 0), 2));
grid.push(Pointbox::new((2, 2), 2));
grid.push(Pointbox::new((-1, 0), 2));
assert_eq!(grid.neighbours((0, 0)), vec![&0, &2]);
}
/*
#[test]
fn can_add_point_test(){
let mut grid = Grid {
boxes: Vec::new(),
alive: HashMap::new(),
hmap: HashMap::new(),
points: Vec::new(),
capacity: 3,
num_of_poly: 2,
};
}
*/
/// Tests for zxz_to_n and spiral
#[test]
fn top_zxz() {
let fasit: Vec<usize> = vec![3, 4, 5];
let input: Vec<(i32, i32)> = vec![(1, 1), (0, 1), (-1, 1)];
let res: Vec<usize> = input.into_iter().map(|x| zxz_to_n(x.0, x.1)).collect();
assert_eq!(fasit, res);
}
#[test]
fn zxz() {
let input: Vec<(i32, i32)> = vec![
(0, 0),
(1, 0),
(1, 1),
(0, 1),
(-1, 1),
(-1, 0),
(-1, -1),
(0, -1),
(1, -1),
(2, -1),
(2, 0),
(2, 1),
(2, 2),
(1, 2),
(0, 2),
(-1, 2),
(-2, 2),
(-2, 1),
(-2, 0),
(-2, -1),
(-2, -2),
(-1, -2),
(0, -2),
(1, -2),
(2, -2),
];
let res: Vec<usize> = input.into_iter().map(|x| zxz_to_n(x.0, x.1)).collect();
let fasit: Vec<usize> = (1..26).collect();
assert_eq!(fasit, res);
}
#[test]
fn spiral_to_zxz() {
let input: Vec<usize> = (1..10001).collect();
let fasit: Vec<usize> = (1..10001).collect();
let res: Vec<usize> = input
.into_iter()
.map(|x| {
let s = spiral(x);
zxz_to_n(s.0, s.1)
})
.collect();
assert_eq!(fasit, res);
}
|
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(
name = "project-example",
about = "A SpatialOS worker written in Rust."
)]
pub struct Opt {
#[structopt(name = "WORKER_TYPE", long = "worker-type", short = "w")]
pub worker_type: String,
#[structopt(name = "WORKER_ID", long = "worker-id", short = "i")]
pub worker_id: Option<String>,
#[structopt(name = "POLLING_CONNECTION", long = "polling-connection", short = "p")]
pub connect_with_poll: bool,
#[structopt(subcommand)]
pub command: Command,
}
#[derive(Debug, StructOpt)]
pub enum Command {
#[structopt(name = "receptionist")]
Receptionist {
#[structopt(long, short)]
connect_with_external_ip: bool,
#[structopt(long, short)]
host: Option<String>,
#[structopt(long, short)]
port: Option<u16>,
},
#[structopt(name = "locator")]
Locator {
#[structopt(name = "LOCATOR_TOKEN", long = "locator-token", short = "t")]
token: String,
#[structopt(name = "PROJECT_NAME", long = "project-name", short = "n")]
project_name: String,
},
#[structopt(name = "dev-auth")]
DevelopmentAuthentication {
#[structopt(name = "DEV_AUTH_TOKEN", long = "dev-auth-token", short = "t")]
dev_auth_token: String,
},
}
|
use super::abstract_container::AbstractContainer;
use super::arche_type::{ArcheType, ArcheTypeError};
use super::arche_type_hash::ArcheTypeHash;
use super::component::Component;
use super::component_type::ComponentType;
use super::container::Container;
use std::collections::HashMap;
pub trait ComponentTuple: 'static + Sized {
fn arche_type(&self) -> ArcheType;
fn arche_type_hash(&self) -> ArcheTypeHash;
fn add_entity_to(
self,
components: &mut HashMap<ComponentType, Box<dyn AbstractContainer>>,
) -> Result<(), ArcheTypeError>;
}
macro_rules! component_tuple_impls {
(@impl next) => {};
(@impl next $first:ident, $($rest:ident,)*) => {
component_tuple_impls!($($rest,)*);
};
(@impl $components:ident, ) => {
return Ok(());
};
(@impl $components:ident, $first:ident, $($rest:ident,)*) => {
match $components.get_mut(&ComponentType::of::<$first>()) {
Some(container) => {
container
.downcast_mut::<Container<$first>>()
.unwrap()
.insert($first);
}
None => return Err(ArcheTypeError::InvalidComponentType(ComponentType::of::<$first>())),
}
component_tuple_impls!(@impl $components, $($rest,)*);
};
($($components:ident,)*) => {
impl<$($components: Component,)*> ComponentTuple for ($($components,)*) {
fn arche_type(&self) -> ArcheType {
ArcheType::new(vec![$((ComponentType::of::<$components>(), Box::new(|| -> Box<dyn AbstractContainer> { Box::new(Container::<$components>::new()) })), ) *])
}
fn arche_type_hash(&self) -> ArcheTypeHash {
ArcheTypeHash::calc(&[$(&ComponentType::of::<$components>(), ) *])
}
fn add_entity_to(
self,
#[allow(unused_variables)]
components: &mut HashMap<ComponentType, Box<dyn AbstractContainer>>,
) -> Result<(), ArcheTypeError> {
#[allow(non_snake_case)]
let ($($components,)*) = self;
component_tuple_impls!(@impl components, $($components,)*);
}
}
component_tuple_impls!(@impl next $($components,)*);
};
() => {};
}
component_tuple_impls!(
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31,
);
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Clock Calibration Unit Core Release Register"]
pub crel: CREL,
#[doc = "0x04 - Calibration Configuration Register"]
pub ccfg: CCFG,
#[doc = "0x08 - Calibration Status Register"]
pub cstat: CSTAT,
#[doc = "0x0c - Calibration Watchdog Register"]
pub cwd: CWD,
#[doc = "0x10 - Clock Calibration Unit Interrupt Register"]
pub ir: IR,
#[doc = "0x14 - Clock Calibration Unit Interrupt Enable Register"]
pub ie: IE,
}
#[doc = "Clock Calibration Unit Core Release Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [crel](crel) module"]
pub type CREL = crate::Reg<u32, _CREL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CREL;
#[doc = "`read()` method returns [crel::R](crel::R) reader structure"]
impl crate::Readable for CREL {}
#[doc = "`write(|w| ..)` method takes [crel::W](crel::W) writer structure"]
impl crate::Writable for CREL {}
#[doc = "Clock Calibration Unit Core Release Register"]
pub mod crel;
#[doc = "Calibration Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ccfg](ccfg) module"]
pub type CCFG = crate::Reg<u32, _CCFG>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CCFG;
#[doc = "`read()` method returns [ccfg::R](ccfg::R) reader structure"]
impl crate::Readable for CCFG {}
#[doc = "`write(|w| ..)` method takes [ccfg::W](ccfg::W) writer structure"]
impl crate::Writable for CCFG {}
#[doc = "Calibration Configuration Register"]
pub mod ccfg;
#[doc = "Calibration Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cstat](cstat) module"]
pub type CSTAT = crate::Reg<u32, _CSTAT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CSTAT;
#[doc = "`read()` method returns [cstat::R](cstat::R) reader structure"]
impl crate::Readable for CSTAT {}
#[doc = "`write(|w| ..)` method takes [cstat::W](cstat::W) writer structure"]
impl crate::Writable for CSTAT {}
#[doc = "Calibration Status Register"]
pub mod cstat;
#[doc = "Calibration Watchdog Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cwd](cwd) module"]
pub type CWD = crate::Reg<u32, _CWD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CWD;
#[doc = "`read()` method returns [cwd::R](cwd::R) reader structure"]
impl crate::Readable for CWD {}
#[doc = "`write(|w| ..)` method takes [cwd::W](cwd::W) writer structure"]
impl crate::Writable for CWD {}
#[doc = "Calibration Watchdog Register"]
pub mod cwd;
#[doc = "Clock Calibration Unit Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ir](ir) module"]
pub type IR = crate::Reg<u32, _IR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IR;
#[doc = "`read()` method returns [ir::R](ir::R) reader structure"]
impl crate::Readable for IR {}
#[doc = "`write(|w| ..)` method takes [ir::W](ir::W) writer structure"]
impl crate::Writable for IR {}
#[doc = "Clock Calibration Unit Interrupt Register"]
pub mod ir;
#[doc = "Clock Calibration Unit Interrupt Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ie](ie) module"]
pub type IE = crate::Reg<u32, _IE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IE;
#[doc = "`read()` method returns [ie::R](ie::R) reader structure"]
impl crate::Readable for IE {}
#[doc = "`write(|w| ..)` method takes [ie::W](ie::W) writer structure"]
impl crate::Writable for IE {}
#[doc = "Clock Calibration Unit Interrupt Enable Register"]
pub mod ie;
|
// 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.
// pretty-expanded FIXME #23616
// Test that `Fn(isize) -> isize + 'static` parses as `(Fn(isize) -> isize) +
// 'static` and not `Fn(isize) -> (isize + 'static)`. The latter would
// cause a compilation error. Issue #18772.
fn adder(y: isize) -> Box<Fn(isize) -> isize + 'static> {
Box::new(move |x| y + x)
}
fn main() {}
|
use super::*;
use std::collections::HashMap;
use std::cmp::max;
use dungeon::generator::Evaluate;
use std::iter::FromIterator;
use item::Equipment;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Monster {
life: i32,
damage: i32,
name: String,
/// Designer defined difficulty
difficulty: Option<usize>,
keywords: Vec<Keyword>,
}
/// Template monsters represent themed variants of monsters. Template monsters
/// are converted to normal Monsters before instantiation in game world.
#[derive(Serialize, Deserialize)]
pub struct TemplateMonster {
template: Monster,
variants: HashMap<Keyword, Variant>,
}
pub type Variant = Vec<Variable>;
impl TemplateMonster {
pub fn new(template: Monster, variants: HashMap<Keyword, Variant>) -> TemplateMonster {
TemplateMonster {
template: template,
variants: variants,
}
}
}
/// Changing properties for a monster of a certain theme
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum Variable {
}
pub struct MonsterBuilder {
monster: Monster,
}
impl MonsterBuilder {
// Only required elements can go here
pub fn new(name: &str, damage: i32, life: i32) -> Self {
MonsterBuilder {
monster: Monster {
name: name.to_string(),
damage: damage,
life: life,
difficulty: None,
keywords: vec![],
},
}
}
pub fn difficulty(mut self, d: usize) -> Self {
self.monster.difficulty = Some(d);
self
}
pub fn keywords(mut self, keywords: &[&str]) -> Self {
let keywords: Vec<Keyword> = keywords
.iter()
.map(|x| Keyword { id: x.to_string() })
.collect();
self.monster.keywords.extend(keywords);
self
}
pub fn keyword(mut self, keyword: &str) -> Self {
self.monster.keywords.push(Keyword {
id: keyword.to_string(),
});
self
}
// TODO: from template
// Spawn a copy of the generated monster
pub fn spawn(&self) -> Monster {
self.monster.clone()
}
}
lazy_static! {
static ref DEFAULT_MONSTER_WEAPON: Equipment = equipment("fist", 1, Slot::Hand, vec![]).build();
}
impl Combatant for Monster {
fn best_weapon(&self) -> &Equipment {
&DEFAULT_MONSTER_WEAPON
}
fn damage(&self) -> i32 {
self.damage
}
fn action_buffer(&self) -> ActionBuffer {
ActionBuffer::default()
}
fn set_life(&mut self, amount: i32) -> i32 {
self.life = max(amount, 0);
self.life
}
fn life(&self) -> i32 {
self.life
}
fn can_combat(&self) -> bool {
self.life > 0
}
}
impl Display for Monster {
fn name(&self) -> String {
self.name.clone()
}
}
impl<'a> Evaluate for Monster {
fn theme(&self) -> &[Keyword] {
self.keywords.as_slice()
}
fn difficulty(&self) -> usize {
self.difficulty.expect(&format!(
"monsters without difficulty may not be included in a dungeon: {}",
&self.name
))
}
}
impl AsRef<Monster> for Monster {
fn as_ref(&self) -> &Self {
self
}
}
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Z identify_regions -Z emit-end-regions
// ignore-tidy-linelength
// Binding the borrow's subject outside the loop does not increase the
// scope of the borrow.
fn main() {
let mut a;
loop {
a = true;
let b = &a;
if a { break; }
let c = &a;
}
}
// END RUST SOURCE
// START rustc.main.SimplifyCfg-qualify-consts.after.mir
// let mut _0: ();
// ...
// let _7: &'26_3rs bool;
// ...
// let _3: &'26_1rs bool;
// ...
// let mut _1: bool;
// ...
// let mut _2: ();
// let mut _4: ();
// let mut _5: bool;
// let mut _6: !;
// bb0: {
// StorageLive(_1);
// goto -> bb1;
// }
// bb1: {
// falseUnwind -> [real: bb2, cleanup: bb3];
// }
// bb2: {
// _1 = const true;
// StorageLive(_3);
// _3 = &'26_1rs _1;
// StorageLive(_5);
// _5 = _1;
// switchInt(move _5) -> [false: bb5, otherwise: bb4];
// }
// bb3: {
// ...
// }
// bb4: {
// _0 = ();
// StorageDead(_5);
// EndRegion('26_1rs);
// StorageDead(_3);
// StorageDead(_1);
// return;
// }
// bb5: {
// _4 = ();
// StorageDead(_5);
// StorageLive(_7);
// _7 = &'26_3rs _1;
// _2 = ();
// EndRegion('26_3rs);
// StorageDead(_7);
// EndRegion('26_1rs);
// StorageDead(_3);
// goto -> bb1;
// }
// END rustc.main.SimplifyCfg-qualify-consts.after.mir
|
/// Minter represents the minting state.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Minter {
/// current annual inflation rate
#[prost(string, tag = "1")]
pub inflation: std::string::String,
/// current annual expected provisions
#[prost(string, tag = "2")]
pub annual_provisions: std::string::String,
}
/// Params holds parameters for the mint module.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Params {
/// type of coin to mint
#[prost(string, tag = "1")]
pub mint_denom: std::string::String,
/// maximum annual change in inflation rate
#[prost(string, tag = "2")]
pub inflation_rate_change: std::string::String,
/// maximum inflation rate
#[prost(string, tag = "3")]
pub inflation_max: std::string::String,
/// minimum inflation rate
#[prost(string, tag = "4")]
pub inflation_min: std::string::String,
/// goal of percent bonded atoms
#[prost(string, tag = "5")]
pub goal_bonded: std::string::String,
/// expected blocks per year
#[prost(uint64, tag = "6")]
pub blocks_per_year: u64,
}
/// GenesisState defines the mint module's genesis state.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GenesisState {
/// minter is a space for holding current inflation information.
#[prost(message, optional, tag = "1")]
pub minter: ::std::option::Option<Minter>,
/// params defines all the paramaters of the module.
#[prost(message, optional, tag = "2")]
pub params: ::std::option::Option<Params>,
}
/// QueryParamsRequest is the request type for the Query/Params RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryParamsRequest {}
/// QueryParamsResponse is the response type for the Query/Params RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryParamsResponse {
/// params defines the parameters of the module.
#[prost(message, optional, tag = "1")]
pub params: ::std::option::Option<Params>,
}
/// QueryInflationRequest is the request type for the Query/Inflation RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryInflationRequest {}
/// QueryInflationResponse is the response type for the Query/Inflation RPC
/// method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryInflationResponse {
/// inflation is the current minting inflation value.
#[prost(bytes, tag = "1")]
pub inflation: std::vec::Vec<u8>,
}
/// QueryAnnualProvisionsRequest is the request type for the
/// Query/AnnualProvisions RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryAnnualProvisionsRequest {}
/// QueryAnnualProvisionsResponse is the response type for the
/// Query/AnnualProvisions RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryAnnualProvisionsResponse {
/// annual_provisions is the current minting annual provisions value.
#[prost(bytes, tag = "1")]
pub annual_provisions: std::vec::Vec<u8>,
}
#[doc = r" Generated client implementations."]
pub mod query_client {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = " Query provides defines the gRPC querier service."]
pub struct QueryClient<T> {
inner: tonic::client::Grpc<T>,
}
impl QueryClient<tonic::transport::Channel> {
#[doc = r" Attempt to create a new client by connecting to a given endpoint."]
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
where
D: std::convert::TryInto<tonic::transport::Endpoint>,
D::Error: Into<StdError>,
{
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
Ok(Self::new(conn))
}
}
impl<T> QueryClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::ResponseBody: Body + HttpBody + Send + 'static,
T::Error: Into<StdError>,
<T::ResponseBody as HttpBody>::Error: Into<StdError> + Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = tonic::client::Grpc::with_interceptor(inner, interceptor);
Self { inner }
}
#[doc = " Params returns the total set of minting parameters."]
pub async fn params(
&mut self,
request: impl tonic::IntoRequest<super::QueryParamsRequest>,
) -> Result<tonic::Response<super::QueryParamsResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static("/cosmos.mint.v1beta1.Query/Params");
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Inflation returns the current minting inflation value."]
pub async fn inflation(
&mut self,
request: impl tonic::IntoRequest<super::QueryInflationRequest>,
) -> Result<tonic::Response<super::QueryInflationResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static("/cosmos.mint.v1beta1.Query/Inflation");
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " AnnualProvisions current minting annual provisions value."]
pub async fn annual_provisions(
&mut self,
request: impl tonic::IntoRequest<super::QueryAnnualProvisionsRequest>,
) -> Result<tonic::Response<super::QueryAnnualProvisionsResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path =
http::uri::PathAndQuery::from_static("/cosmos.mint.v1beta1.Query/AnnualProvisions");
self.inner.unary(request.into_request(), path, codec).await
}
}
impl<T: Clone> Clone for QueryClient<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> std::fmt::Debug for QueryClient<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "QueryClient {{ ... }}")
}
}
}
#[doc = r" Generated server implementations."]
pub mod query_server {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = "Generated trait containing gRPC methods that should be implemented for use with QueryServer."]
#[async_trait]
pub trait Query: Send + Sync + 'static {
#[doc = " Params returns the total set of minting parameters."]
async fn params(
&self,
request: tonic::Request<super::QueryParamsRequest>,
) -> Result<tonic::Response<super::QueryParamsResponse>, tonic::Status>;
#[doc = " Inflation returns the current minting inflation value."]
async fn inflation(
&self,
request: tonic::Request<super::QueryInflationRequest>,
) -> Result<tonic::Response<super::QueryInflationResponse>, tonic::Status>;
#[doc = " AnnualProvisions current minting annual provisions value."]
async fn annual_provisions(
&self,
request: tonic::Request<super::QueryAnnualProvisionsRequest>,
) -> Result<tonic::Response<super::QueryAnnualProvisionsResponse>, tonic::Status>;
}
#[doc = " Query provides defines the gRPC querier service."]
#[derive(Debug)]
pub struct QueryServer<T: Query> {
inner: _Inner<T>,
}
struct _Inner<T>(Arc<T>, Option<tonic::Interceptor>);
impl<T: Query> QueryServer<T> {
pub fn new(inner: T) -> Self {
let inner = Arc::new(inner);
let inner = _Inner(inner, None);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = Arc::new(inner);
let inner = _Inner(inner, Some(interceptor.into()));
Self { inner }
}
}
impl<T, B> Service<http::Request<B>> for QueryServer<T>
where
T: Query,
B: HttpBody + Send + Sync + 'static,
B::Error: Into<StdError> + Send + 'static,
{
type Response = http::Response<tonic::body::BoxBody>;
type Error = Never;
type Future = BoxFuture<Self::Response, Self::Error>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: http::Request<B>) -> Self::Future {
let inner = self.inner.clone();
match req.uri().path() {
"/cosmos.mint.v1beta1.Query/Params" => {
#[allow(non_camel_case_types)]
struct ParamsSvc<T: Query>(pub Arc<T>);
impl<T: Query> tonic::server::UnaryService<super::QueryParamsRequest> for ParamsSvc<T> {
type Response = super::QueryParamsResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryParamsRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).params(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = ParamsSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.mint.v1beta1.Query/Inflation" => {
#[allow(non_camel_case_types)]
struct InflationSvc<T: Query>(pub Arc<T>);
impl<T: Query> tonic::server::UnaryService<super::QueryInflationRequest> for InflationSvc<T> {
type Response = super::QueryInflationResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryInflationRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).inflation(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = InflationSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.mint.v1beta1.Query/AnnualProvisions" => {
#[allow(non_camel_case_types)]
struct AnnualProvisionsSvc<T: Query>(pub Arc<T>);
impl<T: Query> tonic::server::UnaryService<super::QueryAnnualProvisionsRequest>
for AnnualProvisionsSvc<T>
{
type Response = super::QueryAnnualProvisionsResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryAnnualProvisionsRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).annual_provisions(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = AnnualProvisionsSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
_ => Box::pin(async move {
Ok(http::Response::builder()
.status(200)
.header("grpc-status", "12")
.body(tonic::body::BoxBody::empty())
.unwrap())
}),
}
}
}
impl<T: Query> Clone for QueryServer<T> {
fn clone(&self) -> Self {
let inner = self.inner.clone();
Self { inner }
}
}
impl<T: Query> Clone for _Inner<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for _Inner<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl<T: Query> tonic::transport::NamedService for QueryServer<T> {
const NAME: &'static str = "cosmos.mint.v1beta1.Query";
}
}
|
use bytes::{Buf, Bytes};
use crate::error::Error;
#[derive(Debug)]
pub(crate) struct Order {
#[allow(dead_code)]
columns: Bytes,
}
impl Order {
pub(crate) fn get(buf: &mut Bytes) -> Result<Self, Error> {
let len = buf.get_u16_le();
let columns = buf.split_to(len as usize);
Ok(Self { columns })
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::TBMR {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = "Possible values of the field `TIMER_TBMR_TBMR`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIMER_TBMR_TBMRR {
#[doc = "One-Shot Timer mode"]
TIMER_TBMR_TBMR_1_SHOT,
#[doc = "Periodic Timer mode"]
TIMER_TBMR_TBMR_PERIOD,
#[doc = "Capture mode"]
TIMER_TBMR_TBMR_CAP,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl TIMER_TBMR_TBMRR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
TIMER_TBMR_TBMRR::TIMER_TBMR_TBMR_1_SHOT => 1,
TIMER_TBMR_TBMRR::TIMER_TBMR_TBMR_PERIOD => 2,
TIMER_TBMR_TBMRR::TIMER_TBMR_TBMR_CAP => 3,
TIMER_TBMR_TBMRR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> TIMER_TBMR_TBMRR {
match value {
1 => TIMER_TBMR_TBMRR::TIMER_TBMR_TBMR_1_SHOT,
2 => TIMER_TBMR_TBMRR::TIMER_TBMR_TBMR_PERIOD,
3 => TIMER_TBMR_TBMRR::TIMER_TBMR_TBMR_CAP,
i => TIMER_TBMR_TBMRR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TBMR_1_SHOT`"]
#[inline(always)]
pub fn is_timer_tbmr_tbmr_1_shot(&self) -> bool {
*self == TIMER_TBMR_TBMRR::TIMER_TBMR_TBMR_1_SHOT
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TBMR_PERIOD`"]
#[inline(always)]
pub fn is_timer_tbmr_tbmr_period(&self) -> bool {
*self == TIMER_TBMR_TBMRR::TIMER_TBMR_TBMR_PERIOD
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TBMR_CAP`"]
#[inline(always)]
pub fn is_timer_tbmr_tbmr_cap(&self) -> bool {
*self == TIMER_TBMR_TBMRR::TIMER_TBMR_TBMR_CAP
}
}
#[doc = "Values that can be written to the field `TIMER_TBMR_TBMR`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIMER_TBMR_TBMRW {
#[doc = "One-Shot Timer mode"]
TIMER_TBMR_TBMR_1_SHOT,
#[doc = "Periodic Timer mode"]
TIMER_TBMR_TBMR_PERIOD,
#[doc = "Capture mode"]
TIMER_TBMR_TBMR_CAP,
}
impl TIMER_TBMR_TBMRW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
TIMER_TBMR_TBMRW::TIMER_TBMR_TBMR_1_SHOT => 1,
TIMER_TBMR_TBMRW::TIMER_TBMR_TBMR_PERIOD => 2,
TIMER_TBMR_TBMRW::TIMER_TBMR_TBMR_CAP => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBMRW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBMRW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIMER_TBMR_TBMRW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "One-Shot Timer mode"]
#[inline(always)]
pub fn timer_tbmr_tbmr_1_shot(self) -> &'a mut W {
self.variant(TIMER_TBMR_TBMRW::TIMER_TBMR_TBMR_1_SHOT)
}
#[doc = "Periodic Timer mode"]
#[inline(always)]
pub fn timer_tbmr_tbmr_period(self) -> &'a mut W {
self.variant(TIMER_TBMR_TBMRW::TIMER_TBMR_TBMR_PERIOD)
}
#[doc = "Capture mode"]
#[inline(always)]
pub fn timer_tbmr_tbmr_cap(self) -> &'a mut W {
self.variant(TIMER_TBMR_TBMRW::TIMER_TBMR_TBMR_CAP)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 0);
self.w.bits |= ((value as u32) & 3) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBCMRR {
bits: bool,
}
impl TIMER_TBMR_TBCMRR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBCMRW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBCMRW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBAMSR {
bits: bool,
}
impl TIMER_TBMR_TBAMSR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBAMSW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBAMSW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBCDIRR {
bits: bool,
}
impl TIMER_TBMR_TBCDIRR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBCDIRW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBCDIRW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 4);
self.w.bits |= ((value as u32) & 1) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBMIER {
bits: bool,
}
impl TIMER_TBMR_TBMIER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBMIEW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBMIEW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 5);
self.w.bits |= ((value as u32) & 1) << 5;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBWOTR {
bits: bool,
}
impl TIMER_TBMR_TBWOTR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBWOTW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBWOTW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 6);
self.w.bits |= ((value as u32) & 1) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBSNAPSR {
bits: bool,
}
impl TIMER_TBMR_TBSNAPSR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBSNAPSW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBSNAPSW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 7);
self.w.bits |= ((value as u32) & 1) << 7;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBILDR {
bits: bool,
}
impl TIMER_TBMR_TBILDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBILDW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBILDW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 8);
self.w.bits |= ((value as u32) & 1) << 8;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBPWMIER {
bits: bool,
}
impl TIMER_TBMR_TBPWMIER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBPWMIEW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBPWMIEW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 9);
self.w.bits |= ((value as u32) & 1) << 9;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBMRSUR {
bits: bool,
}
impl TIMER_TBMR_TBMRSUR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBMRSUW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBMRSUW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 10);
self.w.bits |= ((value as u32) & 1) << 10;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBPLOR {
bits: bool,
}
impl TIMER_TBMR_TBPLOR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBPLOW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBPLOW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 11);
self.w.bits |= ((value as u32) & 1) << 11;
self.w
}
}
#[doc = r"Value of the field"]
pub struct TIMER_TBMR_TBCINTDR {
bits: bool,
}
impl TIMER_TBMR_TBCINTDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TBCINTDW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TBCINTDW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 12);
self.w.bits |= ((value as u32) & 1) << 12;
self.w
}
}
#[doc = "Possible values of the field `TIMER_TBMR_TCACT`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIMER_TBMR_TCACTR {
#[doc = "Disable compare operations"]
TIMER_TBMR_TCACT_NONE,
#[doc = "Toggle State on Time-Out"]
TIMER_TBMR_TCACT_TOGGLE,
#[doc = "Clear CCP on Time-Out"]
TIMER_TBMR_TCACT_CLRTO,
#[doc = "Set CCP on Time-Out"]
TIMER_TBMR_TCACT_SETTO,
#[doc = "Set CCP immediately and toggle on Time-Out"]
TIMER_TBMR_TCACT_SETTOGTO,
#[doc = "Clear CCP immediately and toggle on Time-Out"]
TIMER_TBMR_TCACT_CLRTOGTO,
#[doc = "Set CCP immediately and clear on Time-Out"]
TIMER_TBMR_TCACT_SETCLRTO,
#[doc = "Clear CCP immediately and set on Time-Out"]
TIMER_TBMR_TCACT_CLRSETTO,
}
impl TIMER_TBMR_TCACTR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_NONE => 0,
TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_TOGGLE => 1,
TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_CLRTO => 2,
TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_SETTO => 3,
TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_SETTOGTO => 4,
TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_CLRTOGTO => 5,
TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_SETCLRTO => 6,
TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_CLRSETTO => 7,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> TIMER_TBMR_TCACTR {
match value {
0 => TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_NONE,
1 => TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_TOGGLE,
2 => TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_CLRTO,
3 => TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_SETTO,
4 => TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_SETTOGTO,
5 => TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_CLRTOGTO,
6 => TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_SETCLRTO,
7 => TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_CLRSETTO,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TCACT_NONE`"]
#[inline(always)]
pub fn is_timer_tbmr_tcact_none(&self) -> bool {
*self == TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_NONE
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TCACT_TOGGLE`"]
#[inline(always)]
pub fn is_timer_tbmr_tcact_toggle(&self) -> bool {
*self == TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_TOGGLE
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TCACT_CLRTO`"]
#[inline(always)]
pub fn is_timer_tbmr_tcact_clrto(&self) -> bool {
*self == TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_CLRTO
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TCACT_SETTO`"]
#[inline(always)]
pub fn is_timer_tbmr_tcact_setto(&self) -> bool {
*self == TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_SETTO
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TCACT_SETTOGTO`"]
#[inline(always)]
pub fn is_timer_tbmr_tcact_settogto(&self) -> bool {
*self == TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_SETTOGTO
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TCACT_CLRTOGTO`"]
#[inline(always)]
pub fn is_timer_tbmr_tcact_clrtogto(&self) -> bool {
*self == TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_CLRTOGTO
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TCACT_SETCLRTO`"]
#[inline(always)]
pub fn is_timer_tbmr_tcact_setclrto(&self) -> bool {
*self == TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_SETCLRTO
}
#[doc = "Checks if the value of the field is `TIMER_TBMR_TCACT_CLRSETTO`"]
#[inline(always)]
pub fn is_timer_tbmr_tcact_clrsetto(&self) -> bool {
*self == TIMER_TBMR_TCACTR::TIMER_TBMR_TCACT_CLRSETTO
}
}
#[doc = "Values that can be written to the field `TIMER_TBMR_TCACT`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIMER_TBMR_TCACTW {
#[doc = "Disable compare operations"]
TIMER_TBMR_TCACT_NONE,
#[doc = "Toggle State on Time-Out"]
TIMER_TBMR_TCACT_TOGGLE,
#[doc = "Clear CCP on Time-Out"]
TIMER_TBMR_TCACT_CLRTO,
#[doc = "Set CCP on Time-Out"]
TIMER_TBMR_TCACT_SETTO,
#[doc = "Set CCP immediately and toggle on Time-Out"]
TIMER_TBMR_TCACT_SETTOGTO,
#[doc = "Clear CCP immediately and toggle on Time-Out"]
TIMER_TBMR_TCACT_CLRTOGTO,
#[doc = "Set CCP immediately and clear on Time-Out"]
TIMER_TBMR_TCACT_SETCLRTO,
#[doc = "Clear CCP immediately and set on Time-Out"]
TIMER_TBMR_TCACT_CLRSETTO,
}
impl TIMER_TBMR_TCACTW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_NONE => 0,
TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_TOGGLE => 1,
TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_CLRTO => 2,
TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_SETTO => 3,
TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_SETTOGTO => 4,
TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_CLRTOGTO => 5,
TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_SETCLRTO => 6,
TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_CLRSETTO => 7,
}
}
}
#[doc = r"Proxy"]
pub struct _TIMER_TBMR_TCACTW<'a> {
w: &'a mut W,
}
impl<'a> _TIMER_TBMR_TCACTW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIMER_TBMR_TCACTW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Disable compare operations"]
#[inline(always)]
pub fn timer_tbmr_tcact_none(self) -> &'a mut W {
self.variant(TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_NONE)
}
#[doc = "Toggle State on Time-Out"]
#[inline(always)]
pub fn timer_tbmr_tcact_toggle(self) -> &'a mut W {
self.variant(TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_TOGGLE)
}
#[doc = "Clear CCP on Time-Out"]
#[inline(always)]
pub fn timer_tbmr_tcact_clrto(self) -> &'a mut W {
self.variant(TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_CLRTO)
}
#[doc = "Set CCP on Time-Out"]
#[inline(always)]
pub fn timer_tbmr_tcact_setto(self) -> &'a mut W {
self.variant(TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_SETTO)
}
#[doc = "Set CCP immediately and toggle on Time-Out"]
#[inline(always)]
pub fn timer_tbmr_tcact_settogto(self) -> &'a mut W {
self.variant(TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_SETTOGTO)
}
#[doc = "Clear CCP immediately and toggle on Time-Out"]
#[inline(always)]
pub fn timer_tbmr_tcact_clrtogto(self) -> &'a mut W {
self.variant(TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_CLRTOGTO)
}
#[doc = "Set CCP immediately and clear on Time-Out"]
#[inline(always)]
pub fn timer_tbmr_tcact_setclrto(self) -> &'a mut W {
self.variant(TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_SETCLRTO)
}
#[doc = "Clear CCP immediately and set on Time-Out"]
#[inline(always)]
pub fn timer_tbmr_tcact_clrsetto(self) -> &'a mut W {
self.variant(TIMER_TBMR_TCACTW::TIMER_TBMR_TCACT_CLRSETTO)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(7 << 13);
self.w.bits |= ((value as u32) & 7) << 13;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:1 - GPTM Timer B Mode"]
#[inline(always)]
pub fn timer_tbmr_tbmr(&self) -> TIMER_TBMR_TBMRR {
TIMER_TBMR_TBMRR::_from(((self.bits >> 0) & 3) as u8)
}
#[doc = "Bit 2 - GPTM Timer B Capture Mode"]
#[inline(always)]
pub fn timer_tbmr_tbcmr(&self) -> TIMER_TBMR_TBCMRR {
let bits = ((self.bits >> 2) & 1) != 0;
TIMER_TBMR_TBCMRR { bits }
}
#[doc = "Bit 3 - GPTM Timer B Alternate Mode Select"]
#[inline(always)]
pub fn timer_tbmr_tbams(&self) -> TIMER_TBMR_TBAMSR {
let bits = ((self.bits >> 3) & 1) != 0;
TIMER_TBMR_TBAMSR { bits }
}
#[doc = "Bit 4 - GPTM Timer B Count Direction"]
#[inline(always)]
pub fn timer_tbmr_tbcdir(&self) -> TIMER_TBMR_TBCDIRR {
let bits = ((self.bits >> 4) & 1) != 0;
TIMER_TBMR_TBCDIRR { bits }
}
#[doc = "Bit 5 - GPTM Timer B Match Interrupt Enable"]
#[inline(always)]
pub fn timer_tbmr_tbmie(&self) -> TIMER_TBMR_TBMIER {
let bits = ((self.bits >> 5) & 1) != 0;
TIMER_TBMR_TBMIER { bits }
}
#[doc = "Bit 6 - GPTM Timer B Wait-on-Trigger"]
#[inline(always)]
pub fn timer_tbmr_tbwot(&self) -> TIMER_TBMR_TBWOTR {
let bits = ((self.bits >> 6) & 1) != 0;
TIMER_TBMR_TBWOTR { bits }
}
#[doc = "Bit 7 - GPTM Timer B Snap-Shot Mode"]
#[inline(always)]
pub fn timer_tbmr_tbsnaps(&self) -> TIMER_TBMR_TBSNAPSR {
let bits = ((self.bits >> 7) & 1) != 0;
TIMER_TBMR_TBSNAPSR { bits }
}
#[doc = "Bit 8 - GPTM Timer B Interval Load Write"]
#[inline(always)]
pub fn timer_tbmr_tbild(&self) -> TIMER_TBMR_TBILDR {
let bits = ((self.bits >> 8) & 1) != 0;
TIMER_TBMR_TBILDR { bits }
}
#[doc = "Bit 9 - GPTM Timer B PWM Interrupt Enable"]
#[inline(always)]
pub fn timer_tbmr_tbpwmie(&self) -> TIMER_TBMR_TBPWMIER {
let bits = ((self.bits >> 9) & 1) != 0;
TIMER_TBMR_TBPWMIER { bits }
}
#[doc = "Bit 10 - GPTM Timer B Match Register Update"]
#[inline(always)]
pub fn timer_tbmr_tbmrsu(&self) -> TIMER_TBMR_TBMRSUR {
let bits = ((self.bits >> 10) & 1) != 0;
TIMER_TBMR_TBMRSUR { bits }
}
#[doc = "Bit 11 - GPTM Timer B PWM Legacy Operation"]
#[inline(always)]
pub fn timer_tbmr_tbplo(&self) -> TIMER_TBMR_TBPLOR {
let bits = ((self.bits >> 11) & 1) != 0;
TIMER_TBMR_TBPLOR { bits }
}
#[doc = "Bit 12 - One-Shot/Periodic Interrupt Disable"]
#[inline(always)]
pub fn timer_tbmr_tbcintd(&self) -> TIMER_TBMR_TBCINTDR {
let bits = ((self.bits >> 12) & 1) != 0;
TIMER_TBMR_TBCINTDR { bits }
}
#[doc = "Bits 13:15 - Timer Compare Action Select"]
#[inline(always)]
pub fn timer_tbmr_tcact(&self) -> TIMER_TBMR_TCACTR {
TIMER_TBMR_TCACTR::_from(((self.bits >> 13) & 7) as u8)
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - GPTM Timer B Mode"]
#[inline(always)]
pub fn timer_tbmr_tbmr(&mut self) -> _TIMER_TBMR_TBMRW {
_TIMER_TBMR_TBMRW { w: self }
}
#[doc = "Bit 2 - GPTM Timer B Capture Mode"]
#[inline(always)]
pub fn timer_tbmr_tbcmr(&mut self) -> _TIMER_TBMR_TBCMRW {
_TIMER_TBMR_TBCMRW { w: self }
}
#[doc = "Bit 3 - GPTM Timer B Alternate Mode Select"]
#[inline(always)]
pub fn timer_tbmr_tbams(&mut self) -> _TIMER_TBMR_TBAMSW {
_TIMER_TBMR_TBAMSW { w: self }
}
#[doc = "Bit 4 - GPTM Timer B Count Direction"]
#[inline(always)]
pub fn timer_tbmr_tbcdir(&mut self) -> _TIMER_TBMR_TBCDIRW {
_TIMER_TBMR_TBCDIRW { w: self }
}
#[doc = "Bit 5 - GPTM Timer B Match Interrupt Enable"]
#[inline(always)]
pub fn timer_tbmr_tbmie(&mut self) -> _TIMER_TBMR_TBMIEW {
_TIMER_TBMR_TBMIEW { w: self }
}
#[doc = "Bit 6 - GPTM Timer B Wait-on-Trigger"]
#[inline(always)]
pub fn timer_tbmr_tbwot(&mut self) -> _TIMER_TBMR_TBWOTW {
_TIMER_TBMR_TBWOTW { w: self }
}
#[doc = "Bit 7 - GPTM Timer B Snap-Shot Mode"]
#[inline(always)]
pub fn timer_tbmr_tbsnaps(&mut self) -> _TIMER_TBMR_TBSNAPSW {
_TIMER_TBMR_TBSNAPSW { w: self }
}
#[doc = "Bit 8 - GPTM Timer B Interval Load Write"]
#[inline(always)]
pub fn timer_tbmr_tbild(&mut self) -> _TIMER_TBMR_TBILDW {
_TIMER_TBMR_TBILDW { w: self }
}
#[doc = "Bit 9 - GPTM Timer B PWM Interrupt Enable"]
#[inline(always)]
pub fn timer_tbmr_tbpwmie(&mut self) -> _TIMER_TBMR_TBPWMIEW {
_TIMER_TBMR_TBPWMIEW { w: self }
}
#[doc = "Bit 10 - GPTM Timer B Match Register Update"]
#[inline(always)]
pub fn timer_tbmr_tbmrsu(&mut self) -> _TIMER_TBMR_TBMRSUW {
_TIMER_TBMR_TBMRSUW { w: self }
}
#[doc = "Bit 11 - GPTM Timer B PWM Legacy Operation"]
#[inline(always)]
pub fn timer_tbmr_tbplo(&mut self) -> _TIMER_TBMR_TBPLOW {
_TIMER_TBMR_TBPLOW { w: self }
}
#[doc = "Bit 12 - One-Shot/Periodic Interrupt Disable"]
#[inline(always)]
pub fn timer_tbmr_tbcintd(&mut self) -> _TIMER_TBMR_TBCINTDW {
_TIMER_TBMR_TBCINTDW { w: self }
}
#[doc = "Bits 13:15 - Timer Compare Action Select"]
#[inline(always)]
pub fn timer_tbmr_tcact(&mut self) -> _TIMER_TBMR_TCACTW {
_TIMER_TBMR_TCACTW { w: self }
}
}
|
use std::io::Cursor;
use std::path::PathBuf;
use rocket::response;
use rocket::response::NamedFile;
use rocket::Response;
use super::all_request;
use super::Context;
#[get("/")]
pub fn index<'a>(ctx: Context) -> response::Result<'a> {
all_request(ctx)
}
#[get("/favicon.ico")]
pub fn favicon() -> Option<NamedFile> {
NamedFile::open("./static/favicon.ico").ok()
}
#[get("/<_all..>", rank = 11)]
pub fn all<'a>(_all: PathBuf, ctx: Context) -> response::Result<'a> {
all_request(ctx)
}
#[get("/board")]
pub fn board<'a>() -> response::Result<'a> {
Response::build()
.raw_header("Content-Type", "text/html")
.raw_status(404, "Not Found")
.sized_body(Cursor::new(
"<script>location.assign(\
'/console/#/home')</script>",
))
.ok()
}
|
use day_09::{self, INPUT};
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn criterion_benchmark(c: &mut Criterion) {
let motions = day_09::parse_input(INPUT);
c.bench_function("day_09::parse_input", |b| {
b.iter(|| day_09::parse_input(black_box(INPUT)));
});
c.bench_function("day_09::part_one", |b| {
b.iter(|| day_09::part_one(black_box(&motions)));
});
c.bench_function("day_09::part_two", |b| {
b.iter(|| day_09::part_two(black_box(&motions)));
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
#[doc = "Reader of register ALTCLKCFG"]
pub type R = crate::R<u32, super::ALTCLKCFG>;
#[doc = "Writer for register ALTCLKCFG"]
pub type W = crate::W<u32, super::ALTCLKCFG>;
#[doc = "Register ALTCLKCFG `reset()`'s with value 0"]
impl crate::ResetValue for super::ALTCLKCFG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Alternate Clock Source\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum ALTCLK_A {
#[doc = "0: PIOSC"]
PIOSC = 0,
#[doc = "3: Hibernation Module Real-time clock output (RTCOSC)"]
RTCOSC = 3,
#[doc = "4: Low-frequency internal oscillator (LFIOSC)"]
LFIOSC = 4,
}
impl From<ALTCLK_A> for u8 {
#[inline(always)]
fn from(variant: ALTCLK_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `ALTCLK`"]
pub type ALTCLK_R = crate::R<u8, ALTCLK_A>;
impl ALTCLK_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, ALTCLK_A> {
use crate::Variant::*;
match self.bits {
0 => Val(ALTCLK_A::PIOSC),
3 => Val(ALTCLK_A::RTCOSC),
4 => Val(ALTCLK_A::LFIOSC),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PIOSC`"]
#[inline(always)]
pub fn is_piosc(&self) -> bool {
*self == ALTCLK_A::PIOSC
}
#[doc = "Checks if the value of the field is `RTCOSC`"]
#[inline(always)]
pub fn is_rtcosc(&self) -> bool {
*self == ALTCLK_A::RTCOSC
}
#[doc = "Checks if the value of the field is `LFIOSC`"]
#[inline(always)]
pub fn is_lfiosc(&self) -> bool {
*self == ALTCLK_A::LFIOSC
}
}
#[doc = "Write proxy for field `ALTCLK`"]
pub struct ALTCLK_W<'a> {
w: &'a mut W,
}
impl<'a> ALTCLK_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ALTCLK_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "PIOSC"]
#[inline(always)]
pub fn piosc(self) -> &'a mut W {
self.variant(ALTCLK_A::PIOSC)
}
#[doc = "Hibernation Module Real-time clock output (RTCOSC)"]
#[inline(always)]
pub fn rtcosc(self) -> &'a mut W {
self.variant(ALTCLK_A::RTCOSC)
}
#[doc = "Low-frequency internal oscillator (LFIOSC)"]
#[inline(always)]
pub fn lfiosc(self) -> &'a mut W {
self.variant(ALTCLK_A::LFIOSC)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - Alternate Clock Source"]
#[inline(always)]
pub fn altclk(&self) -> ALTCLK_R {
ALTCLK_R::new((self.bits & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - Alternate Clock Source"]
#[inline(always)]
pub fn altclk(&mut self) -> ALTCLK_W {
ALTCLK_W { w: self }
}
}
|
use sdl2::event::Event;
use sdl2::pixels::Color;
use sdl2::render::{Renderer, Texture, TextureQuery};
use sdl2_ttf::Font;
use setup;
const SCREEN_WIDTH: u32 = 640;
const SCREEN_HEIGHT: u32 = 480;
pub fn timer() {
let mut basic_window_setup = setup::init("Timer", SCREEN_WIDTH, SCREEN_HEIGHT);
let mut events = basic_window_setup.sdl_context.event_pump().unwrap();
let mut renderer = basic_window_setup.window
.renderer()
.present_vsync()
.accelerated()
.build()
.unwrap();
let font = setup::load_font("resources/lazy.ttf", 16, &basic_window_setup.ttf_context);
let mut time_elapsed = basic_window_setup.timer_subsystem.ticks();
let mut timer_start = time_elapsed;
'event: loop {
for event in events.poll_iter() {
match event {
Event::Quit{..} => break 'event,
Event::KeyDown{keycode: Some(::sdl2::keyboard::Keycode::Q), ..} => break 'event,
Event::KeyDown{keycode: Some(::sdl2::keyboard::Keycode::Return), ..} => {
timer_start = basic_window_setup.timer_subsystem.ticks();
}
_ => continue,
}
}
time_elapsed = basic_window_setup.timer_subsystem.ticks();
let mut timer_display_texture = time_texture(time_elapsed - timer_start, &font, &renderer);
let target = time_texture_draw_position(&timer_display_texture);
renderer.set_draw_color(Color::RGB(0xff, 0xff, 0xff));
renderer.clear();
renderer.copy(&mut timer_display_texture, None, Some(target)).expect("Texture copy failed");
renderer.present();
}
setup::quit();
}
fn time_texture(ms: u32, font: &Font, renderer: &Renderer) -> Texture {
let msg = format!("Milliseconds since start time {}", ms);
setup::text_texture(&msg, Color::RGB(0, 0, 255), font, renderer)
}
fn time_texture_draw_position(texture: &Texture) -> ::sdl2::rect::Rect {
let padding = 64;
let TextureQuery { width, height, .. } = texture.query();
setup::get_centered_rect(SCREEN_WIDTH,
SCREEN_HEIGHT,
width,
height,
SCREEN_WIDTH - padding,
SCREEN_HEIGHT - padding)
}
|
//! CBOR deserialisation tooling
use error::Error;
use len::{Len, LenSz, StringLenSz, Sz};
use result::Result;
use std::{self, collections::BTreeMap, io::BufRead};
use types::{Special, Type};
pub trait Deserialize: Sized {
/// method to implement to deserialise an object from the given
/// `Deserializer`.
fn deserialize<R: BufRead>(reader: &mut Deserializer<R>) -> Result<Self>;
}
impl Deserialize for u8 {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
let n = raw.unsigned_integer()?;
if n > std::u8::MAX as u64 {
Err(Error::ExpectedU8)
} else {
Ok(n as Self)
}
}
}
impl Deserialize for u16 {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
let n = raw.unsigned_integer()?;
if n > std::u16::MAX as u64 {
Err(Error::ExpectedU16)
} else {
Ok(n as Self)
}
}
}
impl Deserialize for u32 {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
let n = raw.unsigned_integer()?;
if n > std::u32::MAX as u64 {
Err(Error::ExpectedU32)
} else {
Ok(n as Self)
}
}
}
impl Deserialize for u64 {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
raw.unsigned_integer()
}
}
impl Deserialize for bool {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
raw.bool()
}
}
impl Deserialize for f32 {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
raw.float().map(|f| f as f32)
}
}
impl Deserialize for f64 {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
raw.float()
}
}
impl Deserialize for String {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
raw.text()
}
}
impl<T: Deserialize> Deserialize for Vec<T> {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
let mut vec = Vec::new();
raw.array_with(|raw| {
vec.push(Deserialize::deserialize(raw)?);
Ok(())
})?;
Ok(vec)
}
}
impl<K: Deserialize + Ord, V: Deserialize> Deserialize for BTreeMap<K, V> {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
let mut vec = BTreeMap::new();
raw.map_with(|raw| {
let k = Deserialize::deserialize(raw)?;
let v = Deserialize::deserialize(raw)?;
vec.insert(k, v);
Ok(())
})?;
Ok(vec)
}
}
impl<T: Deserialize> Deserialize for Option<T> {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
match raw.array()? {
Len::Len(0) => Ok(None),
Len::Len(1) => Ok(Some(raw.deserialize()?)),
len => Err(Error::CustomError(format!(
"Invalid Option<T>: received array of {:?} elements",
len
))),
}
}
}
/// [`Deserialize`]: ./trait.Deserialize.html
/// [`Error`]: ../enum.Error.html
/// [`Type`]: ../enum.Type.html
/// [`Bytes`]: ../struct.Bytes.html
/// [`cbor_type`]: #method.cbor_type
/// [`cbor_len`]: #method.cbor_len
/// [`Len`]: ../enum.Len.html
///
/// `Deserializer` represents a chunk of bytes believed to be cbor object.
/// The validity of the cbor bytes is known only when trying
/// to get meaningful cbor objects from it.
///
/// # Examples
///
/// If you already know the CBOR Primary [`Type`] you are expecting, you
/// can efficiently use the appropriate commands:
///
/// ```
/// use cbor_event::de::*;
/// use std::io::Cursor;
///
/// let vec = vec![0x18, 0x40];
/// let mut raw = Deserializer::from(Cursor::new(vec));
///
/// assert!(raw.unsigned_integer().is_ok());
/// ```
///
/// ```
/// use cbor_event::de::*;
/// use std::io::Cursor;
///
/// let vec = vec![0x18, 0x40];
/// let mut raw = Deserializer::from(Cursor::new(vec));
///
/// assert!(raw.array().is_err());
/// ```
///
/// If you don't know the [`Type`] and are only analyzing the structure, you
/// can use [`cbor_type`] to get the type of the next object to parse.
///
/// # Error
///
/// When deserialising from `Deserializer` it is possible to see the following
/// [`Error`]s:
///
/// - `Error::NotEnough(current_size, needed_size)`: meaning we are expecting
/// a more bytes to parse the CBOR properly;
/// - `Error::Expected(expected_type, current_type)`: the current cbor primary
/// [`Type`] is different from the expected [`Type`];
/// - `Error::UnknownLenType(byte)`: the CBOR is serialized in an unknown
/// or unsupported format;
/// - `Error::IndefiniteLenUnsupported(t)`: the Indefinite length is not
/// supported for the given [`Type`] `t`;
/// - `Error::IoError(io_error)`: error due relating to buffer management;
///
/// # Panic
///
/// There is no explicit `panic!` in this code, except a few `unreachable!`.
///
pub struct Deserializer<R>(R);
impl<R> From<R> for Deserializer<R> {
fn from(r: R) -> Self {
Deserializer(r)
}
}
impl<R> AsRef<R> for Deserializer<R> {
fn as_ref(&self) -> &R {
&self.0
}
}
impl<R> Deserializer<R> {
pub fn as_mut_ref(&mut self) -> &mut R {
&mut self.0
}
pub fn inner(self) -> R {
self.0
}
}
impl<R: BufRead> Deserializer<R> {
#[inline]
fn get(&mut self, index: usize) -> Result<u8> {
let buf = self.0.fill_buf()?;
match buf.get(index) {
None => Err(Error::NotEnough(buf.len(), index)),
Some(b) => Ok(*b),
}
}
#[inline]
fn u8(&mut self, index: usize) -> Result<u64> {
let b = self.get(index)?;
Ok(b as u64)
}
#[inline]
fn u16(&mut self, index: usize) -> Result<u64> {
let b1 = self.u8(index)?;
let b2 = self.u8(index + 1)?;
Ok(b1 << 8 | b2)
}
#[inline]
fn u32(&mut self, index: usize) -> Result<u64> {
let b1 = self.u8(index)?;
let b2 = self.u8(index + 1)?;
let b3 = self.u8(index + 2)?;
let b4 = self.u8(index + 3)?;
Ok(b1 << 24 | b2 << 16 | b3 << 8 | b4)
}
#[inline]
fn u64(&mut self, index: usize) -> Result<u64> {
let b1 = self.u8(index)?;
let b2 = self.u8(index + 1)?;
let b3 = self.u8(index + 2)?;
let b4 = self.u8(index + 3)?;
let b5 = self.u8(index + 4)?;
let b6 = self.u8(index + 5)?;
let b7 = self.u8(index + 6)?;
let b8 = self.u8(index + 7)?;
Ok(b1 << 56 | b2 << 48 | b3 << 40 | b4 << 32 | b5 << 24 | b6 << 16 | b7 << 8 | b8)
}
/// function to extract the type of the given `Deserializer`.
///
/// This function does not consume the underlying buffer.
///
/// # Examples
///
/// ```
/// use cbor_event::{de::*, Type};
/// use std::io::Cursor;
///
/// let vec = vec![0x18, 0x40];
/// let mut raw = Deserializer::from(Cursor::new(vec));
/// let cbor_type = raw.cbor_type().unwrap();
///
/// assert!(cbor_type == Type::UnsignedInteger);
/// ```
#[inline]
pub fn cbor_type(&mut self) -> Result<Type> {
Ok(Type::from(self.get(0)?))
}
#[inline]
fn cbor_expect_type(&mut self, t: Type) -> Result<()> {
let t_ = self.cbor_type()?;
if t_ != t {
Err(Error::Expected(t, t_))
} else {
Ok(())
}
}
/// function to extract the length parameter of
/// the given cbor object. The returned tuple contains
///
/// [`Type`]: ../enum.Type.html
/// [`Len`]: ../enum.Len.html
///
/// * the [`Len`];
/// * the size of the encoded length (the number of bytes the data was encoded in).
/// `0` means the length is `< 24` and was encoded along the `Type`.
///
/// If you are expecting a `Type` `UnsignedInteger` or `NegativeInteger` the meaning of
/// the length is slightly different:
///
/// * `Len::Indefinite` is an error;
/// * `Len::Len(len)` is the read value of the integer.
///
/// This function does not consume the underlying buffer.
///
/// # Examples
///
/// ```
/// use cbor_event::{de::*, Len};
/// use std::io::Cursor;
///
/// let vec = vec![0x83, 0x01, 0x02, 0x03];
/// let mut raw = Deserializer::from(Cursor::new(vec));
/// let (len, len_sz) = raw.cbor_len().unwrap();
///
/// assert_eq!(len, Len::Len(3));
/// assert_eq!(len_sz, 0);
/// ```
///
#[inline]
pub fn cbor_len(&mut self) -> Result<(Len, usize)> {
let b: u8 = self.get(0)? & 0b0001_1111;
match b {
0x00..=0x17 => Ok((Len::Len(b as u64), 0)),
0x18 => self.u8(1).map(|v| (Len::Len(v), 1)),
0x19 => self.u16(1).map(|v| (Len::Len(v), 2)),
0x1a => self.u32(1).map(|v| (Len::Len(v), 4)),
0x1b => self.u64(1).map(|v| (Len::Len(v), 8)),
0x1c..=0x1e => Err(Error::UnknownLenType(b)),
0x1f => Ok((Len::Indefinite, 0)),
// since the value `b` has been masked to only consider the first 5 lowest bits
// all value above 0x1f are unreachable.
_ => unreachable!(),
}
}
/// function to extract the length parameter of
/// the given cbor object as well as the encoding details of the length.
///
/// [`LenSz`]: ../enum.LenSz.html
#[inline]
pub fn cbor_len_sz(&mut self) -> Result<LenSz> {
let b: u8 = self.get(0)? & 0b0001_1111;
match b {
0x00..=0x17 => Ok(LenSz::Len(b as u64, Sz::Inline)),
0x18 => self.u8(1).map(|v| LenSz::Len(v, Sz::One)),
0x19 => self.u16(1).map(|v| LenSz::Len(v, Sz::Two)),
0x1a => self.u32(1).map(|v| LenSz::Len(v, Sz::Four)),
0x1b => self.u64(1).map(|v| LenSz::Len(v, Sz::Eight)),
0x1c..=0x1e => Err(Error::UnknownLenType(b)),
0x1f => Ok(LenSz::Indefinite),
// since the value `b` has been masked to only consider the first 5 lowest bits
// all value above 0x1f are unreachable.
_ => unreachable!(),
}
}
/// consume the given `len` from the underlying buffer. Skipped bytes are
/// then lost, they cannot be retrieved for future references.
#[inline]
pub fn advance(&mut self, len: usize) -> Result<()> {
self.0.consume(len);
Ok(())
}
/// Read an `UnsignedInteger` from the `Deserializer`
///
/// The function fails if the type of the given Deserializer is not `Type::UnsignedInteger`.
///
/// # Example
///
/// ```
/// use cbor_event::de::{*};
/// use std::io::Cursor;
///
/// let vec = vec![0x18, 0x40];
/// let mut raw = Deserializer::from(Cursor::new(vec));
///
/// let integer = raw.unsigned_integer().unwrap();
///
/// assert_eq!(integer, 64);
/// ```
///
/// ```should_panic
/// use cbor_event::de::{*};
/// use std::io::Cursor;
///
/// let vec = vec![0x83, 0x01, 0x02, 0x03];
/// let mut raw = Deserializer::from(Cursor::new(vec));
///
/// // the following line will panic:
/// let integer = raw.unsigned_integer().unwrap();
/// ```
pub fn unsigned_integer(&mut self) -> Result<u64> {
Ok(self.unsigned_integer_sz()?.0)
}
/// Read an `UnsignedInteger` from the `Deserializer` with encoding information
///
/// Same as `unsigned_integer` but returns the `Sz` (bytes used) in the encoding
pub fn unsigned_integer_sz(&mut self) -> Result<(u64, Sz)> {
self.cbor_expect_type(Type::UnsignedInteger)?;
let len_sz = self.cbor_len_sz()?;
match len_sz {
LenSz::Indefinite => Err(Error::IndefiniteLenNotSupported(Type::UnsignedInteger)),
LenSz::Len(v, sz) => {
self.advance(1 + sz.bytes_following())?;
Ok((v, sz))
}
}
}
/// Read a `NegativeInteger` from the `Deserializer`
///
/// The function fails if the type of the given Deserializer is not `Type::NegativeInteger`.
///
/// # Example
///
/// ```
/// use cbor_event::de::{*};
/// use std::io::Cursor;
///
/// let vec = vec![0x38, 0x29];
/// let mut raw = Deserializer::from(Cursor::new(vec));
///
/// let integer = raw.negative_integer().unwrap();
///
/// assert_eq!(integer, -42);
/// ```
pub fn negative_integer(&mut self) -> Result<i64> {
self.cbor_expect_type(Type::NegativeInteger)?;
let (len, len_sz) = self.cbor_len()?;
match len {
Len::Indefinite => Err(Error::IndefiniteLenNotSupported(Type::NegativeInteger)),
Len::Len(v) => {
self.advance(1 + len_sz)?;
Ok(-(v as i64) - 1)
}
}
}
/// Read a `NegativeInteger` from the `Deserializer` with encoding information
///
/// Same as `negative_integer` but returns the `Sz` (bytes used)
/// in the encoding as well as using a `i128` return type as `i64`
/// does not cover the entire CBOR `nint` range.
pub fn negative_integer_sz(&mut self) -> Result<(i128, Sz)> {
self.cbor_expect_type(Type::NegativeInteger)?;
let len_sz = self.cbor_len_sz()?;
match len_sz {
LenSz::Indefinite => Err(Error::IndefiniteLenNotSupported(Type::NegativeInteger)),
LenSz::Len(v, sz) => {
self.advance(1 + sz.bytes_following())?;
Ok((-(v as i128) - 1, sz))
}
}
}
/// Read a Bytes from the Deserializer
///
/// The function fails if the type of the given Deserializer is not `Type::Bytes`.
///
/// # Example
///
/// ```
/// use cbor_event::de::{*};
/// use std::io::Cursor;
///
/// let vec = vec![0x52, 0x73, 0x6F, 0x6D, 0x65, 0x20, 0x72, 0x61, 0x6E, 0x64, 0x6F, 0x6D, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6E, 0x67];
/// let mut raw = Deserializer::from(Cursor::new(vec));
///
/// let bytes = raw.bytes().unwrap();
/// ```
pub fn bytes(&mut self) -> Result<Vec<u8>> {
Ok(self.bytes_sz()?.0)
}
/// Read a Bytes from the Deserializer with encoding information
///
/// Same as `bytes` but also returns `StringLenSz` for details about the encoding used.
pub fn bytes_sz(&mut self) -> Result<(Vec<u8>, StringLenSz)> {
use std::io::Read;
self.cbor_expect_type(Type::Bytes)?;
let len_sz = self.cbor_len_sz()?;
self.advance(1 + len_sz.bytes_following())?;
match len_sz {
LenSz::Indefinite => {
let mut bytes = vec![];
let mut chunk_lens = Vec::new();
while self.cbor_type()? != Type::Special || !self.special_break()? {
self.cbor_expect_type(Type::Bytes)?;
let chunk_len_sz = self.cbor_len_sz()?;
match chunk_len_sz {
LenSz::Indefinite => return Err(Error::InvalidIndefiniteString),
LenSz::Len(len, sz) => {
self.advance(1 + sz.bytes_following())?;
self.0.by_ref().take(len).read_to_end(&mut bytes)?;
chunk_lens.push((len, sz));
}
}
}
Ok((bytes, StringLenSz::Indefinite(chunk_lens)))
}
LenSz::Len(len, sz) => {
let mut bytes = vec![0; len as usize];
self.0.read_exact(&mut bytes)?;
Ok((bytes, StringLenSz::Len(sz)))
}
}
}
/// Read a Text from the Deserializer
///
/// The function fails if the type of the given Deserializer is not `Type::Text`.
///
/// # Example
///
/// ```
/// use cbor_event::de::{*};
/// use std::io::Cursor;
///
/// let vec = vec![0x64, 0x74, 0x65, 0x78, 0x74];
/// let mut raw = Deserializer::from(Cursor::new(vec));
///
/// let text = raw.text().unwrap();
///
/// assert!(&*text == "text");
/// ```
pub fn text(&mut self) -> Result<String> {
Ok(self.text_sz()?.0)
}
/// Read a Text from the Deserializer with encoding information
///
/// Same as `text` but also returns `StringLenSz` for details about the encoding used.
pub fn text_sz(&mut self) -> Result<(String, StringLenSz)> {
self.cbor_expect_type(Type::Text)?;
let len_sz = self.cbor_len_sz()?;
self.advance(1 + len_sz.bytes_following())?;
match len_sz {
LenSz::Indefinite => {
let mut text = String::new();
let mut chunk_lens = Vec::new();
while self.cbor_type()? != Type::Special || !self.special_break()? {
self.cbor_expect_type(Type::Text)?;
let chunk_len = self.cbor_len_sz()?;
match chunk_len {
LenSz::Indefinite => return Err(Error::InvalidIndefiniteString),
LenSz::Len(len, sz) => {
// rfc7049 forbids splitting UTF-8 characters across chunks so we must
// read each chunk separately as a definite encoded UTF-8 string
self.advance(1 + sz.bytes_following())?;
let mut bytes = vec![0; len as usize];
self.0.read_exact(&mut bytes)?;
let chunk_text = String::from_utf8(bytes)?;
text.push_str(&chunk_text);
chunk_lens.push((len, sz));
}
}
}
Ok((text, StringLenSz::Indefinite(chunk_lens)))
}
LenSz::Len(len, sz) => {
let mut bytes = vec![0; len as usize];
self.0.read_exact(&mut bytes)?;
let text = String::from_utf8(bytes)?;
Ok((text, StringLenSz::Len(sz)))
}
}
}
// Internal helper to decode a series of `len` items using a function. If
// `len` is indefinite, decode until a `Special::Break`. If `len` is
// definite, decode that many items.
fn internal_items_with<F>(&mut self, len: Len, mut f: F) -> Result<()>
where
F: FnMut(&mut Self) -> Result<()>,
{
match len {
Len::Indefinite => {
while !self.special_break()? {
f(self)?;
}
}
Len::Len(len) => {
for _ in 0..len {
f(self)?;
}
}
}
Ok(())
}
/// cbor array of cbor objects
///
/// The function fails if the type of the given Deserializer is not `Type::Array`.
///
/// # Example
///
/// ```
/// use cbor_event::{de::{*}, Len};
/// use std::io::Cursor;
///
/// let vec = vec![0x86, 0,1,2,3,4,5];
/// let mut raw = Deserializer::from(Cursor::new(vec));
///
/// let len = raw.array().unwrap();
///
/// assert_eq!(len, Len::Len(6));
/// ```
///
pub fn array(&mut self) -> Result<Len> {
self.cbor_expect_type(Type::Array)?;
let (len, sz) = self.cbor_len()?;
self.advance(1 + sz)?;
Ok(len)
}
/// cbor array of cbor objects with length encoding information
///
/// Same as `array` but returns the `LenSz` instead which contains
/// additional information about the encoding used for the length
pub fn array_sz(&mut self) -> Result<LenSz> {
self.cbor_expect_type(Type::Array)?;
let len_sz = self.cbor_len_sz()?;
self.advance(1 + len_sz.bytes_following())?;
Ok(len_sz)
}
/// Helper to decode a cbor array using a specified function.
///
/// This works with either definite or indefinite arrays. Each call to the
/// function should decode one item. If the function returns an error,
/// decoding stops and returns that error.
pub fn array_with<F>(&mut self, f: F) -> Result<()>
where
F: FnMut(&mut Self) -> Result<()>,
{
let len = self.array()?;
self.internal_items_with(len, f)
}
/// Expect an array of a specified length. Must be a definite-length array.
pub fn tuple(&mut self, expected_len: u64, error_location: &'static str) -> Result<()> {
let actual_len = self.array()?;
match actual_len {
Len::Len(len) if expected_len == len => Ok(()),
_ => Err(Error::WrongLen(expected_len, actual_len, error_location)),
}
}
/// cbor map
///
/// The function fails if the type of the given Deserializer is not `Type::Map`.
///
/// # Example
///
/// ```
/// use cbor_event::{de::{*}, Len};
/// use std::io::Cursor;
///
/// let vec = vec![0xA2, 0x00, 0x64, 0x74, 0x65, 0x78, 0x74, 0x01, 0x18, 0x2A];
/// let mut raw = Deserializer::from(Cursor::new(vec));
///
/// let len = raw.map().unwrap();
///
/// assert_eq!(len, Len::Len(2));
/// ```
///
pub fn map(&mut self) -> Result<Len> {
self.cbor_expect_type(Type::Map)?;
let (len, sz) = self.cbor_len()?;
self.advance(1 + sz)?;
Ok(len)
}
/// cbor map with length encoding information
///
/// Same as `map` but returns the `LenSz` instead which contains
/// additional information about the encoding used for the length
pub fn map_sz(&mut self) -> Result<LenSz> {
self.cbor_expect_type(Type::Map)?;
let len_sz = self.cbor_len_sz()?;
self.advance(1 + len_sz.bytes_following())?;
Ok(len_sz)
}
/// Helper to decode a cbor map using a specified function
///
/// This works with either definite or indefinite maps. Each call to the
/// function should decode one key followed by one value. If the function
/// returns an error, decoding stops and returns that error.
pub fn map_with<F>(&mut self, f: F) -> Result<()>
where
F: FnMut(&mut Self) -> Result<()>,
{
let len = self.map()?;
self.internal_items_with(len, f)
}
/// Cbor Tag
///
/// The function fails if the type of the given Deserializer is not `Type::Tag`.
///
/// # Example
///
/// ```
/// use std::io::Cursor;
/// use cbor_event::{de::{*}, Len};
///
/// let vec = vec![0xD8, 0x18, 0x64, 0x74, 0x65, 0x78, 0x74];
/// let mut raw = Deserializer::from(Cursor::new(vec));
///
/// let tag = raw.tag().unwrap();
///
/// assert_eq!(24, tag);
/// assert_eq!("text", &*raw.text().unwrap());
/// ```
///
pub fn tag(&mut self) -> Result<u64> {
Ok(self.tag_sz()?.0)
}
/// CBOR Tag with encoding information
///
/// Same as `tag` but returns the `Sz` (bytes used) in the encoding
pub fn tag_sz(&mut self) -> Result<(u64, Sz)> {
self.cbor_expect_type(Type::Tag)?;
match self.cbor_len_sz()? {
LenSz::Indefinite => Err(Error::IndefiniteLenNotSupported(Type::Tag)),
LenSz::Len(len, sz) => {
self.advance(1 + sz.bytes_following())?;
Ok((len, sz))
}
}
}
pub fn set_tag(&mut self) -> Result<()> {
let tag = self.tag()?;
if tag != 258 {
return Err(Error::ExpectedSetTag);
}
Ok(())
}
/// If the next byte is a `Special::Break`, advance past it and return `true`; otherwise,
/// return `false` without advancing.
///
/// Useful when decoding a variable-length array or map where the items may themselves use
/// `Special`, such as bool values.
pub fn special_break(&mut self) -> Result<bool> {
self.cbor_expect_type(Type::Special)?;
let b = self.get(0)? & 0b0001_1111;
if b == 0x1f {
self.advance(1)?;
Ok(true)
} else {
Ok(false)
}
}
pub fn special(&mut self) -> Result<Special> {
self.cbor_expect_type(Type::Special)?;
let b = self.get(0)? & 0b0001_1111;
match b {
0x00..=0x13 => {
self.advance(1)?;
Ok(Special::Unassigned(b))
}
0x14 => {
self.advance(1)?;
Ok(Special::Bool(false))
}
0x15 => {
self.advance(1)?;
Ok(Special::Bool(true))
}
0x16 => {
self.advance(1)?;
Ok(Special::Null)
}
0x17 => {
self.advance(1)?;
Ok(Special::Undefined)
}
0x18 => {
let b = self.u8(1)?;
self.advance(2)?;
Ok(Special::Unassigned(b as u8))
}
0x19 => {
let f = self.u16(1)?;
self.advance(3)?;
Ok(Special::Float(f as f64))
}
0x1a => {
let f = self.u32(1)? as u32;
self.advance(5)?;
Ok(Special::Float(f32::from_bits(f) as f64))
}
0x1b => {
let f = self.u64(1)?;
self.advance(9)?;
Ok(Special::Float(f64::from_bits(f)))
}
0x1c..=0x1e => {
self.advance(1)?;
Ok(Special::Unassigned(b))
}
0x1f => {
self.advance(1)?;
Ok(Special::Break)
}
_ => unreachable!(),
}
}
pub fn bool(&mut self) -> Result<bool> {
self.special()?.unwrap_bool()
}
pub fn float(&mut self) -> Result<f64> {
self.special()?.unwrap_float()
}
pub fn deserialize<T>(&mut self) -> Result<T>
where
T: Deserialize,
{
Deserialize::deserialize(self)
}
/// Deserialize a value of type `T` and check that there is no
/// trailing data.
pub fn deserialize_complete<T>(&mut self) -> Result<T>
where
T: Deserialize,
{
let v = self.deserialize()?;
if !self.0.fill_buf()?.is_empty() {
Err(Error::TrailingData)
} else {
Ok(v)
}
}
}
// deserialisation macro
macro_rules! deserialize_array {
( $( $x:expr ),* ) => {
$(
impl Deserialize for [u8; $x] {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> {
let mut bytes = [0u8; $x];
let len = raw.array()?;
match len {
Len::Indefinite => {
return Err(Error::WrongLen($x, len, "static array"));
},
Len::Len(x) => {
if x != $x {
return Err(Error::WrongLen($x, len, "static array"));
}
}
}
for byte in bytes.iter_mut() {
*byte = Deserialize::deserialize(raw)?;
}
Ok(bytes)
}
}
)*
}
}
deserialize_array!(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64
);
#[cfg(test)]
#[allow(clippy::bool_assert_comparison)]
mod test {
use super::*;
use std::io::Cursor;
#[test]
fn negative_integer() {
let vec = vec![0x38, 0x29];
let mut raw = Deserializer::from(Cursor::new(vec));
let integer = raw.negative_integer().unwrap();
assert_eq!(integer, -42);
}
#[test]
fn bytes() {
let vec = vec![
0x52, 0x73, 0x6F, 0x6D, 0x65, 0x20, 0x72, 0x61, 0x6E, 0x64, 0x6F, 0x6D, 0x20, 0x73,
0x74, 0x72, 0x69, 0x6E, 0x67,
];
let mut raw = Deserializer::from(Cursor::new(vec.clone()));
let bytes = raw.bytes().unwrap();
assert_eq!(&vec[1..], &*bytes);
}
#[test]
fn bytes_indefinite() {
let chunks = vec![
vec![
0x52, 0x73, 0x6F, 0x6D, 0x65, 0x20, 0x72, 0x61, 0x6E, 0x64, 0x6F, 0x6D, 0x20, 0x73,
0x74, 0x72, 0x69, 0x6E, 0x67,
],
vec![0x44, 0x01, 0x02, 0x03, 0x04],
];
let mut expected = Vec::new();
for chunk in chunks.iter() {
expected.extend_from_slice(&chunk[1..]);
}
let mut vec = vec![0x5f];
for mut chunk in chunks {
vec.append(&mut chunk);
}
vec.push(0xff);
let mut raw = Deserializer::from(Cursor::new(vec.clone()));
let found = raw.bytes().unwrap();
assert_eq!(found, expected);
}
#[test]
fn bytes_empty() {
let vec = vec![0x40];
let mut raw = Deserializer::from(Cursor::new(vec));
let bytes = raw.bytes().unwrap();
assert!(bytes.is_empty());
}
#[test]
fn text() {
let vec = vec![0x64, 0x74, 0x65, 0x78, 0x74];
let mut raw = Deserializer::from(Cursor::new(vec));
let text = raw.text().unwrap();
assert_eq!(&text, "text");
}
#[test]
fn text_indefinite() {
let chunks = vec![vec![0x64, 0x49, 0x45, 0x54, 0x46], vec![0x61, 0x61]];
let expected = "IETFa";
let mut vec = vec![0x7f];
for mut chunk in chunks {
vec.append(&mut chunk);
}
vec.push(0xff);
let mut raw = Deserializer::from(Cursor::new(vec.clone()));
let found = raw.text().unwrap();
assert_eq!(found, expected);
}
#[test]
fn text_empty() {
let vec = vec![0x60];
let mut raw = Deserializer::from(Cursor::new(vec));
let text = raw.text().unwrap();
assert_eq!(&text, "");
}
#[test]
fn float64() {
let vec = vec![0xfb, 0x3f, 0xf1, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a];
let mut raw = Deserializer::from(Cursor::new(vec));
let float = raw.float().unwrap();
assert_eq!(float, 1.1);
}
#[test]
fn float32() {
let vec = vec![0xfa, 0x47, 0xc3, 0x50, 0x00];
let mut raw = Deserializer::from(Cursor::new(vec));
let float = raw.float().unwrap();
assert_eq!(float, 100000.0);
}
#[test]
fn array() {
let vec = vec![0x86, 0, 1, 2, 3, 4, 5];
let mut raw = Deserializer::from(Cursor::new(vec));
let len = raw.array().unwrap();
assert_eq!(len, Len::Len(6));
// assert_eq!(&*raw, &[0, 1, 2, 3, 4, 5][..]);
assert_eq!(0, raw.unsigned_integer().unwrap());
assert_eq!(1, raw.unsigned_integer().unwrap());
assert_eq!(2, raw.unsigned_integer().unwrap());
assert_eq!(3, raw.unsigned_integer().unwrap());
assert_eq!(4, raw.unsigned_integer().unwrap());
assert_eq!(5, raw.unsigned_integer().unwrap());
}
#[test]
fn array_empty() {
let vec = vec![0x80];
let mut raw = Deserializer::from(Cursor::new(vec));
let len = raw.array().unwrap();
assert_eq!(len, Len::Len(0));
// assert_eq!(&*raw, &[][..]);
}
#[test]
fn array_indefinite() {
let vec = vec![0x9F, 0x01, 0x02, 0xFF];
let mut raw = Deserializer::from(Cursor::new(vec));
let len = raw.array().unwrap();
assert_eq!(len, Len::Indefinite);
// assert_eq!(&*raw, &[0x01, 0x02, 0xFF][..]);
let i = raw.unsigned_integer().unwrap();
assert!(i == 1);
let i = raw.unsigned_integer().unwrap();
assert!(i == 2);
assert_eq!(Special::Break, raw.special().unwrap());
}
#[test]
fn vec_bool_definite() {
let vec = vec![0x83, 0xf4, 0xf5, 0xf4];
let mut raw = Deserializer::from(Cursor::new(vec));
let bools = Vec::<bool>::deserialize(&mut raw).unwrap();
assert_eq!(bools, &[false, true, false]);
}
#[test]
fn vec_bool_indefinite() {
let vec = vec![0x9f, 0xf4, 0xf5, 0xf4, 0xff];
let mut raw = Deserializer::from(Cursor::new(vec));
let bools = Vec::<bool>::deserialize(&mut raw).unwrap();
assert_eq!(bools, &[false, true, false]);
}
#[test]
fn complex_array() {
let vec = vec![
0x85, 0x64, 0x69, 0x6F, 0x68, 0x6B, 0x01, 0x20, 0x84, 0, 1, 2, 3, 0x10,
/* garbage... */ 0, 1, 2, 3, 4, 5, 6,
];
let mut raw = Deserializer::from(Cursor::new(vec));
let len = raw.array().unwrap();
assert_eq!(len, Len::Len(5));
assert_eq!("iohk", &raw.text().unwrap());
assert_eq!(1, raw.unsigned_integer().unwrap());
assert_eq!(-1, raw.negative_integer().unwrap());
let nested_array_len = raw.array().unwrap();
assert_eq!(nested_array_len, Len::Len(4));
assert_eq!(0, raw.unsigned_integer().unwrap());
assert_eq!(1, raw.unsigned_integer().unwrap());
assert_eq!(2, raw.unsigned_integer().unwrap());
assert_eq!(3, raw.unsigned_integer().unwrap());
assert_eq!(0x10, raw.unsigned_integer().unwrap());
// const GARBAGE_LEN: usize = 7;
// assert_eq!(GARBAGE_LEN, raw.len());
}
#[test]
fn map() {
let vec = vec![0xA2, 0x00, 0x64, 0x74, 0x65, 0x78, 0x74, 0x01, 0x18, 0x2A];
let mut raw = Deserializer::from(Cursor::new(vec));
let len = raw.map().unwrap();
assert_eq!(len, Len::Len(2));
let k = raw.unsigned_integer().unwrap();
let v = raw.text().unwrap();
assert_eq!(0, k);
assert_eq!("text", &v);
let k = raw.unsigned_integer().unwrap();
let v = raw.unsigned_integer().unwrap();
assert_eq!(1, k);
assert_eq!(42, v);
}
#[test]
fn map_empty() {
let vec = vec![0xA0];
let mut raw = Deserializer::from(Cursor::new(vec));
let len = raw.map().unwrap();
assert_eq!(len, Len::Len(0));
}
#[test]
fn btreemap_bool_definite() {
let vec = vec![0xa2, 0xf4, 0xf5, 0xf5, 0xf4];
let mut raw = Deserializer::from(Cursor::new(vec));
let boolmap = BTreeMap::<bool, bool>::deserialize(&mut raw).unwrap();
assert_eq!(boolmap.len(), 2);
assert_eq!(boolmap[&false], true);
assert_eq!(boolmap[&true], false);
}
#[test]
fn btreemap_bool_indefinite() {
let vec = vec![0xbf, 0xf4, 0xf5, 0xf5, 0xf4, 0xff];
let mut raw = Deserializer::from(Cursor::new(vec));
let boolmap = BTreeMap::<bool, bool>::deserialize(&mut raw).unwrap();
assert_eq!(boolmap.len(), 2);
assert_eq!(boolmap[&false], true);
assert_eq!(boolmap[&true], false);
}
#[test]
fn tag() {
let vec = vec![
0xD8, 0x18, 0x52, 0x73, 0x6F, 0x6D, 0x65, 0x20, 0x72, 0x61, 0x6E, 0x64, 0x6F, 0x6D,
0x20, 0x73, 0x74, 0x72, 0x69, 0x6E, 0x67,
];
let mut raw = Deserializer::from(Cursor::new(vec));
let tag = raw.tag().unwrap();
assert_eq!(24, tag);
let tagged = raw.bytes().unwrap();
assert_eq!(b"some random string", &*tagged);
}
#[test]
fn tag2() {
let vec = vec![
0x82, 0xd8, 0x18, 0x53, 0x52, 0x73, 0x6f, 0x6d, 0x65, 0x20, 0x72, 0x61, 0x6e, 0x64,
0x6f, 0x6d, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x1a, 0x71, 0xad, 0x58, 0x36,
];
let mut raw = Deserializer::from(Cursor::new(vec));
let len = raw.array().unwrap();
assert_eq!(len, Len::Len(2));
let tag = raw.tag().unwrap();
assert!(tag == 24);
let _ = raw.bytes().unwrap();
let crc = raw.unsigned_integer().unwrap();
assert!(crc as u32 == 0x71AD5836);
}
#[test]
fn uint_sz() {
let vec = vec![
0x09, 0x18, 0x09, 0x19, 0x00, 0x09, 0x1a, 0x00, 0x00, 0x00, 0x09, 0x1b, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x09,
];
let mut raw = Deserializer::from(Cursor::new(vec));
assert_eq!(raw.unsigned_integer_sz().unwrap(), (9, Sz::Inline));
assert_eq!(raw.unsigned_integer_sz().unwrap(), (9, Sz::One));
assert_eq!(raw.unsigned_integer_sz().unwrap(), (9, Sz::Two));
assert_eq!(raw.unsigned_integer_sz().unwrap(), (9, Sz::Four));
assert_eq!(raw.unsigned_integer_sz().unwrap(), (9, Sz::Eight));
}
#[test]
fn nint_sz() {
let vec = vec![
0x28, 0x38, 0x08, 0x39, 0x00, 0x08, 0x3a, 0x00, 0x00, 0x00, 0x08, 0x3b, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x08,
];
let mut raw = Deserializer::from(Cursor::new(vec));
assert_eq!(raw.negative_integer_sz().unwrap(), (-9, Sz::Inline));
assert_eq!(raw.negative_integer_sz().unwrap(), (-9, Sz::One));
assert_eq!(raw.negative_integer_sz().unwrap(), (-9, Sz::Two));
assert_eq!(raw.negative_integer_sz().unwrap(), (-9, Sz::Four));
assert_eq!(raw.negative_integer_sz().unwrap(), (-9, Sz::Eight));
}
#[test]
fn bytes_sz() {
let def_parts: Vec<Vec<u8>> = vec![
vec![0x44, 0xBA, 0xAD, 0xF0, 0x0D],
vec![0x58, 0x04, 0xCA, 0xFE, 0xD0, 0x0D],
vec![0x59, 0x00, 0x04, 0xDE, 0xAD, 0xBE, 0xEF],
vec![0x5a, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xFE],
vec![
0x5b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xBE, 0xEF,
],
];
let mut vec: Vec<u8> = def_parts.iter().flatten().cloned().collect();
// also make an indefinite encoded one out all the definite-encoded parts
vec.push(0x5F);
for slice in def_parts.iter() {
vec.extend_from_slice(&slice[..]);
}
vec.push(0xFF);
let mut raw = Deserializer::from(Cursor::new(vec));
let indef_bytes = vec![
0xBA, 0xAD, 0xF0, 0x0D, 0xCA, 0xFE, 0xD0, 0x0D, 0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE,
0xBE, 0xEF,
];
let indef_lens = vec![
(4, Sz::Inline),
(4, Sz::One),
(4, Sz::Two),
(2, Sz::Four),
(2, Sz::Eight),
];
assert_eq!(
raw.bytes_sz().unwrap(),
(vec![0xBA, 0xAD, 0xF0, 0x0D], StringLenSz::Len(Sz::Inline))
);
assert_eq!(
raw.bytes_sz().unwrap(),
(vec![0xCA, 0xFE, 0xD0, 0x0D], StringLenSz::Len(Sz::One))
);
assert_eq!(
raw.bytes_sz().unwrap(),
(vec![0xDE, 0xAD, 0xBE, 0xEF], StringLenSz::Len(Sz::Two))
);
assert_eq!(
raw.bytes_sz().unwrap(),
(vec![0xCA, 0xFE], StringLenSz::Len(Sz::Four))
);
assert_eq!(
raw.bytes_sz().unwrap(),
(vec![0xBE, 0xEF], StringLenSz::Len(Sz::Eight))
);
assert_eq!(
raw.bytes_sz().unwrap(),
(indef_bytes, StringLenSz::Indefinite(indef_lens))
);
}
#[test]
fn text_sz() {
let def_parts: Vec<Vec<u8>> = vec![
vec![0x65, 0x48, 0x65, 0x6c, 0x6c, 0x6f],
vec![0x78, 0x05, 0x57, 0x6f, 0x72, 0x6c, 0x64],
vec![
0x79, 0x00, 0x09, 0xE6, 0x97, 0xA5, 0xE6, 0x9C, 0xAC, 0xE8, 0xAA, 0x9E,
],
vec![0x7a, 0x00, 0x00, 0x00, 0x01, 0x39],
vec![
0x7b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x41, 0x42, 0x43,
],
];
let mut vec: Vec<u8> = def_parts.iter().flatten().cloned().collect();
// also make an indefinite encoded one out all the definite-encoded parts
vec.push(0x7F);
for slice in def_parts.iter() {
vec.extend_from_slice(&slice[..]);
}
vec.push(0xFF);
let mut raw = Deserializer::from(Cursor::new(vec));
let indef_lens = vec![
(5, Sz::Inline),
(5, Sz::One),
(9, Sz::Two),
(1, Sz::Four),
(3, Sz::Eight),
];
assert_eq!(
raw.text_sz().unwrap(),
("Hello".into(), StringLenSz::Len(Sz::Inline))
);
assert_eq!(
raw.text_sz().unwrap(),
("World".into(), StringLenSz::Len(Sz::One))
);
assert_eq!(
raw.text_sz().unwrap(),
("日本語".into(), StringLenSz::Len(Sz::Two))
);
assert_eq!(
raw.text_sz().unwrap(),
("9".into(), StringLenSz::Len(Sz::Four))
);
assert_eq!(
raw.text_sz().unwrap(),
("ABC".into(), StringLenSz::Len(Sz::Eight))
);
assert_eq!(
raw.text_sz().unwrap(),
(
"HelloWorld日本語9ABC".into(),
StringLenSz::Indefinite(indef_lens)
)
);
}
#[test]
fn array_sz() {
let vec = vec![
0x80, 0x98, 0x01, 0x99, 0x00, 0x02, 0x9a, 0x00, 0x00, 0x00, 0x03, 0x9b, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x9f,
];
let mut raw = Deserializer::from(Cursor::new(vec));
assert_eq!(raw.array_sz().unwrap(), LenSz::Len(0, Sz::Inline));
assert_eq!(raw.array_sz().unwrap(), LenSz::Len(1, Sz::One));
assert_eq!(raw.array_sz().unwrap(), LenSz::Len(2, Sz::Two));
assert_eq!(raw.array_sz().unwrap(), LenSz::Len(3, Sz::Four));
assert_eq!(raw.array_sz().unwrap(), LenSz::Len(4, Sz::Eight));
assert_eq!(raw.array_sz().unwrap(), LenSz::Indefinite);
}
#[test]
fn map_sz() {
let vec = vec![
0xa0, 0xb8, 0x01, 0xb9, 0x00, 0x02, 0xba, 0x00, 0x00, 0x00, 0x03, 0xbb, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xbf,
];
let mut raw = Deserializer::from(Cursor::new(vec));
assert_eq!(raw.map_sz().unwrap(), LenSz::Len(0, Sz::Inline));
assert_eq!(raw.map_sz().unwrap(), LenSz::Len(1, Sz::One));
assert_eq!(raw.map_sz().unwrap(), LenSz::Len(2, Sz::Two));
assert_eq!(raw.map_sz().unwrap(), LenSz::Len(3, Sz::Four));
assert_eq!(raw.map_sz().unwrap(), LenSz::Len(4, Sz::Eight));
assert_eq!(raw.map_sz().unwrap(), LenSz::Indefinite);
}
#[test]
fn tag_sz() {
let vec = vec![
0xc9, 0xd8, 0x01, 0xd9, 0x00, 0x02, 0xda, 0x00, 0x00, 0x00, 0x04, 0xdb, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x08,
];
let mut raw = Deserializer::from(Cursor::new(vec));
assert_eq!(raw.tag_sz().unwrap(), (9, Sz::Inline));
assert_eq!(raw.tag_sz().unwrap(), (1, Sz::One));
assert_eq!(raw.tag_sz().unwrap(), (2, Sz::Two));
assert_eq!(raw.tag_sz().unwrap(), (4, Sz::Four));
assert_eq!(raw.tag_sz().unwrap(), (8, Sz::Eight));
}
}
|
extern crate tuix;
use tuix::*;
use femtovg::{
renderer::OpenGl, Baseline, Canvas, FillRule, FontId, ImageFlags, ImageId, LineCap,
LineJoin, Paint, Path, Renderer, Solidity,
};
static THEME: &'static str = include_str!("themes/widget_theme.css");
fn main() {
// Create the app
let mut app = Application::new(|win_desc, state, window| {
state.insert_theme(THEME);
let piano_roll = PianoRoll::new().build(state, window, |builder|
builder
//.set_flex_grow(1.0)
//.set_flex_shrink(1.0)
.set_width(Length::Percentage(1.0))
.set_height(Length::Percentage(1.0))
.set_background_color(Color::rgb(100,50,50))
);
win_desc.with_title("basic").with_inner_size(800, 600)
});
app.run();
}
pub struct PianoRoll {
midi_grid_scroll_container: Entity,
}
impl PianoRoll {
pub fn new() -> Self {
PianoRoll {
midi_grid_scroll_container: Entity::null(),
}
}
}
impl BuildHandler for PianoRoll {
type Ret = Entity;
fn on_build(&mut self, state: &mut State, entity: Entity) -> Self::Ret {
let header = HBox::new().build(state, entity, |builder| builder.class("header"));
let body = VBox::new().build(state, entity, |builder| builder.class("body"));
let container = HBox::new().build(state, body, |builder|
builder
//.set_width(Length::Pixels(600.0))
//.set_height(Length::Pixels(1200.0))
.set_background_color(Color::rgb(100,100,50))
.set_flex_grow(1.0)
.set_flex_shrink(1.0)
);
let left = Element::new().build(state, container, |builder| builder.set_background_color(Color::rgb(200,200,255)));
let scroll = ScrollContainer::new().build(state, left, |builder| builder.set_width(Length::Pixels(210.0)).set_flex_grow(0.0));
let keys_container = VBox::new().build(state, scroll, |builder|
builder
.set_width(Length::Pixels(200.0))
.set_height(Length::Pixels(1200.0))
//.set_flex_grow(1.0)
.set_background_color(Color::rgb(80,80,80))
);
for j in 0..4 {
for i in 0..12 {
if i == 1 || i == 3 || i == 5 || i == 8 || i == 10 {
Element::new().build(state, keys_container, |builder|
builder
.set_flex_grow(1.0)
.set_margin_bottom(Length::Pixels(1.0))
.set_background_color(Color::rgb(0,0,0))
);
} else {
Element::new().build(state, keys_container, |builder|
builder
.set_flex_grow(1.0)
.set_margin_bottom(Length::Pixels(1.0))
.set_background_color(Color::rgb(255,255,255))
);
}
}
}
// let scroll2 = ScrollContainerH::new().build(state, container, |builder|
// builder
// // .set_width(Length::Pixels(200.0))
// // .set_height(Length::Pixels(200.0))
// );
let right = Element::new().build(state, container, |builder|
builder
.set_flex_grow(1.0)
// .set_flex_shrink(1.0)
.set_background_color(Color::rgb(200,200,200))
);
self.midi_grid_scroll_container = ScrollContainerH::new().build(state, right, |builder| builder);
let midi_grid = MidiGrid::new().build(state, self.midi_grid_scroll_container, |builder|
builder
.set_flex_grow(1.0)
.set_width(Length::Pixels(2000.0))
.set_height(Length::Pixels(2000.0))
.set_background_color(Color::rgb(80,80,80))
//.set_clip_widget(self.midi_grid_scroll_container)
);
// // let midi_note = MidiNote::new().build(state, midi_grid, |builder|
// // builder
// // .set_top(Length::Pixels(0.0))
// // .set_width(Length::Pixels(40.0))
// // .set_height(Length::Pixels(24.0))
// // .set_background_color(Color::rgb(255,20,20))
// // );
entity
}
}
impl EventHandler for PianoRoll {
fn on_event(&mut self, state: &mut State, entity: Entity, event: &mut Event) -> bool {
if let Some(scroll_event) = event.message.downcast::<ScrollEvent>() {
match scroll_event {
ScrollEvent::ScrollV(val) => {
// Currently a hacky way to do it that doesn't currently generalise
self.midi_grid_scroll_container.set_top(state, Length::Percentage(*val));
}
}
}
false
}
}
const zoom_levels: [f32; 11] = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5];
pub struct MidiGrid {
zoom_index: usize,
}
impl MidiGrid {
pub fn new() -> Self {
MidiGrid {
zoom_index: 5,
}
}
}
impl BuildHandler for MidiGrid {
type Ret = Entity;
fn on_build(&mut self, state: &mut State, entity: Entity) -> Self::Ret {
entity
}
}
impl EventHandler for MidiGrid {
fn on_event(&mut self, state: &mut State, entity: Entity, event: &mut Event) -> bool {
if let Some(window_event) = event.message.downcast::<WindowEvent>() {
match window_event {
WindowEvent::MouseScroll(x,y) => {
if state.modifiers.ctrl {
let width = state.transform.get_width(entity);
let posx = state.transform.get_posx(entity);
self.zoom_index = (self.zoom_index as f32 + *y) as usize;
if self.zoom_index >= 10 {
self.zoom_index = 10;
}
if self.zoom_index <= 0 {
self.zoom_index = 0;
}
let new_width = 2000.0 * zoom_levels[self.zoom_index];
// Distance between centre and mouse position
let distx = state.mouse.cursorx - posx;
let new_posx = distx * (zoom_levels[self.zoom_index] - 1.0);
entity.set_width(state, Length::Pixels(new_width));
//entity.set_left(state, Length::Pixels(-new_posx));
//state.insert_event(Event::new(WindowEvent::Relayout).target(Entity::null()).origin(entity));
}
}
_=> {}
}
}
false
}
fn on_draw(&mut self, state: &mut State, entity: Entity, canvas: &mut Canvas<OpenGl>) {
// Skip window
if entity == Entity::new(0, 0) {
return;
}
// Skip invisible widgets
if state.transform.get_visibility(entity) == Visibility::Invisible {
return;
}
if state.transform.get_opacity(entity) == 0.0 {
return;
}
let posx = state.transform.get_posx(entity);
let posy = state.transform.get_posy(entity);
let width = state.transform.get_width(entity);
let height = state.transform.get_height(entity);
let background_color = state
.style
.background_color
.get(entity)
.cloned()
.unwrap_or_default();
let font_color = state
.style
.font_color
.get(entity)
.cloned()
.unwrap_or(tuix::Color::rgb(255, 255, 255));
let border_color = state
.style
.border_color
.get(entity)
.cloned()
.unwrap_or_default();
let shadow_color = state
.style
.shadow_color
.get(entity)
.cloned()
.unwrap_or_default();
let parent = state
.hierarchy
.get_parent(entity)
.expect("Failed to find parent somehow");
let parent_width = state.transform.get_width(parent);
let border_radius_top_left = match state.style.border_radius_top_left.get(entity).cloned().unwrap_or_default() {
Length::Pixels(val) => val,
Length::Percentage(val) => parent_width * val,
_ => 0.0,
};
let border_radius_top_right = match state.style.border_radius_top_right.get(entity).cloned().unwrap_or_default() {
Length::Pixels(val) => val,
Length::Percentage(val) => parent_width * val,
_ => 0.0,
};
let border_radius_bottom_left = match state.style.border_radius_bottom_left.get(entity).cloned().unwrap_or_default() {
Length::Pixels(val) => val,
Length::Percentage(val) => parent_width * val,
_ => 0.0,
};
let border_radius_bottom_right = match state.style.border_radius_bottom_right.get(entity).cloned().unwrap_or_default() {
Length::Pixels(val) => val,
Length::Percentage(val) => parent_width * val,
_ => 0.0,
};
let opacity = state.transform.get_opacity(entity);
let mut background_color: femtovg::Color = background_color.into();
background_color.set_alphaf(background_color.a * opacity);
let mut border_color: femtovg::Color = border_color.into();
border_color.set_alphaf(border_color.a * opacity);
let mut shadow_color: femtovg::Color = shadow_color.into();
shadow_color.set_alphaf(shadow_color.a * opacity);
let border_width = match state
.style
.border_width
.get(entity)
.cloned()
.unwrap_or_default()
{
Length::Pixels(val) => val,
Length::Percentage(val) => parent_width * val,
_ => 0.0,
};
// Apply Scissor
let clip_entity = state.transform.get_clip_widget(entity);
let clip_posx = state.transform.get_posx(clip_entity);
let clip_posy = state.transform.get_posy(clip_entity);
let clip_width = state.transform.get_width(clip_entity);
let clip_height = state.transform.get_height(clip_entity);
canvas.scissor(clip_posx, clip_posy, clip_width, clip_height);
// Draw rounded rect
let mut path = Path::new();
path.rounded_rect_varying(
posx + (border_width / 2.0),
posy + (border_width / 2.0),
width - border_width,
height - border_width,
border_radius_top_left,
border_radius_top_right,
border_radius_bottom_right,
border_radius_bottom_left,
);
let mut paint = Paint::color(background_color);
canvas.fill_path(&mut path, paint);
// Draw border
let mut paint = Paint::color(border_color);
paint.set_line_width(border_width);
//paint.set_anti_alias(false);
canvas.stroke_path(&mut path, paint);
let horizontal_spacing = state.transform.get_width(entity) / 50.0;
let vertical_spacing = state.transform.get_height(entity) / 50.0;
for i in 0..50 {
if i % 2 == 0 {
let mut path = Path::new();
path.rect(posx, posy + (i as f32) * 25.0, width, 24.0);
let mut paint = Paint::color(femtovg::Color::rgb(70,70,70));
paint.set_line_width(1.0);
canvas.fill_path(&mut path, paint);
}
}
for i in 0..50 {
let mut path = Path::new();
path.move_to(posx + (i as f32)*horizontal_spacing, posy);
path.line_to(posx + (i as f32)*horizontal_spacing, posy + height);
let mut paint = Paint::color(femtovg::Color::rgb(100,100,100));
paint.set_line_width(1.0);
canvas.stroke_path(&mut path, paint);
}
}
}
pub struct MidiNote {
moving: bool,
resizing_right: bool,
resizing_left: bool,
mouse_down_x: f32,
}
impl MidiNote {
pub fn new() -> Self {
MidiNote {
moving: false,
resizing_left: false,
resizing_right: false,
mouse_down_x: 0.0,
}
}
}
impl BuildHandler for MidiNote {
type Ret = Entity;
fn on_build(&mut self, state: &mut State, entity: Entity) -> Self::Ret {
entity.set_position(state, Position::Absolute)
}
}
impl EventHandler for MidiNote {
fn on_event(&mut self, state: &mut State, entity: Entity, event: &mut Event) -> bool {
if let Some(window_event) = event.message.downcast::<WindowEvent>() {
match window_event {
WindowEvent::MouseDown(button) => {
if event.target == entity && *button == MouseButton::Left {
if state.mouse.left.pos_down.0 > state.transform.get_posx(entity)
&& state.mouse.left.pos_down.0 < state.transform.get_posx(entity) + 5.0
{
self.resizing_left = true;
state.capture(entity);
} else if state.mouse.left.pos_down.0 > state.transform.get_posx(entity) + state.transform.get_width(entity) - 5.0
&& state.mouse.left.pos_down.0 < state.transform.get_posx(entity) + state.transform.get_width(entity)
{
self.resizing_right = true;
state.capture(entity);
} else {
self.moving = true;
self.mouse_down_x = state.mouse.left.pos_down.0;
state.capture(entity);
}
}
}
WindowEvent::MouseUp(button) => {
if event.target == entity && *button == MouseButton::Left {
self.moving = false;
self.resizing_left = false;
self.resizing_right = false;
state.release(entity);
}
}
WindowEvent::MouseMove(x,y) => {
let dx = *x - self.mouse_down_x;
let parent = state.hierarchy.get_parent(entity).unwrap();
let parent_posy = state.transform.get_posy(parent);
let parent_posx = state.transform.get_posx(parent);
let posy = state.transform.get_posy(entity) - parent_posy;
let posx = state.transform.get_posx(entity) - parent_posx;
let height = state.transform.get_height(entity);
let width = state.transform.get_width(entity);
if self.moving {
if *y < state.transform.get_posy(entity) {
entity.set_top(state, Length::Pixels(posy - height - 1.0));
} else if *y > (state.transform.get_posy(entity) + height) {
entity.set_top(state, Length::Pixels(posy + height + 1.0));
}
if dx < -20.0 {
entity.set_left(state, Length::Pixels(posx - 40.0));
self.mouse_down_x -= 40.0;
} else if dx > 20.0 {
entity.set_left(state, Length::Pixels(posx + 40.0));
self.mouse_down_x += 40.0;
}
}
if self.resizing_right {
if *x > state.transform.get_posx(entity) + state.transform.get_width(entity) + 20.0 {
entity.set_width(state, Length::Pixels(width + 40.0));
} else if *x < state.transform.get_posx(entity) + state.transform.get_width(entity) - 20.0 {
entity.set_width(state, Length::Pixels(width - 40.0));
}
}
if self.resizing_left {
if *x > state.transform.get_posx(entity) + 20.0 {
entity.set_width(state, Length::Pixels(width - 40.0));
entity.set_left(state, Length::Pixels(posx + 40.0));
} else if *x < state.transform.get_posx(entity) - 20.0 {
entity.set_width(state, Length::Pixels(width + 40.0));
entity.set_left(state, Length::Pixels(posx - 40.0));
}
}
}
_=> {}
}
}
false
}
} |
#![no_main]
#![no_std]
extern crate cortex_m;
extern crate cortex_m_rt;
extern crate panic_itm;
extern crate stm32f407g_disc as board;
extern crate embedded_hal as hal;
use cortex_m_rt::entry;
use board::hal::delay::Delay;
use board::hal::prelude::*;
use board::hal::stm32;
use board::gpio;
use board::gpio::gpiod::{PD12, PD13, PD14, PD15};
use board::hal::serial;
use board::hal::serial::{Serial};
#[macro_use(block)]
extern crate nb;
mod sbus;
use hal::digital::OutputPin;
use cortex_m::iprintln;
use cortex_m::peripheral::Peripherals;
struct Leds {
green: PD12<gpio::Output<gpio::PushPull>>,
orange: PD13<gpio::Output<gpio::PushPull>>,
red: PD14<gpio::Output<gpio::PushPull>>,
blue: PD15<gpio::Output<gpio::PushPull>>,
}
#[entry]
fn main() -> ! {
if let (Some(p), Some(cp)) = (stm32::Peripherals::take(), Peripherals::take()) {
let gpiod = p.GPIOD.split();
let mut itm = cp.ITM;
// Constrain clock registers
let mut rcc = p.RCC.constrain();
// Configure clock to 168 MHz (i.e. the maximum) and freeze it
let clocks = rcc.cfgr.sysclk(168.mhz()).freeze();
// USART2 at PD5 (TX) and PD6(RX)
let txpin = gpiod.pd5.into_alternate_af7();
let rxpin = gpiod.pd6.into_alternate_af7();
let config = serial::config::Config::default()
.baudrate(100_000.bps())
.parity_even()
.wordlength_9()
.stopbits(serial::config::StopBits::STOP2);
let serial = Serial::usart2(p.USART2, (txpin, rxpin), config, clocks).unwrap();
let (mut tx, mut rx) = serial.split();
// Get delay provider
let mut delay = Delay::new(cp.SYST, clocks);
iprintln!(&mut itm.stim[0], "start" );
let mut state = sbus::SbusReadState::default();
loop {
let received = block!(rx.read());
match received {
Ok(c) => {
let complete = sbus::process_char(&mut state, c);
if complete {
iprintln!(&mut itm.stim[0], "{} {}", state.frame.channels[0], state.frame.channels[1] );
}
},
Err(e) => {
iprintln!(&mut itm.stim[0], "err" );
},
}
}
}
loop {}
} |
use std::fmt;
trait Graph<N, E> {
fn has_edge(&self, &N, &N) -> bool;
fn edges(&self, &N) -> Vec<E>;
}
fn distance<N, E, G: Graph<N, E>>(graph: &G, start: &N, end: &N) -> u32 {
0
}
trait Graph_v2 {
type N;
type E;
fn has_edge(&self, &Self::N, &Self::N) -> bool;
fn edges(&self, &Self::N) -> Vec<Self::E>;
}
fn distance_v2<G: Graph_v2>(graph: &G, start: &G::N, end: &G::N) -> u32 {
0
}
struct Node;
struct Edge;
struct MyGraph;
impl Graph_v2 for MyGraph {
type N = Node;
type E = Edge;
fn has_edge(&self, n1: &Node, n2: &Node) -> bool {
true
}
fn edges(&self, n: &Node) -> Vec<Edge> {
Vec::new()
}
}
// won't compile. Don't know associated types
//#[test]
//fn test_failing_trait_object() {
// let graph = MyGraph;
// let obj = Box::new(graph) as Box<Graph_v2>;
//}
#[test]
fn test_associated_type_trait_object() {
let graph = MyGraph;
let obj = Box::new(graph) as Box<Graph_v2<N=Node, E=Edge>>;
}
|
extern crate webplatform;
fn main() {
print!("HELLO FROM RUST");
webplatform::init().element_query("#container").unwrap().html_set("<h1>HELLO FROM RUST</h1>");
}
// Functions that you wish to access from Javascript must be marked as no_mangle
#[no_mangle]
pub fn doub(a: i32) -> i32 {
return a + a
}
|
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0.
/// Type alias to use this library's [`FormatError`] type in a `Result`.
pub type Result<T> = std::result::Result<T, FormatError>;
/// Errors generated from this library.
#[derive(Debug, thiserror::Error)]
pub enum FormatError {
/// The object is not support statistics for a node.
#[error("this obj can't return NodeStat")]
NotSupportStat,
/// Failed to decode block into node.
#[error("decode block into node error")]
DecodeError,
/// Cannot find the decoder corresponding to codec.
#[error("this code has not register decoder: {0:?}")]
DecoderNotRegister(cid::Codec),
/// More than the depth of path.
#[error("depth is larger than path, depth: {0}, path len: {1}")]
DepthError(usize, usize),
/// Depth is not init yet.
#[error("depth is not init yet")]
DepthNotInit,
/// Cannot go down, no child.
#[error("can't go down, the child does not exist, depth: {0}, index: {1}, child: {0}")]
DownNoChild(usize, usize, usize),
/// Cannot go up, already on root.
#[error("can't go up, already on root")]
UpOnRoot,
/// No more child nodes.
#[error("can't go to the next child, no more child nodes in this parent")]
NextNoChild,
/// No child exist at the index.
#[error("child not exist for this index. index: {0}")]
NoChild(usize),
/// Link not found.
#[error("no such link found")]
NoSuchLink,
/// Other error.
#[error("other err: {0}")]
Other(Box<dyn std::error::Error + Send + Sync>),
}
|
use self::diesel::prelude::*;
use actix_web::actix::Handler;
use chrono::Utc;
use diesel::{self, QueryDsl, RunQueryDsl};
use uuid::Uuid;
use crate::model::db::Database;
use crate::model::response::MyError;
use crate::model::{
member::Member,
project::{CreateProject, NewProject, Project, ProjectById, ProjectMembers},
};
impl Handler<ProjectById> for Database {
type Result = Result<Project, MyError>;
fn handle(&mut self, project_by_id: ProjectById, _: &mut Self::Context) -> Self::Result {
match Uuid::parse_str(&project_by_id.project_id) {
Ok(id) => {
use crate::share::schema::projects::dsl;
let conn = &self.connection.get().map_err(|_| MyError::DatabaseError)?;
Ok(dsl::projects
.find(id)
.first::<Project>(conn)
.map_err(|_| MyError::NotFound)?)
}
Err(_e) => Err(MyError::NotFound),
}
}
}
impl Handler<CreateProject> for Database {
type Result = Result<Project, MyError>;
fn handle(&mut self, create_project: CreateProject, _: &mut Self::Context) -> Self::Result {
use crate::share::schema::members::dsl as mdsl;
use crate::share::schema::projects::dsl;
let conn = &self.connection.get().map_err(|_| MyError::DatabaseError)?;
let new_project = NewProject {
id: Uuid::new_v4(),
name: &create_project.name,
archived: false,
created_at: Utc::now().naive_utc(),
};
let project: Project = diesel::insert_into(dsl::projects)
.values(&new_project)
.get_result(conn)
.map_err(|_e| MyError::DatabaseError)?;
let new_member = Member {
user_id: create_project.user.id,
project_id: project.id,
permission: "OWNER".to_string(),
};
let _member: Member = diesel::insert_into(mdsl::members)
.values(&new_member)
.get_result(conn)
.map_err(|_e| MyError::DatabaseError)?;
Ok(project)
}
}
impl Handler<ProjectMembers> for Database {
type Result = Result<Vec<Member>, MyError>;
fn handle(&mut self, project_members: ProjectMembers, _: &mut Self::Context) -> Self::Result {
use crate::share::schema::members::dsl;
let conn = &self.connection.get().map_err(|_| MyError::DatabaseError)?;
Ok(dsl::members
.filter(dsl::project_id.eq(project_members.project.id))
.load::<Member>(conn)
.map_err(|_| MyError::NotFound)?)
}
}
|
use super::Lab;
use std::arch::x86_64::*;
use std::{f32, iter, mem};
use simd::labs_to_rgbs::{lab_slice_to_simd, labs_to_xyzs, xyzs_to_rgbs};
static BLANK_LAB: Lab = Lab {
l: f32::NAN,
a: f32::NAN,
b: f32::NAN,
};
/// Converts a slice of `Lab`s to `[u8; 3]` BGR triples using 256-bit SIMD operations.
///
/// # Panics
/// This function will panic if executed on a non-x86_64 CPU or one without AVX
/// and SSE 4.1 support.
/// ```ignore
/// if is_x86_feature_detected!("avx") && is_x86_feature_detected!("sse4.1") {
/// lab::simd::labs_to_bgrs(&labs);
/// }
/// ```
pub fn labs_to_bgrs(labs: &[Lab]) -> Vec<[u8; 3]> {
let chunks = labs.chunks_exact(8);
let remainder = chunks.remainder();
let mut vs = chunks.fold(Vec::with_capacity(labs.len()), |mut v, labs| {
let bgrs = unsafe { slice_labs_to_slice_bgrs(labs) };
v.extend_from_slice(&bgrs);
v
});
// While we could simplify this block by just calling the scalar version
// of the code on the remainder, there are some variations between scalar
// and SIMD floating point math (especially on TravisCI for some reason?)
// and I don't want the trailing N items to be computed by a different
// algorithm.
if remainder.len() > 0 {
let labs: Vec<Lab> = remainder
.iter()
.cloned()
.chain(iter::repeat(BLANK_LAB))
.take(8)
.collect();
let bgrs = unsafe { slice_labs_to_slice_bgrs(&labs) };
vs.extend_from_slice(&bgrs[..remainder.len()]);
}
vs
}
/// Convert a slice of 8 `Lab` structs into an array of 8 BGR (`[u8; 3]`) triples.
///
/// This is the fundamental unit of work that `lab::simd::labs_to_bgrs` performs.
/// If you need to control how to parallelize this work, use this function.
///
/// Only the first 8 elements of the input slice will be converted. The example given
/// is very close to the implementation of `lab::simd::labs_to_bgrs`. Because this
/// library makes no assumptions about how to parallelize work, use this function
/// to add parallelization with Rayon, etc.
///
/// # Example
/// ```
/// # use lab::Lab;
/// # use std::{iter, f32};
/// # let labs: Vec<Lab> = {
/// # let values: &[[f32; 3]] = &[[0.44953918, 0.2343294, 0.9811987], [0.66558355, 0.86746496, 0.6557031], [0.3853534, 0.5447681, 0.563337], [0.5060024, 0.002653122, 0.28564066], [0.112734795, 0.42281234, 0.5662596], [0.61263186, 0.7541826, 0.7710692], [0.35402274, 0.6711668, 0.090500355], [0.09291971, 0.18202633, 0.27621543], [0.74104124, 0.56239027, 0.6807165], [0.19430345, 0.46403062, 0.31903458], [0.9805223, 0.22615737, 0.6665648], [0.61051553, 0.66672426, 0.2612421]];
/// # values.iter().map(|lab| lab::Lab { l: lab[0], a: lab[1], b: lab[2] }).collect()
/// # };
/// ##[cfg(target_arch = "x86_64")]
/// {
/// if is_x86_feature_detected!("avx") && is_x86_feature_detected!("sse4.1") {
/// let chunks = labs.chunks_exact(8);
/// let remainder = chunks.remainder();
/// // Parallelizing work with Rayon? Do it here, at `.fold()`
/// let mut vs = chunks.fold(Vec::with_capacity(labs.len()), |mut v, labs| {
/// let bgrs = lab::simd::labs_to_bgrs_chunk(labs);
/// v.extend_from_slice(&bgrs);
/// v
/// });
///
/// if remainder.len() > 0 {
/// const BLANK_LAB: Lab = Lab { l: f32::NAN, a: f32::NAN, b: f32::NAN };
/// let labs: Vec<Lab> =
/// remainder.iter().cloned().chain(iter::repeat(BLANK_LAB))
/// .take(8)
/// .collect();
///
/// let bgrs = lab::simd::labs_to_bgrs_chunk(&labs);
/// vs.extend_from_slice(&bgrs[..remainder.len()]);
/// }
/// }
/// }
/// ```
///
/// # Panics
/// This function will panic of the input slice has fewer than 8 elements. Consider
/// padding the input slice with blank values and then truncating the result.
///
/// Additionally, it will panic if run on a CPU that does not support x86_64's AVX
/// and SSE 4.1 instructions.
pub fn labs_to_bgrs_chunk(labs: &[Lab]) -> [[u8; 3]; 8] {
unsafe { slice_labs_to_slice_bgrs(labs) }
}
#[inline]
unsafe fn slice_labs_to_slice_bgrs(labs: &[Lab]) -> [[u8; 3]; 8] {
let (l, a, b) = lab_slice_to_simd(labs);
let (x, y, z) = labs_to_xyzs(l, a, b);
let (r, g, b) = xyzs_to_rgbs(x, y, z);
simd_to_bgr_array(b, g, r)
}
#[inline]
unsafe fn simd_to_bgr_array(b: __m256, g: __m256, r: __m256) -> [[u8; 3]; 8] {
let b: [f32; 8] = mem::transmute(_mm256_round_ps(b, _MM_FROUND_TO_NEAREST_INT));
let g: [f32; 8] = mem::transmute(_mm256_round_ps(g, _MM_FROUND_TO_NEAREST_INT));
let r: [f32; 8] = mem::transmute(_mm256_round_ps(r, _MM_FROUND_TO_NEAREST_INT));
let mut bgrs: [mem::MaybeUninit<[u8; 3]>; 8] = mem::MaybeUninit::uninit().assume_init();
for (((&b, &g), &r), bgr) in b
.iter()
.zip(g.iter())
.zip(r.iter())
.rev()
.zip(bgrs.iter_mut())
{
*bgr = mem::MaybeUninit::new([b as u8, g as u8, r as u8]);
}
mem::transmute(bgrs)
}
// #[cfg(all(target_cpu = "x86_64", target_feature = "avx", target_feature = "sse4.1"))]
#[cfg(test)]
mod test {
use super::super::super::{labs_to_bgrs, simd, Lab};
use rand;
use rand::distributions::Standard;
use rand::Rng;
lazy_static! {
static ref BGRS: Vec<[u8; 3]> = {
let rand_seed = [0u8; 32];
let mut rng: rand::StdRng = rand::SeedableRng::from_seed(rand_seed);
rng.sample_iter(&Standard).take(512).collect()
};
}
#[test]
fn test_simd_labs_to_bgrs() {
let labs = simd::bgrs_to_labs(&BGRS);
let bgrs = simd::labs_to_bgrs(&labs);
assert_eq!(bgrs.as_slice(), BGRS.as_slice());
}
#[test]
fn test_simd_labs_to_bgrs_unsaturated() {
let labs = vec![Lab {
l: 66.6348,
a: 52.260696,
b: 14.850557,
}];
let bgrs_non_simd = labs_to_bgrs(&labs);
let bgrs_simd = simd::labs_to_bgrs(&labs);
assert_eq!(bgrs_simd, bgrs_non_simd);
}
}
|
use std::collections::HashSet;
use std::io;
use std::io::Read;
use std::ops::Add;
#[derive(Hash, PartialEq, Eq, Clone, Copy)]
struct Pos {
x: i8,
y: i8,
}
impl Add for Pos {
type Output = Self;
fn add(self, other: Pos) -> Pos {
Pos {x: self.x + other.x, y: self.y + other.y}
}
}
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
let seats: HashSet<_> = input
.lines()
.zip(0..)
.flat_map(|(line, y)| line.chars().zip(0..).filter_map(move |(tile, x)| {
if tile == 'L' {
Some(Pos {x: x, y: y})
} else {
None
}
}))
.collect();
let adjacent: Vec<_> = (-1..=1)
.flat_map(|x| (-1..=1)
.filter(move |&y| (x, y) != (0, 0))
.map(move |y| Pos {x: x, y: y})
)
.collect();
let seats: Vec<(_, Vec<_>)> = seats.iter().map(|&pos| (pos, adjacent.iter().filter_map(|&delta| {
let adjacent_seat = pos + delta;
if seats.contains(&adjacent_seat) {
Some(adjacent_seat)
} else {
None
}
}).collect())).collect();
let mut filled_seats: Vec<Vec<_>> = input
.lines()
.map(|line| line.chars().map(|_| false).collect())
.collect();
let mut changed = true;
let mut to_remove = Vec::with_capacity(seats.len());
let mut to_add = Vec::with_capacity(seats.len());
while changed {
for (pos, adjacent) in seats.iter() {
let adjacent_filled = adjacent.iter().filter(|&x| filled_seats[x.y as usize][x.x as usize]).count();
let filled = filled_seats[pos.y as usize][pos.x as usize];
if adjacent_filled >= 4 && filled {
to_remove.push(pos);
} else if adjacent_filled == 0 && !filled {
to_add.push(pos);
}
}
changed = to_remove.len() > 0 || to_add.len() > 0;
for &i in &to_remove {
filled_seats[i.y as usize][i.x as usize] = false;
}
for &i in &to_add {
filled_seats[i.y as usize][i.x as usize] = true;
}
to_remove.clear();
to_add.clear();
}
println!("{}", filled_seats.iter().map(|x| x.iter().filter(|&&y| y).count()).sum::<usize>());
}
|
use std::io;
fn main() {
println!("Temprature Converter:");
let temp = loop {
println!("Enter temprature:");
let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read temprature");
let temp: f64 = match temp.trim().parse() {
Ok(num) => num,
Err(_) => {
print!("Invalid input. ");
continue;
}
};
break temp;
};
let unit = loop {
println!("Enter temprature unit `C` or `F`");
let mut unit = String::new();
io::stdin()
.read_line(&mut unit)
.expect("Failed to read unit");
let unit: char = match unit.trim().parse() {
Ok(str) => str,
Err(_) => {
print!("Invalid input. ");
continue;
}
};
if !is_unit_allowed(unit) {
print!("Invalid input. ");
continue;
}
break unit;
};
let converted_temp: f64 = if is_fahrenheit(unit) {
(5.0 / 9.0) * (temp - 32.0)
} else {
((9.0 / 5.0) * (temp)) + 32.0
};
print!("Converted temprature is {} : ", converted_temp);
}
fn is_celsius(unit: char) -> bool {
const C_UNITS: [char; 2] = ['C', 'c'];
C_UNITS.contains(&unit)
}
fn is_fahrenheit(unit: char) -> bool {
const F_UNITS: [char; 2] = ['F', 'f'];
F_UNITS.contains(&unit)
}
fn is_unit_allowed(unit: char) -> bool {
is_celsius(unit) || is_fahrenheit(unit)
}
|
//! Construct planar sheets.
use surface::LatticeType;
use surface::Sheet;
use coord::{Coord, Direction, Translate};
use describe::{unwrap_name, Describe};
use error::Result;
use iterator::{ResidueIter, ResidueIterOut};
use system::*;
use std::fmt;
use std::fmt::{Display, Formatter};
impl_component![Cuboid];
impl_translate![Cuboid];
bitflags! {
#[derive(Deserialize, Serialize)]
/// Sides of a cuboid box.
pub struct Sides: u8 {
const X0 = 0b00000001;
const X1 = 0b00000010;
const Y0 = 0b00000100;
const Y1 = 0b00001000;
const Z0 = 0b00010000;
const Z1 = 0b00100000;
}
}
impl Display for Sides {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.contains(Sides::X0) {
write!(f, "X0")?;
}
if self.contains(Sides::X1) {
write!(f, "X1")?;
}
if self.contains(Sides::Y0) {
write!(f, "Y0")?;
}
if self.contains(Sides::Y1) {
write!(f, "Y1")?;
}
if self.contains(Sides::Z0) {
write!(f, "Z0")?;
}
if self.contains(Sides::Z1) {
write!(f, "Z1")?;
}
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
/// A cuboid surface. All sides will be created to exactly match multiples of the lattice spacing.
pub struct Cuboid {
/// Name of component.
pub name: Option<String>,
/// Optional residue placed at each coordinate. If not set the sheet describes
/// a general collection of coordinates.
pub residue: Option<Residue>,
/// Lattice type used to construct the surface structure.
pub lattice: LatticeType,
/// Standard deviation along z of coordinates. Added to the coordinates when `construct`
/// is called.
pub std_z: Option<f64>,
#[serde(skip)]
/// Origin of the sheet. Located in the lower-left position of it.
pub origin: Coord,
#[serde(skip)]
/// Size of cuboid box.
pub size: Coord,
/// Sides that are added for the box. Is a `bitflag` struct.
pub sides: Sides,
#[serde(skip)]
/// List of coordinates belonging to the sheet. Relative to the `origin`.
pub coords: Vec<Coord>,
}
fn translate_coordinate_list(coords: &[Coord], translate: Coord) -> Vec<Coord> {
coords.iter().map(|&c| c + translate).collect()
}
impl Cuboid {
/// Construct the cuboid coordinates and return the object.
///
/// # Errors
/// Returns an error if either the length or width is non-positive.
pub fn construct(self) -> Result<Cuboid> {
let sheet_base = Sheet {
name: None,
residue: None,
lattice: self.lattice.clone(),
std_z: self.std_z,
origin: Coord::ORIGO,
normal: Direction::X,
length: 0.0,
width: 0.0,
coords: Vec::new(),
};
let mut coords: Vec<Coord> = Vec::new();
let (dx_target, dy_target, dz_target) = self.size.to_tuple();
let sheet_yz = Sheet {
normal: Direction::X,
length: dz_target,
width: dy_target,
.. sheet_base.clone()
}.construct()?.with_pbc();
let sheet_xz = Sheet {
normal: Direction::Y,
length: dx_target,
width: dz_target,
.. sheet_base.clone()
}.construct()?.with_pbc();
let sheet_xy = Sheet {
normal: Direction::Z,
length: dx_target,
width: dy_target,
.. sheet_base.clone()
}.construct()?.with_pbc();
let (dx, dy, dz) = (sheet_xy.length, sheet_xy.width, sheet_yz.length);
if self.sides.contains(Sides::X0) {
coords.extend_from_slice(&sheet_yz.coords);
}
if self.sides.contains(Sides::X1) {
let dr = Coord::new(dx, 0.0, 0.0);
coords.extend_from_slice(&translate_coordinate_list(&sheet_yz.coords, dr));
}
if self.sides.contains(Sides::Y0) {
coords.extend_from_slice(&sheet_xz.coords);
}
if self.sides.contains(Sides::Y1) {
let dr = Coord::new(0.0, dy, 0.0);
coords.extend_from_slice(&translate_coordinate_list(&sheet_xz.coords, dr));
}
if self.sides.contains(Sides::Z0) {
coords.extend_from_slice(&sheet_xy.coords);
}
if self.sides.contains(Sides::Z1) {
let dr = Coord::new(0.0, 0.0, dz);
coords.extend_from_slice(&translate_coordinate_list(&sheet_xy.coords, dr));
}
Ok(Cuboid {
coords,
size: Coord::new(dx, dy, dz),
.. self
})
}
/// Calculate the box size.
fn calc_box_size(&self) -> Coord {
self.size
}
}
impl Describe for Cuboid {
fn describe(&self) -> String {
format!("{} (Surface box of size {} at {})",
unwrap_name(&self.name), self.size, self.origin)
}
fn describe_short(&self) -> String {
format!("{} (Surface box)", unwrap_name(&self.name))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn setup_sheets_and_cuboid_base(dx: f64, dy: f64, dz: f64, lattice: LatticeType)
-> (Sheet, Sheet, Sheet, Cuboid) {
let size = Coord::new(dx, dy, dz);
// Create sheets of the box in each direction to compare against.
let sheet_base = Sheet {
name: None,
residue: None,
std_z: None,
origin: Coord::ORIGO,
lattice: lattice.clone(),
normal: Direction::X,
length: 0.0,
width: 0.0,
coords: Vec::new(),
};
let sheet_xy = Sheet {
normal: Direction::Z,
length: dx,
width: dy,
.. sheet_base.clone()
}.construct().unwrap().with_pbc();
assert!(!sheet_xy.coords.is_empty());
let sheet_xz = Sheet {
normal: Direction::Y,
length: dx,
width: dz,
.. sheet_base.clone()
}.construct().unwrap().with_pbc();
assert!(!sheet_xz.coords.is_empty());
let sheet_yz = Sheet {
normal: Direction::X,
length: dz,
width: dy,
.. sheet_base.clone()
}.construct().unwrap().with_pbc();
assert!(!sheet_yz.coords.is_empty());
// Now create the cuboids with the six different faces and ensure that the coordinates
// match the sheets.
let cuboid_base = Cuboid {
name: None,
residue: None,
lattice: lattice.clone(),
std_z: None,
origin: Coord::ORIGO,
size: size,
sides: Sides::empty(),
coords: Vec::new(),
};
(sheet_xy, sheet_xz, sheet_yz, cuboid_base)
}
#[test]
fn box_is_created_with_set_sides_that_are_translated() {
let (dx, dy, dz) = (3.0, 5.0, 7.0);
let lattice = LatticeType::Hexagonal { a: 0.57 };
let (sheet_xy, sheet_xz, sheet_yz, cuboid_base) = setup_sheets_and_cuboid_base(
dx, dy, dz, lattice);
let cuboid_x0 = Cuboid {
sides: Sides::X0,
.. cuboid_base.clone()
}.construct().unwrap();
assert_eq!(cuboid_x0.coords, sheet_yz.coords);
let cuboid_x1 = Cuboid {
sides: Sides::X1,
.. cuboid_base.clone()
}.construct().unwrap();
// Compare the further away side by translating the sheet coordinates accordingly.
// Note that they are translated using the *output* side size, since this may not
// match the input due to the lattice construction!
let dr = Coord::new(sheet_xy.length, 0.0, 0.0);
for (&c0, &c1) in cuboid_x1.coords.iter().zip(sheet_yz.coords.iter()) {
assert_eq!(c0, c1 + dr);
}
let cuboid_y0 = Cuboid {
sides: Sides::Y0,
.. cuboid_base.clone()
}.construct().unwrap();
assert_eq!(cuboid_y0.coords, sheet_xz.coords);
let cuboid_y1 = Cuboid {
sides: Sides::Y1,
.. cuboid_base.clone()
}.construct().unwrap();
let dr = Coord::new(0.0, sheet_xy.width, 0.0);
for (&c0, &c1) in cuboid_y1.coords.iter().zip(sheet_xz.coords.iter()) {
assert_eq!(c0, c1 + dr);
}
let cuboid_z0 = Cuboid {
sides: Sides::Z0,
.. cuboid_base.clone()
}.construct().unwrap();
assert_eq!(cuboid_z0.coords, sheet_xy.coords);
let cuboid_z1 = Cuboid {
sides: Sides::Z1,
.. cuboid_base.clone()
}.construct().unwrap();
let dr = Coord::new(0.0, 0.0, sheet_yz.length);
for (&c0, &c1) in cuboid_z1.coords.iter().zip(sheet_xy.coords.iter()) {
assert_eq!(c0, c1 + dr);
}
}
#[test]
fn box_with_several_set_sides_has_matching_number_of_coordinates() {
let (dx, dy, dz) = (3.0, 5.0, 7.0);
let lattice = LatticeType::Hexagonal { a: 0.57 };
let (_, sheet_xz, sheet_yz, cuboid_base)
= setup_sheets_and_cuboid_base(dx, dy, dz, lattice);
let cuboid = Cuboid {
sides: Sides::X0 | Sides::X1 | Sides::Y0,
.. cuboid_base
}.construct().unwrap();
assert_eq!(cuboid.coords.len(), 2 * sheet_yz.coords.len() + sheet_xz.coords.len());
}
#[test]
fn box_from_sheets_has_box_size_matching_the_lattice() {
let (dx_target, dy_target, dz_target) = (3.0, 5.0, 7.0);
let lattice = LatticeType::Hexagonal { a: 0.57 };
let (sheet_xy, _, sheet_yz, cuboid_base) = setup_sheets_and_cuboid_base(
dx_target, dy_target, dz_target, lattice);
// The final box size will be that of the sheets
let size = Coord::new(sheet_xy.length, sheet_xy.width, sheet_yz.length);
let cuboid = cuboid_base.construct().unwrap();
assert_eq!(cuboid.size, size);
assert_eq!(cuboid.calc_box_size(), size);
}
#[test]
fn creating_a_box_respects_the_set_stdz_value() {
let (dx_target, dy_target, dz_target) = (3.0, 5.0, 7.0);
let lattice = LatticeType::Hexagonal { a: 0.57 };
let (sheet_xy, _, _, cuboid_base) = setup_sheets_and_cuboid_base(
dx_target, dy_target, dz_target, lattice);
// Create a cuboid with a side in the (lower) xy plane
let cuboid_z0 = Cuboid {
std_z: Some(2.0),
sides: Sides::Z0,
.. cuboid_base
}.construct().unwrap();
assert!(!cuboid_z0.coords
.iter()
.zip(sheet_xy.coords.iter())
.all(|(&c0, &c1)| c0.z == c1.z)
);
}
}
|
pub mod command;
pub mod response_handling;
use anyhow::Result;
use teloxide::types::{CallbackQuery, PollAnswer};
use teloxide::{
prelude::*,
types::{InlineKeyboardButtonKind, MessageKind},
};
use self::{
command::Command,
response_handling::perform_reponse_to_callback_query,
response_handling::{
perform_reponse_to_poll_answer, perform_response_to_command, send_challenge_updates,
send_user_task_polls,
},
};
use crate::{action_handling::perform_action, config};
use crate::{
database::{challenge_data::ChallengeData, task_data::TaskData},
response::Response,
};
use crate::{action::Action, time_frame::TimeFrame};
use std::sync::atomic::AtomicU64;
use lazy_static::lazy_static;
use tokio::{
join,
time::{delay_for, Duration},
};
lazy_static! {
static ref MESSAGES_TOTAL: AtomicU64 = AtomicU64::new(0);
}
#[tokio::main]
pub async fn run_bot() -> Result<()> {
teloxide::enable_logging!();
log::info!("Starting deshittify_bot...");
let bot = Bot::from_env();
let bot_name = "deshittify";
let user_task_poll_sender = user_task_polls_send_thread(Bot::from_env());
let challenge_status_update_sender = challenge_updates_send_thread(Bot::from_env());
let dispatcher = Dispatcher::new(bot)
.messages_handler(move |rx: DispatcherHandlerRx<Message>| {
rx.commands(bot_name).for_each(|(cx, command)| async move {
handle_command(cx, command).await.log_on_error().await;
})
})
.callback_queries_handler(move |rx: DispatcherHandlerRx<CallbackQuery>| {
rx.for_each(|cx| async move {
handle_callback_query(cx).await.log_on_error().await;
})
})
.poll_answers_handler(move |rx: DispatcherHandlerRx<PollAnswer>| {
rx.for_each(|cx| async move {
handle_poll(cx).await.log_on_error().await;
})
});
let handler = dispatcher.dispatch();
let (res1, res2, _) = join!(
user_task_poll_sender,
challenge_status_update_sender,
handler
);
res1?;
res2?;
Ok(())
}
async fn challenge_updates_send_thread(bot: Bot) -> Result<()> {
loop {
let response = perform_action(&Action::CheckDateMaybeSendChallengeUpdates);
if let Response::ChallengeUpdates(user_task_data) = response {
let action = send_challenge_updates(&bot, &user_task_data).await?;
perform_action(&action);
}
delay_for(Duration::from_secs(config::DATE_CHECK_TIMEOUT_SECS)).await;
}
}
async fn user_task_polls_send_thread(bot: Bot) -> Result<()> {
loop {
let response = perform_action(&Action::CheckDateMaybeSendPolls);
if let Response::TaskPolls(user_task_data) = response {
let action = send_user_task_polls(&bot, &user_task_data).await?;
perform_action(&action);
}
delay_for(Duration::from_secs(config::DATE_CHECK_TIMEOUT_SECS)).await;
}
}
async fn handle_command(message: UpdateWithCx<Message>, command: Command) -> Result<()> {
let action = convert_message_to_action(&message, command)
.unwrap_or_else(|err| Action::ErrorMessage(format!("Error: {}", err.to_string())));
let response = perform_action(&action);
let maybe_action = perform_response_to_command(&response, &message).await?;
if let Some(new_action) = maybe_action {
perform_action(&new_action);
}
Ok(())
}
async fn handle_callback_query(message: UpdateWithCx<CallbackQuery>) -> Result<()> {
let action = convert_callback_query_to_action(&message)
.unwrap_or_else(|err| Action::ErrorMessage(format!("Error: {}", err.to_string())));
let response = perform_action(&action);
perform_reponse_to_callback_query(&response, &message).await
}
async fn handle_poll(message: UpdateWithCx<PollAnswer>) -> Result<()> {
let action = convert_poll_to_action(&message)
.unwrap_or_else(|err| Action::ErrorMessage(format!("Error: {}", err.to_string())));
let response = perform_action(&action);
perform_reponse_to_poll_answer(&response, &message).await
}
fn convert_callback_query_to_action(message: &UpdateWithCx<CallbackQuery>) -> Result<Action> {
if let MessageKind::Common(x) = &message.update.message.as_ref().unwrap().kind {
if let InlineKeyboardButtonKind::CallbackData(data) =
&x.reply_markup.as_ref().unwrap().inline_keyboard[0][0].kind
{
let challenge_id: i32 = data.parse()?;
let user_id = message.update.from.id;
let user_name = message.update.from.first_name.clone();
return Ok(Action::SubscribeToChallenge(
user_id,
challenge_id,
user_name,
));
}
};
unimplemented!()
}
fn convert_poll_to_action(message: &UpdateWithCx<PollAnswer>) -> Result<Action> {
let poll_id = &message.update.poll_id;
let poll_options = message.update.option_ids.clone();
Ok(Action::ModifyUserTaskTimestamps(
poll_id.clone(),
poll_options,
))
}
fn convert_message_to_action(message: &UpdateWithCx<Message>, command: Command) -> Result<Action> {
match command {
Command::Help => Ok(Action::SendHelp),
Command::CreateNewChallenge { name, start, end } => {
Ok(Action::CreateNewChallenge(ChallengeData {
name,
time_frame: TimeFrame::new(start, end),
}))
}
Command::AddTask {
challenge_name,
task_name,
count,
period,
} => Ok(Action::AddTask(
message.update.from().unwrap().id,
challenge_name,
TaskData {
name: task_name,
count,
period,
},
)),
Command::Signup => {
if message.update.chat.is_private() {
let user = message.update.from().unwrap();
Ok(Action::SignupUser(
user.id,
message.update.chat.id,
user.first_name.clone(),
))
} else {
Ok(Action::ErrorMessage(
"You can't sign up in groups. Please sign up with @deshittify_bot directly."
.to_owned(),
))
}
}
Command::SendPoll => Ok(Action::CheckDateMaybeSendPolls),
Command::SendUpdates => Ok(Action::CheckDateMaybeSendChallengeUpdates),
}
}
|
use ::game::player::Player;
pub trait Item {
fn new() -> Self;
fn save();
fn restore();
fn spawn();
fn attributes();
fn give_to_player(player: &mut Player) -> bool;
fn pickup(player: &mut Player) -> bool;
}
|
use crate::pixel::Pixel;
use sdl2::render::WindowCanvas;
use sdl2::EventPump;
use sdl2::Sdl;
pub struct Display {
pub context: Sdl,
canvas: WindowCanvas,
event_pump: EventPump,
pixels: Vec<Pixel>,
width: u32,
height: u32,
}
pub struct DisplayBuilder {
name: String,
width: u32,
height: u32,
pixel_size: u32,
margin_x: u32,
margin_y: u32,
}
impl Display {
pub fn refresh(&mut self) {
for pixel in &self.pixels {
self.canvas.set_draw_color(pixel.color().clone());
self.canvas.fill_rect(pixel.rect().clone()).unwrap();
}
self.canvas.present();
}
pub fn get_event_pump(&mut self) -> &mut EventPump {
&mut self.event_pump
}
pub fn pixel_at(&mut self, x: u32, y: u32) -> &mut Pixel {
&mut self.pixels[(y * self.width + x % self.width) as usize]
}
pub fn from_buffer(&mut self, buffer: &[(u8, u8, u8)]) {
for i in 0..self.pixels.len() {
self.pixels[i].set_color_rgb(buffer[i]);
}
}
pub fn height(&self) -> u32 {
self.height
}
pub fn width(&self) -> u32 {
self.width
}
}
impl DisplayBuilder {
pub fn new(name: &str, width: u32, height: u32, pixel_size: u32) -> Self {
Self {
name: String::from(name),
width: width,
height: height,
margin_x: 0,
margin_y: 0,
pixel_size: pixel_size,
}
}
pub fn with_margin(&mut self, margin_x: u32, margin_y: u32) -> &mut Self {
self.margin_x = margin_x;
self.margin_y = margin_y;
self
}
pub fn build(&self) -> Result<Display, Box<dyn std::error::Error>> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let win_width = self.width * self.pixel_size + 2 * self.margin_x;
let win_height = self.height * self.pixel_size + 2 * self.margin_y;
let window = video_subsystem
.window(&self.name, win_width, win_height)
.position_centered()
.build()?;
let mut canvas = window.into_canvas().build()?;
let event_pump = sdl_context.event_pump()?;
canvas.clear();
Ok(Display {
context: sdl_context,
canvas: canvas,
event_pump: event_pump,
pixels: self.make_pixel_grid(),
width: self.width,
height: self.height,
})
}
fn make_pixel_grid(&self) -> Vec<Pixel> {
let mut pixels = Vec::with_capacity((self.height * self.width) as usize);
for j in 0..self.height {
for i in 0..self.width {
pixels.push(Pixel::new(
i * self.pixel_size + self.margin_x,
j * self.pixel_size + self.margin_y,
self.pixel_size,
));
}
}
pixels
}
}
|
use crate::{
config::{cache_duration, serve_mode, ServeMode},
database::get_connection,
errors::QSParseError,
feed_generator::FeedGenerator,
responses,
source::Source,
utils::{now, NabuResult},
};
use actix_web::{HttpRequest, HttpResponse};
use atom_syndication::{Feed, FixedDateTime, Generator};
use log::error;
use serde_json::Value;
#[derive(Clone)]
pub struct FeedWorker {
pub prefix: String,
pub path: String,
pub clean_query_string: fn(&str) -> NabuResult<Value>,
pub update_by_value: fn(Value) -> NabuResult<Feed>,
}
impl FeedWorker {
pub fn new<T: FeedGenerator>(source: &Source, _: T) -> Self {
let prefix = source
.prefix
.split('/')
.filter(|x| !x.is_empty())
.collect::<Vec<&str>>()
.join("/");
let path = T::PATH
.split('/')
.filter(|x| !x.is_empty())
.collect::<Vec<&str>>()
.join("/");
FeedWorker {
prefix,
path,
clean_query_string: T::clean_query_string,
update_by_value: T::update_by_value,
}
}
pub fn get_cache(&self, info: &Value) -> NabuResult<Option<Feed>> {
let query_result = get_connection()?
.query(r"SELECT updated_time, content FROM fetch_cache WHERE prefix=$1 AND path=$2 AND info@> $3 AND info<@ $3 limit 1", &[
&self.prefix, &self.path, info
])?;
if query_result.is_empty() {
return Ok(None);
}
let row = query_result.get(0);
let updated_time: FixedDateTime = row.get(0);
let content: Value = row.get(1);
let feed = ::serde_json::from_value::<Feed>(content)?;
if now().signed_duration_since(updated_time).to_std()? > cache_duration() {
Ok(None)
} else {
Ok(Some(feed))
}
}
pub fn put_cache(&self, info: &Value, feed: &Feed) -> NabuResult<()> {
let content = ::serde_json::to_value(feed)?;
get_connection()?.execute(
r#"INSERT INTO fetch_cache(prefix, path, info, content)
VALUES ($1, $2, $3, $4)
ON CONFLICT ON CONSTRAINT logic_unique_key DO UPDATE
SET content=$4"#,
&[&self.prefix, &self.path, info, &content],
)?;
Ok(())
}
pub fn into_actix_web_handler(self) -> impl Fn(&HttpRequest) -> HttpResponse {
move |request: &HttpRequest| {
let query_string = request.query_string();
let value = match (self.clean_query_string)(query_string) {
Ok(value) => value,
Err(error) => match error.downcast::<QSParseError>() {
Ok(parse_error) => {
error!("{:?}", parse_error);
return responses::parse_query_string_failed();
}
Err(unexpected_error) => {
error!("{:?}", unexpected_error);
return responses::unexpected_error();
}
},
};
if serve_mode() != ServeMode::Dev {
// Logic for get cache
match self.get_cache(&value) {
Ok(cache_option) => {
if let Some(cache) = cache_option {
return responses::cache_hit(cache.to_string());
}
}
Err(unexpected_error) => {
error!("{:?}", unexpected_error);
return responses::unexpected_error();
}
}
}
match (self.update_by_value)(value.clone()) {
Ok(mut feed) => {
feed.set_generator(Some(Generator {
value: "Nabu".to_string(),
uri: Some("https://github.com/DCjanus/nabu".to_string()),
version: None,
}));
if let Err(put_cache_error) = self.put_cache(&value, &feed) {
error!("{:?}", put_cache_error);
}
responses::feed_created(feed.to_string())
}
Err(update_error) => {
error!("{:?}", update_error);
responses::unexpected_error()
}
}
}
}
}
|
#[doc = "Reader of register PLL2DIVR"]
pub type R = crate::R<u32, super::PLL2DIVR>;
#[doc = "Writer for register PLL2DIVR"]
pub type W = crate::W<u32, super::PLL2DIVR>;
#[doc = "Register PLL2DIVR `reset()`'s with value 0x0101_0280"]
impl crate::ResetValue for super::PLL2DIVR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0101_0280
}
}
#[doc = "Reader of field `DIVN2`"]
pub type DIVN2_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `DIVN2`"]
pub struct DIVN2_W<'a> {
w: &'a mut W,
}
impl<'a> DIVN2_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01ff) | ((value as u32) & 0x01ff);
self.w
}
}
#[doc = "Reader of field `DIVP2`"]
pub type DIVP2_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DIVP2`"]
pub struct DIVP2_W<'a> {
w: &'a mut W,
}
impl<'a> DIVP2_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7f << 9)) | (((value as u32) & 0x7f) << 9);
self.w
}
}
#[doc = "Reader of field `DIVQ2`"]
pub type DIVQ2_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DIVQ2`"]
pub struct DIVQ2_W<'a> {
w: &'a mut W,
}
impl<'a> DIVQ2_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7f << 16)) | (((value as u32) & 0x7f) << 16);
self.w
}
}
#[doc = "Reader of field `DIVR2`"]
pub type DIVR2_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DIVR2`"]
pub struct DIVR2_W<'a> {
w: &'a mut W,
}
impl<'a> DIVR2_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7f << 24)) | (((value as u32) & 0x7f) << 24);
self.w
}
}
impl R {
#[doc = "Bits 0:8 - Multiplication factor for PLL1 VCO"]
#[inline(always)]
pub fn divn2(&self) -> DIVN2_R {
DIVN2_R::new((self.bits & 0x01ff) as u16)
}
#[doc = "Bits 9:15 - PLL1 DIVP division factor"]
#[inline(always)]
pub fn divp2(&self) -> DIVP2_R {
DIVP2_R::new(((self.bits >> 9) & 0x7f) as u8)
}
#[doc = "Bits 16:22 - PLL1 DIVQ division factor"]
#[inline(always)]
pub fn divq2(&self) -> DIVQ2_R {
DIVQ2_R::new(((self.bits >> 16) & 0x7f) as u8)
}
#[doc = "Bits 24:30 - PLL1 DIVR division factor"]
#[inline(always)]
pub fn divr2(&self) -> DIVR2_R {
DIVR2_R::new(((self.bits >> 24) & 0x7f) as u8)
}
}
impl W {
#[doc = "Bits 0:8 - Multiplication factor for PLL1 VCO"]
#[inline(always)]
pub fn divn2(&mut self) -> DIVN2_W {
DIVN2_W { w: self }
}
#[doc = "Bits 9:15 - PLL1 DIVP division factor"]
#[inline(always)]
pub fn divp2(&mut self) -> DIVP2_W {
DIVP2_W { w: self }
}
#[doc = "Bits 16:22 - PLL1 DIVQ division factor"]
#[inline(always)]
pub fn divq2(&mut self) -> DIVQ2_W {
DIVQ2_W { w: self }
}
#[doc = "Bits 24:30 - PLL1 DIVR division factor"]
#[inline(always)]
pub fn divr2(&mut self) -> DIVR2_W {
DIVR2_W { w: self }
}
}
|
use frame_system as system;
use frame_support::assert_ok;
use move_core_types::identifier::Identifier;
use move_core_types::language_storage::ModuleId;
use move_core_types::language_storage::StructTag;
use move_vm::data::*;
use move_vm_runtime::data_cache::RemoteCache;
use serde::Deserialize;
use sp_mvm::storage::MoveVmStorage;
mod common;
use common::assets::*;
use common::mock::*;
use common::utils::*;
#[derive(Deserialize)]
struct StoreU64 {
pub val: u64,
}
fn call_publish_module(signer: <Test as system::Trait>::AccountId, bc: Vec<u8>, mod_name: &str) {
let origin = Origin::signed(signer);
// execute VM for publish module:
let result = Mvm::publish(origin, bc.clone());
eprintln!("publish_module result: {:?}", result);
assert_ok!(result);
// check storage:
let module_id = ModuleId::new(to_move_addr(signer), Identifier::new(mod_name).unwrap());
let storage = Mvm::move_vm_storage();
let oracle = MockOracle(None);
let state = State::new(storage, oracle);
assert_eq!(bc, state.get_module(&module_id).unwrap().unwrap());
}
fn call_execute_script_tx_block(origin: Origin, tx: UserTx) {
let txbc = tx.bc().to_vec();
let result = Mvm::execute(origin, txbc);
eprintln!("execute_script result: {:?}", result);
assert_ok!(result);
}
fn check_storage_block(expected: u64) {
let store = Mvm::move_vm_storage();
let oracle = MockOracle(None);
let state = State::new(store, oracle);
let tag = StructTag {
address: origin_move_addr(),
module: Identifier::new(UserMod::Store.name()).unwrap(),
name: Identifier::new("U64").unwrap(),
type_params: vec![],
};
let blob = state
.get_resource(&origin_move_addr(), &tag)
.unwrap()
.unwrap();
let store: StoreU64 = lcs::from_bytes(&blob).unwrap();
assert_eq!(expected, store.val);
}
#[test]
fn execute_store_block() {
new_test_ext().execute_with(|| {
let root = root_ps_acc();
let origin = origin_ps_acc();
let signer = Origin::signed(origin);
let block = StdMod::Block;
let store = UserMod::Store;
call_publish_module(root, block.bc().to_vec(), block.name());
call_publish_module(origin, store.bc().to_vec(), store.name());
const EXPECTED: u64 = 3;
for _ in 0..EXPECTED {
roll_next_block();
}
call_execute_script_tx_block(signer, UserTx::StoreSysBlock);
check_storage_block(EXPECTED);
});
}
#[test]
fn execute_store_time() {
new_test_ext().execute_with(|| {
let root = root_ps_acc();
let origin = origin_ps_acc();
let signer = Origin::signed(origin);
let time = StdMod::Time;
let store = UserMod::Store;
call_publish_module(root, time.bc().to_vec(), time.name());
call_publish_module(origin, store.bc().to_vec(), store.name());
const EXPECTED: u64 = 3;
for _ in 0..EXPECTED {
roll_next_block();
}
call_execute_script_tx_block(signer, UserTx::StoreSysTime);
check_storage_block(EXPECTED * TIME_BLOCK_MULTIPLIER);
});
}
|
#![feature(test)]
#![feature(nll)]
extern crate test;
pub mod scheme;
#[cfg(test)]
mod tests {
use test::Bencher;
use scheme::interpreter::Interpreter;
use scheme::value::Sexp::*;
use scheme::error::LispError::*;
#[test]
fn it_works() {
let mut interp = Interpreter::new();
assert_eq!(Ok(Number(123)), interp.eval_string("(+ 1 2 (* 3 4 5 (- 6 -7 (/ 9 3) 8)))"));
assert_eq!(Ok(True), interp.eval_string("(< 1 2)"));
assert_eq!(Ok(False), interp.eval_string("(pair? '())"));
}
#[test]
fn list() {
let mut interp = Interpreter::new();
assert_eq!(Ok(Nil), interp.eval_string("'()"));
assert_eq!(Ok(Number(2)), interp.eval_string("'(. 2)"));
assert_eq!(Ok(Symbol("a".to_string())), interp.eval_string("(car '(a))"));
assert_eq!(Ok(Nil), interp.eval_string("(cdr '(a))"));
assert_eq!(interp.eval_string("'(a b c . d)"), interp.eval_string("(cons 'a (cons 'b (cons 'c 'd)))"));
assert_eq!(Ok(Number(3)), interp.eval_string("(car (cdr (car (cdr '(1 (2 3) 4 5)))))"));
assert_eq!(interp.eval_string("'(1 2 3 quote (4 5 . 6))"), interp.eval_string("(cons 1 '(2 . (3 . '(4 5 . 6))))"));
}
#[test]
fn lambda() {
let mut interp = Interpreter::new();
// equivalent to (list a b c)
assert_eq!(Ok(List(Box::new(vec![Number(1), Number(2), Number(3), Nil]))), interp.eval_string("((lambda x x) 1 2 3)"));
assert_eq!(Ok(Number(1)), interp.eval_string("((lambda (a b . x) a) 1 2 3)"));
assert_eq!(Ok(Number(2)), interp.eval_string("((lambda (a b . x) b) 1 2 3)"));
assert_eq!(Ok(List(Box::new(vec![Number(3), Nil]))), interp.eval_string("((lambda (a b . x) x) 1 2 3)"));
}
#[test]
fn closure1() {
let mut interp = Interpreter::new();
interp.eval_string("(define (addn n) (lambda (x) (+ x n)))").unwrap();
assert_eq!(Ok(Number(30)), interp.eval_string("((addn 10) 20)"));
assert_eq!(Err(Undefined("x".to_owned())), interp.eval_string("x"));
assert_eq!(Err(Undefined("n".to_owned())), interp.eval_string("n"));
}
#[test]
fn closure2() {
let mut interp = Interpreter::new();
interp.eval_string("(define f (lambda (a) (+ a b)))").unwrap();
interp.eval_string("(define b 10)").unwrap();
assert_eq!(Ok(Number(30)), interp.eval_string("(f 20)"));
}
#[test]
fn clsoure3() {
let mut interp = Interpreter::new();
interp.eval_string("(define func +)").unwrap();
interp.eval_string("(define (foo func) (lambda (a b) (func a b)))").unwrap();
assert_eq!(Ok(Number(2)), interp.eval_string("((foo *) 1 2)"));
}
#[test]
fn closure4() {
let mut interp = Interpreter::new();
interp.eval_string("(define a 1)").unwrap();
interp.eval_string("((lambda (x) (define a 2) (+ x a)) 2)").unwrap();
assert_eq!(Ok(Number(1)), interp.eval_string("a"));
}
#[bench]
fn bench_add_two(b: &mut Bencher) {
let mut interp = Interpreter::new();
b.iter(|| interp.eval_string("(+ 1 2)"));
}
#[bench]
fn bench_is_pair(b: &mut Bencher) {
let mut interp = Interpreter::new();
b.iter(|| interp.eval_string("(pair? '())"));
}
}
|
//! LP55231
//!
//! This is a driver for the [TI LP55231](http://www.ti.com/product/LP55231) RGB LED controller IC
//! using the [`embedded_hal`](https://github.com/rust-embedded/embedded-hal/) traits.
//!
//! NOTE that this driver is not yet platform agnostic, as it relies on `cortex_m` for a delay.
//!
//! This driver optionally takes a [digital output
//! pin](https://docs.rs/embedded-hal/0.2.1/embedded_hal/digital/trait.OutputPin.html) to control
//! power to the LP55231. It will drive the pin (digital) high on power-on, and (digital) low on
//! power-off.
#![no_std]
#![deny(missing_docs)]
extern crate embedded_hal as hal;
#[macro_use]
extern crate bitflags;
use core::fmt::Debug;
use hal::blocking::i2c::{Write, WriteRead};
use hal::digital::OutputPin;
pub mod registers;
use registers as reg;
#[derive(Debug)]
/// Error conditions returned by the LP55231
pub enum Error<I> {
/// The LP is not currently enabled
NotEnabled,
/// Generic I2c error
I2cError(I),
}
#[derive(Copy, Clone)]
/// Available I2C addresses for the part
pub enum Addr {
/// ASEL1=GND, ASEL2=GND
_0x32,
/// ASEL1=GND, ASEL2=VEN
_0x33,
/// ASEL1=VEN, ASEL2=GND
_0x34,
/// ASEL1=VEN, ASEL2=VEN
_0x35,
}
impl From<Addr> for u8 {
fn from(a: Addr) -> Self {
match a {
Addr::_0x32 => 0x32_u8,
Addr::_0x33 => 0x33_u8,
Addr::_0x34 => 0x34_u8,
Addr::_0x35 => 0x35_u8,
}
}
}
#[derive(Debug, Copy, Clone)]
/// Enumeration of the 9 LED lines from the chip
pub enum D {
/// LED line D1
D1,
/// LED line D2
D2,
/// LED line D3
D3,
/// LED line D4
D4,
/// LED line D5
D5,
/// LED line D6
D6,
/// LED line D7
D7,
/// LED line D8
D8,
/// LED line D9
D9,
}
impl From<D> for u8 {
fn from(d: D) -> Self {
match d {
D::D1 => 0,
D::D2 => 1,
D::D3 => 2,
D::D4 => 3,
D::D5 => 4,
D::D6 => 5,
D::D7 => 6,
D::D8 => 7,
D::D9 => 8,
}
}
}
/// The LP55231 device
pub struct Lp55231<I, P> {
/// The owned I2C bus
i2c: I,
/// The owned enable pin
en_pin: Option<P>,
/// The I2C address of this device
addr: u8,
/// Has the LP55231 been enabled
en: bool,
}
impl<E, I, P> Lp55231<I, P>
where
E: Debug,
I: Write<Error = E> + WriteRead<Error = E>,
P: OutputPin,
{
/// Create a new instance of an LP55231 that exclusively owns its I2C bus. Optionally takes a
/// power control pin.
pub fn new(i2c: I, en_pin: Option<P>, addr: Addr) -> Self {
Lp55231 {
i2c,
en_pin,
addr: u8::from(addr) << 1,
en: false,
}
}
/// Convenience method to call `self.i2c.write` with `self.addr`
fn send(&mut self, bytes: &[u8]) -> Result<(), Error<E>> {
if self.en {
self.i2c.write(self.addr, bytes).map_err(|e| Error::I2cError(e))
} else {
Err(Error::NotEnabled)
}
}
/// Enable the device for use
///
/// Sets the enable line high, then sends an enable command, waits 500us, and then configures
/// to device to use its internal clock, enable the charge pump at 1.5x boost, and
/// auto-increment on writes.
pub fn enable(&mut self) -> Result<(), Error<E>> {
if let Some(p) = self.en_pin.as_mut() {
p.set_high();
}
// TODO there should be a 500us delay here, but the chip appears to mostly work without it,
// so I'm not going to worry about it now. Ideally, this function should take a
// `embedded_hal::delay::Delay` and wait.
self.en = true;
self.send(&[reg::CNTRL1, (reg::Cntrl1::CHIP_EN).bits()])?;
self.send(&[
reg::MISC,
(reg::Misc::INT_CLK_EN
| reg::Misc::CLK_DET_EN
| reg::Misc::CP_MODE_1_5x
| reg::Misc::EN_AUTO_INCR)
.bits(),
])?;
Ok(())
}
/// Soft-reset the device NOW
pub fn reset(&mut self) -> Result<(), Error<E>> {
self.send(&[reg::RESET, reg::Reset::RESET_NOW.bits()])?;
Ok(())
}
/// Turn off the device NOW
pub fn disable(&mut self) {
if let Some(p) = self.en_pin.as_mut() {
p.set_low();
}
self.en = false;
}
/// Set the D line to the provided PWM value
pub fn set_pwm(&mut self, d: D, pwm: u8) -> Result<(), Error<E>> {
self.send(&[reg::D_PWM_BASE + u8::from(d), pwm])?;
Ok(())
}
}
|
use super::button::Button;
use seed::virtual_dom::IntoNodes;
use seed::{prelude::*, *};
use std::borrow::Cow;
use std::rc::Rc;
use web_sys::MouseEvent;
// ------ NavBar ------
pub struct NavBar<Ms: 'static> {
brand: Brand<Ms>,
content: Vec<Node<Ms>>,
toggle: Button<Ms>,
attrs: Attrs,
style: Style,
fixed_top: bool,
}
impl<Ms> NavBar<Ms> {
pub fn new(content: impl IntoNodes<Ms>, link: impl Into<Cow<'static, str>>) -> Self {
let toggle = Button::default()
.no_style()
.add_attrs(C!["navbar-toggler"])
.add_attrs(attrs! {
At::from("aria-expanded") => "false",
At::from("aria-label") => "Toggle navigation",
})
.content(span![C!["navbar-toggler-icon"]]);
Self {
brand: Brand::new(content, link),
content: Vec::new(),
toggle,
attrs: Attrs::empty(),
style: Style::empty(),
fixed_top: true,
}
}
pub fn fixed_top(mut self, fixed_top: bool) -> Self {
self.fixed_top = fixed_top;
self
}
pub fn update_brand(mut self, f: impl FnOnce(Brand<Ms>) -> Brand<Ms>) -> Self {
self.brand = f(self.brand);
self
}
pub fn content(mut self, content: impl IntoNodes<Ms>) -> Self {
self.content = content.into_nodes();
self
}
pub fn add_attrs(mut self, attrs: Attrs) -> Self {
self.attrs.merge(attrs);
self
}
pub fn add_style(mut self, style: Style) -> Self {
self.style.merge(style);
self
}
pub fn update_toggle(mut self, f: impl FnOnce(Button<Ms>) -> Button<Ms>) -> Self {
self.toggle = f(self.toggle);
self
}
pub fn view(self) -> Node<Ms> {
nav![
C!["navbar", IF!(self.fixed_top => "fixed-top")],
self.style,
self.attrs,
self.brand,
self.content
]
}
pub fn view_collapsable(
self,
expanded: bool,
content_id: impl Into<Cow<'static, str>>,
) -> Node<Ms> {
let content_id = content_id.into();
nav![
C!["navbar", IF!(self.fixed_top => "fixed-top")],
self.style,
self.attrs,
self.brand,
vec![
self.toggle
.add_attrs(attrs! { At::from("aria-controls") => content_id })
.view(),
div![
C!["collapse", "navbar-collapse", IF!(expanded => "show")],
id!(content_id),
self.content,
]
]
]
}
}
// ------ Brand ------
pub struct Brand<Ms: 'static> {
content: Vec<Node<Ms>>,
link: Cow<'static, str>,
attrs: Attrs,
style: Style,
}
impl<Ms> UpdateEl<Ms> for Brand<Ms> {
fn update_el(self, el: &mut El<Ms>) {
self.view().update_el(el)
}
}
impl<Ms> Brand<Ms> {
pub fn new(content: impl IntoNodes<Ms>, link: impl Into<Cow<'static, str>>) -> Self {
Self {
content: content.into_nodes(),
link: link.into(),
attrs: Attrs::empty(),
style: Style::empty(),
}
}
pub fn content(mut self, content: impl IntoNodes<Ms>) -> Self {
self.content = content.into_nodes();
self
}
pub fn add_attrs(mut self, attrs: Attrs) -> Self {
self.attrs.merge(attrs);
self
}
pub fn add_style(mut self, style: Style) -> Self {
self.style.merge(style);
self
}
pub fn view(self) -> Node<Ms> {
a![
C!["navbar-brand"],
attrs! {At::Href => self.link},
self.style,
self.attrs,
self.content,
]
}
}
// ------ Nav ------
pub struct Nav<Ms: 'static> {
content: Vec<Node<Ms>>,
attrs: Attrs,
style: Style,
}
impl<Ms> Nav<Ms> {
pub fn new() -> Self {
Self::default()
}
pub fn content(mut self, content: impl IntoNodes<Ms>) -> Self {
self.content = content.into_nodes();
self
}
pub fn add_attrs(mut self, attrs: Attrs) -> Self {
self.attrs.merge(attrs);
self
}
pub fn add_style(mut self, style: Style) -> Self {
self.style.merge(style);
self
}
pub fn view(self) -> Node<Ms> {
ul![C!["navbar-nav"], self.style, self.attrs, self.content,]
}
}
impl<Ms> Default for Nav<Ms> {
fn default() -> Self {
Self {
content: Vec::new(),
attrs: Attrs::empty(),
style: Style::empty(),
}
}
}
// ------ NavLink ------
pub struct NavLink<Ms: 'static> {
title: Cow<'static, str>,
link: Cow<'static, str>,
active: bool,
disabled: bool,
icon: Option<Node<Ms>>,
attrs: Attrs,
inner_attrs: Attrs,
style: Style,
on_clicks: Vec<Rc<dyn Fn(MouseEvent) -> Ms>>,
}
impl<Ms> UpdateEl<Ms> for NavLink<Ms> {
fn update_el(self, el: &mut El<Ms>) {
self.view().update_el(el)
}
}
impl<Ms> NavLink<Ms> {
pub fn new(title: impl Into<Cow<'static, str>>, link: impl Into<Cow<'static, str>>) -> Self {
Self {
title: title.into(),
link: link.into(),
active: false,
disabled: false,
icon: None,
attrs: Attrs::empty(),
inner_attrs: Attrs::empty(),
style: Style::empty(),
on_clicks: Vec::new(),
}
}
pub fn active(mut self, active: bool) -> Self {
self.active = active;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn icon(mut self, icon: Node<Ms>) -> Self {
self.icon = Some(icon);
self
}
pub fn add_attrs(mut self, attrs: Attrs) -> Self {
self.attrs.merge(attrs);
self
}
pub fn add_inner_attrs(mut self, attrs: Attrs) -> Self {
self.inner_attrs.merge(attrs);
self
}
pub fn add_style(mut self, style: Style) -> Self {
self.style.merge(style);
self
}
pub fn add_on_click(
mut self,
on_click: impl FnOnce(MouseEvent) -> Ms + Clone + 'static,
) -> Self {
self.on_clicks
.push(Rc::new(move |event| on_click.clone()(event)));
self
}
pub fn view(self) -> Node<Ms> {
let mut elem = li![
C!["nav-item", IF!(self.active => "active")],
&self.attrs,
&self.style,
a![
C![
"nav-link",
IF!(self.disabled => "disabled"),
IF!(self.active => "active")
],
attrs! {
At::Href => self.link
At::TabIndex => if self.disabled { AtValue::Some((-1).to_string()) } else { AtValue::Ignored },
At::from("aria-disabled") => if self.disabled { AtValue::Some(true.to_string()) } else { AtValue::Ignored },
},
self.inner_attrs,
if let Some(icon) = self.icon {
icon
} else {
empty![]
},
self.title,
if self.active {
span![C!["sr-only"], " (current)"]
} else {
empty![]
},
],
];
for on_click in self.on_clicks {
elem.add_event_handler(mouse_ev(Ev::Click, move |event| on_click(event)));
}
elem
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppBroadcastingMonitor(pub ::windows::core::IInspectable);
impl AppBroadcastingMonitor {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AppBroadcastingMonitor, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IsCurrentAppBroadcasting(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn IsCurrentAppBroadcastingChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AppBroadcastingMonitor, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveIsCurrentAppBroadcastingChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for AppBroadcastingMonitor {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.AppBroadcasting.AppBroadcastingMonitor;{00f95a68-8907-48a0-b8ef-24d208137542})");
}
unsafe impl ::windows::core::Interface for AppBroadcastingMonitor {
type Vtable = IAppBroadcastingMonitor_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x00f95a68_8907_48a0_b8ef_24d208137542);
}
impl ::windows::core::RuntimeName for AppBroadcastingMonitor {
const NAME: &'static str = "Windows.Media.AppBroadcasting.AppBroadcastingMonitor";
}
impl ::core::convert::From<AppBroadcastingMonitor> for ::windows::core::IUnknown {
fn from(value: AppBroadcastingMonitor) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppBroadcastingMonitor> for ::windows::core::IUnknown {
fn from(value: &AppBroadcastingMonitor) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppBroadcastingMonitor {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a AppBroadcastingMonitor {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppBroadcastingMonitor> for ::windows::core::IInspectable {
fn from(value: AppBroadcastingMonitor) -> Self {
value.0
}
}
impl ::core::convert::From<&AppBroadcastingMonitor> for ::windows::core::IInspectable {
fn from(value: &AppBroadcastingMonitor) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppBroadcastingMonitor {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a AppBroadcastingMonitor {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppBroadcastingMonitor {}
unsafe impl ::core::marker::Sync for AppBroadcastingMonitor {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppBroadcastingStatus(pub ::windows::core::IInspectable);
impl AppBroadcastingStatus {
pub fn CanStartBroadcast(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Details(&self) -> ::windows::core::Result<AppBroadcastingStatusDetails> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppBroadcastingStatusDetails>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppBroadcastingStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.AppBroadcasting.AppBroadcastingStatus;{1225e4df-03a1-42f8-8b80-c9228cd9cf2e})");
}
unsafe impl ::windows::core::Interface for AppBroadcastingStatus {
type Vtable = IAppBroadcastingStatus_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1225e4df_03a1_42f8_8b80_c9228cd9cf2e);
}
impl ::windows::core::RuntimeName for AppBroadcastingStatus {
const NAME: &'static str = "Windows.Media.AppBroadcasting.AppBroadcastingStatus";
}
impl ::core::convert::From<AppBroadcastingStatus> for ::windows::core::IUnknown {
fn from(value: AppBroadcastingStatus) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppBroadcastingStatus> for ::windows::core::IUnknown {
fn from(value: &AppBroadcastingStatus) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppBroadcastingStatus {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a AppBroadcastingStatus {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppBroadcastingStatus> for ::windows::core::IInspectable {
fn from(value: AppBroadcastingStatus) -> Self {
value.0
}
}
impl ::core::convert::From<&AppBroadcastingStatus> for ::windows::core::IInspectable {
fn from(value: &AppBroadcastingStatus) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppBroadcastingStatus {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a AppBroadcastingStatus {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppBroadcastingStatus {}
unsafe impl ::core::marker::Sync for AppBroadcastingStatus {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppBroadcastingStatusDetails(pub ::windows::core::IInspectable);
impl AppBroadcastingStatusDetails {
pub fn IsAnyAppBroadcasting(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsCaptureResourceUnavailable(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsGameStreamInProgress(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsGpuConstrained(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsAppInactive(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsBlockedForApp(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsDisabledByUser(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsDisabledBySystem(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppBroadcastingStatusDetails {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.AppBroadcasting.AppBroadcastingStatusDetails;{069dada4-b573-4e3c-8e19-1bafacd09713})");
}
unsafe impl ::windows::core::Interface for AppBroadcastingStatusDetails {
type Vtable = IAppBroadcastingStatusDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x069dada4_b573_4e3c_8e19_1bafacd09713);
}
impl ::windows::core::RuntimeName for AppBroadcastingStatusDetails {
const NAME: &'static str = "Windows.Media.AppBroadcasting.AppBroadcastingStatusDetails";
}
impl ::core::convert::From<AppBroadcastingStatusDetails> for ::windows::core::IUnknown {
fn from(value: AppBroadcastingStatusDetails) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppBroadcastingStatusDetails> for ::windows::core::IUnknown {
fn from(value: &AppBroadcastingStatusDetails) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppBroadcastingStatusDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a AppBroadcastingStatusDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppBroadcastingStatusDetails> for ::windows::core::IInspectable {
fn from(value: AppBroadcastingStatusDetails) -> Self {
value.0
}
}
impl ::core::convert::From<&AppBroadcastingStatusDetails> for ::windows::core::IInspectable {
fn from(value: &AppBroadcastingStatusDetails) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppBroadcastingStatusDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a AppBroadcastingStatusDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppBroadcastingStatusDetails {}
unsafe impl ::core::marker::Sync for AppBroadcastingStatusDetails {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppBroadcastingUI(pub ::windows::core::IInspectable);
impl AppBroadcastingUI {
pub fn GetStatus(&self) -> ::windows::core::Result<AppBroadcastingStatus> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppBroadcastingStatus>(result__)
}
}
pub fn ShowBroadcastUI(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() }
}
pub fn GetDefault() -> ::windows::core::Result<AppBroadcastingUI> {
Self::IAppBroadcastingUIStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppBroadcastingUI>(result__)
})
}
#[cfg(feature = "System")]
pub fn GetForUser<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::User>>(user: Param0) -> ::windows::core::Result<AppBroadcastingUI> {
Self::IAppBroadcastingUIStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), user.into_param().abi(), &mut result__).from_abi::<AppBroadcastingUI>(result__)
})
}
pub fn IAppBroadcastingUIStatics<R, F: FnOnce(&IAppBroadcastingUIStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AppBroadcastingUI, IAppBroadcastingUIStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AppBroadcastingUI {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.AppBroadcasting.AppBroadcastingUI;{e56f9f8f-ee99-4dca-a3c3-70af3db44f5f})");
}
unsafe impl ::windows::core::Interface for AppBroadcastingUI {
type Vtable = IAppBroadcastingUI_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe56f9f8f_ee99_4dca_a3c3_70af3db44f5f);
}
impl ::windows::core::RuntimeName for AppBroadcastingUI {
const NAME: &'static str = "Windows.Media.AppBroadcasting.AppBroadcastingUI";
}
impl ::core::convert::From<AppBroadcastingUI> for ::windows::core::IUnknown {
fn from(value: AppBroadcastingUI) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppBroadcastingUI> for ::windows::core::IUnknown {
fn from(value: &AppBroadcastingUI) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppBroadcastingUI {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a AppBroadcastingUI {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppBroadcastingUI> for ::windows::core::IInspectable {
fn from(value: AppBroadcastingUI) -> Self {
value.0
}
}
impl ::core::convert::From<&AppBroadcastingUI> for ::windows::core::IInspectable {
fn from(value: &AppBroadcastingUI) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppBroadcastingUI {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a AppBroadcastingUI {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppBroadcastingUI {}
unsafe impl ::core::marker::Sync for AppBroadcastingUI {}
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppBroadcastingMonitor(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppBroadcastingMonitor {
type Vtable = IAppBroadcastingMonitor_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x00f95a68_8907_48a0_b8ef_24d208137542);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBroadcastingMonitor_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppBroadcastingStatus(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppBroadcastingStatus {
type Vtable = IAppBroadcastingStatus_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1225e4df_03a1_42f8_8b80_c9228cd9cf2e);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBroadcastingStatus_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppBroadcastingStatusDetails(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppBroadcastingStatusDetails {
type Vtable = IAppBroadcastingStatusDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x069dada4_b573_4e3c_8e19_1bafacd09713);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBroadcastingStatusDetails_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppBroadcastingUI(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppBroadcastingUI {
type Vtable = IAppBroadcastingUI_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe56f9f8f_ee99_4dca_a3c3_70af3db44f5f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBroadcastingUI_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppBroadcastingUIStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppBroadcastingUIStatics {
type Vtable = IAppBroadcastingUIStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x55a8a79d_23cb_4579_9c34_886fe02c045a);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBroadcastingUIStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "System")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, user: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "System"))] usize,
);
|
#![no_std]
pub mod local_apic;
pub mod xapic;
pub use local_apic::LocalApic;
pub use xapic::XApic; |
//
// mtpng - a multithreaded parallel PNG encoder in Rust
// writer.rs - low-level PNG chunk writer
//
// Copyright (c) 2018 Brion Vibber
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
use crc::crc32;
use crc::Hasher32;
use std::io;
use std::io::Write;
use super::Header;
use super::utils::*;
pub struct Writer<W: Write> {
output: W,
}
impl<W: Write> Writer<W> {
//
// Creates a new PNG chunk stream writer.
// Consumes the output Write object, but will
// give it back to you via Writer::close().
//
pub fn new(output: W) -> Writer<W> {
Writer {
output,
}
}
//
// Close out the writer and return the Write
// passed in originally so it can be used for
// further output if necessary.
//
// Consumes the writer.
//
pub fn finish(mut self: Writer<W>) -> io::Result<W> {
self.flush()?;
Ok(self.output)
}
//
// Write the PNG file signature to output stream.
// https://www.w3.org/TR/PNG/#5PNG-file-signature
//
pub fn write_signature(&mut self) -> IoResult {
let bytes = [
137u8, // ???
80u8, // 'P'
78u8, // 'N'
71u8, // 'G'
13u8, // \r
10u8, // \n
26u8, // SUB
10u8 // \n
];
self.write_bytes(&bytes)
}
fn write_be32(&mut self, val: u32) -> IoResult {
write_be32(&mut self.output, val)
}
fn write_bytes(&mut self, data: &[u8]) -> IoResult {
self.output.write_all(data)
}
//
// Write a chunk to the output stream.
//
// https://www.w3.org/TR/PNG/#5DataRep
// https://www.w3.org/TR/PNG/#5CRC-algorithm
//
pub fn write_chunk(&mut self, tag: &[u8], data: &[u8]) -> IoResult {
if tag.len() != 4 {
return Err(invalid_input("Chunk tags must be 4 bytes"));
}
if data.len() > u32::max_value() as usize {
return Err(invalid_input("Data chunks cannot exceed 4 GiB - 1 byte"));
}
// CRC covers both tag and data.
let mut digest = crc32::Digest::new(crc32::IEEE);
digest.write(tag);
digest.write(data);
let checksum = digest.sum32();
// Write data...
self.write_be32(data.len() as u32)?;
self.write_bytes(tag)?;
self.write_bytes(data)?;
self.write_be32(checksum)
}
//
// IHDR - first chunk in the file.
// https://www.w3.org/TR/PNG/#11IHDR
//
pub fn write_header(&mut self, header: Header) -> IoResult {
let mut data = Vec::<u8>::new();
write_be32(&mut data, header.width)?;
write_be32(&mut data, header.height)?;
write_byte(&mut data, header.depth)?;
write_byte(&mut data, header.color_type as u8)?;
write_byte(&mut data, header.compression_method as u8)?;
write_byte(&mut data, header.filter_method as u8)?;
write_byte(&mut data, header.interlace_method as u8)?;
self.write_chunk(b"IHDR", &data)
}
//
// IEND - last chunk in the file.
// https://www.w3.org/TR/PNG/#11IEND
//
pub fn write_end(&mut self) -> IoResult {
self.write_chunk(b"IEND", b"")
}
//
// Flush output.
//
pub fn flush(&mut self) -> IoResult {
self.output.flush()
}
}
#[cfg(test)]
mod tests {
use std::io;
use super::Writer;
use super::IoResult;
fn test_writer<F, G>(test_func: F, assert_func: G)
where F: Fn(&mut Writer<Vec<u8>>) -> IoResult,
G: Fn(&[u8])
{
let result = (|| -> io::Result<Vec<u8>> {
let output = Vec::<u8>::new();
let mut writer = Writer::new(output);
test_func(&mut writer)?;
writer.finish()
})();
match result {
Ok(output) => assert_func(&output),
Err(e) => assert!(false, "Error: {}", e),
}
}
#[test]
fn it_works() {
test_writer(|_writer| {
Ok(())
}, |output| {
assert_eq!(output.len(), 0);
})
}
#[test]
fn header_works() {
test_writer(|writer| {
writer.write_signature()
}, |output| {
assert_eq!(output.len(), 8);
})
}
#[test]
fn empty_chunk_works() {
test_writer(|writer| {
writer.write_chunk(b"IDAT", b"")
}, |output| {
// 4 bytes len
// 4 bytes tag
// 4 bytes crc
assert_eq!(output.len(), 12);
})
}
#[test]
fn full_chunk_works() {
test_writer(|writer| {
writer.write_chunk(b"IDAT", b"01234567890123456789")
}, |output| {
// 4 bytes len
// 4 bytes tag
// 20 bytes data
// 4 bytes crc
assert_eq!(output.len(), 32);
})
}
#[test]
fn crc_works() {
// From a 1x1 truecolor black pixel made with gd
let one_pixel = b"\x08\x99\x63\x60\x60\x60\x00\x00\x00\x04\x00\x01";
test_writer(|writer| {
writer.write_chunk(b"IDAT", one_pixel)
}, |output| {
assert_eq!(output[0..4], b"\x00\x00\x00\x0c"[..], "expected length 12");
assert_eq!(output[4..8], b"IDAT"[..], "expected IDAT");
assert_eq!(output[8..20], one_pixel[..], "expected data payload");
assert_eq!(output[20..24], b"\xa3\x0a\x15\xe3"[..], "expected crc32");
})
}
}
|
//! An example of a multisig to execute arbitrary Solana transactions.
#![feature(proc_macro_hygiene)]
use anchor_lang::prelude::*;
use anchor_lang::solana_program;
use anchor_lang::solana_program::instruction::Instruction;
use std::convert::Into;
#[program]
pub mod multisig {
use super::*;
pub fn create_multisig(
ctx: Context<CreateMultisig>,
owners: Vec<Pubkey>,
threshold: u64,
nonce: u8,
) -> Result<()> {
let multisig = &mut ctx.accounts.multisig;
multisig.owners = owners;
multisig.threshold = threshold;
multisig.nonce = nonce;
Ok(())
}
pub fn create_transaction(
ctx: Context<CreateTransaction>,
pid: Pubkey,
accs: Vec<TransactionAccount>,
data: Vec<u8>,
) -> Result<()> {
let owner_index = ctx
.accounts
.multisig
.owners
.iter()
.position(|a| a == ctx.accounts.proposer.key)
.ok_or(ErrorCode::InvalidOwner)?;
let mut signers = Vec::new();
signers.resize(ctx.accounts.multisig.owners.len(), false);
signers[owner_index] = true;
let tx = &mut ctx.accounts.transaction;
tx.program_id = pid;
tx.accounts = accs;
tx.data = data;
tx.signers = signers;
tx.multisig = *ctx.accounts.multisig.to_account_info().key;
tx.did_execute = false;
Ok(())
}
pub fn approve(ctx: Context<Approve>) -> Result<()> {
let owner_index = ctx
.accounts
.multisig
.owners
.iter()
.position(|a| a == ctx.accounts.owner.key)
.ok_or(ErrorCode::InvalidOwner)?;
ctx.accounts.transaction.signers[owner_index] = true;
Ok(())
}
// Sets the owners field on the multisig. The only way this can be invoked
// is via a recursive call from execute_transaction -> set_owners.
pub fn set_owners(ctx: Context<Auth>, owners: Vec<Pubkey>) -> Result<()> {
let multisig = &mut ctx.accounts.multisig;
if (owners.len() as u64) < multisig.threshold {
multisig.threshold = owners.len() as u64;
}
multisig.owners = owners;
Ok(())
}
pub fn change_threshold(ctx: Context<Auth>, threshold: u64) -> Result<()> {
let multisig = &mut ctx.accounts.multisig;
multisig.threshold = threshold;
Ok(())
}
pub fn execute_transaction(ctx: Context<ExecuteTransaction>) -> Result<()> {
// Check we have enough signers.
let sig_count = ctx
.accounts
.transaction
.signers
.iter()
.filter_map(|s| match s {
false => None,
true => Some(true),
})
.collect::<Vec<_>>()
.len() as u64;
if sig_count < ctx.accounts.multisig.threshold {
return Err(ErrorCode::NotEnoughSigners.into());
}
// Execute the multisig transaction.
let ix: Instruction = (&*ctx.accounts.transaction).into();
let seeds = &[
ctx.accounts.multisig.to_account_info().key.as_ref(),
&[ctx.accounts.multisig.nonce],
];
let signer = &[&seeds[..]];
let accounts = ctx.remaining_accounts;
solana_program::program::invoke_signed(&ix, &accounts, signer)?;
// Burn the account to ensure one time use.
ctx.accounts.transaction.did_execute = true;
Ok(())
}
}
#[derive(Accounts)]
pub struct CreateMultisig<'info> {
#[account(init)]
multisig: ProgramAccount<'info, Multisig>,
rent: Sysvar<'info, Rent>,
}
#[derive(Accounts)]
pub struct CreateTransaction<'info> {
multisig: ProgramAccount<'info, Multisig>,
#[account(init)]
transaction: ProgramAccount<'info, Transaction>,
#[account(signer)]
proposer: AccountInfo<'info>,
rent: Sysvar<'info, Rent>,
}
#[derive(Accounts)]
pub struct Approve<'info> {
multisig: ProgramAccount<'info, Multisig>,
#[account(mut, belongs_to = multisig)]
transaction: ProgramAccount<'info, Transaction>,
// One of the multisig owners.
#[account(signer)]
owner: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct Auth<'info> {
#[account(mut)]
multisig: ProgramAccount<'info, Multisig>,
#[account(signer, seeds = [
multisig.to_account_info().key.as_ref(),
&[multisig.nonce],
])]
multisig_signer: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct ExecuteTransaction<'info> {
multisig: ProgramAccount<'info, Multisig>,
#[account(seeds = [
multisig.to_account_info().key.as_ref(),
&[multisig.nonce],
])]
multisig_signer: AccountInfo<'info>,
#[account(mut, belongs_to = multisig)]
transaction: ProgramAccount<'info, Transaction>,
}
#[account]
pub struct Multisig {
owners: Vec<Pubkey>,
threshold: u64,
nonce: u8,
}
#[account]
pub struct Transaction {
// Target program to execute against.
program_id: Pubkey,
// Accounts requried for the transaction.
accounts: Vec<TransactionAccount>,
// Instruction data for the transaction.
data: Vec<u8>,
// signers[index] is true iff multisig.owners[index] signed the transaction.
signers: Vec<bool>,
// The multisig account this transaction belongs to.
multisig: Pubkey,
// Boolean ensuring one time execution.
did_execute: bool,
}
impl From<&Transaction> for Instruction {
fn from(tx: &Transaction) -> Instruction {
Instruction {
program_id: tx.program_id,
accounts: tx.accounts.clone().into_iter().map(Into::into).collect(),
data: tx.data.clone(),
}
}
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct TransactionAccount {
pubkey: Pubkey,
is_signer: bool,
is_writable: bool,
}
impl From<TransactionAccount> for AccountMeta {
fn from(account: TransactionAccount) -> AccountMeta {
match account.is_writable {
false => AccountMeta::new_readonly(account.pubkey, account.is_signer),
true => AccountMeta::new(account.pubkey, account.is_signer),
}
}
}
#[error]
pub enum ErrorCode {
#[msg("The given owner is not part of this multisig.")]
InvalidOwner,
#[msg("Not enough owners signed this transaction.")]
NotEnoughSigners,
Unknown,
}
|
//! Provides a Rust binding to the OpenGL API.
//!
//! This library attempts to provide a complete set of bindings to the OpenGL API while providing
//! a small boost in type-safety over the raw OpenGL API. This library does not abstract the OpenGL
//! API in any way, and in many cases still leaves the task of catching error cases to the
//! programmer. This is meant to be used by other libraries to build higher-level abstractions over
//! raw OpenGL.
//!
//! # Safety Improvements
//!
//! The primary way that `gl-util` improves on the raw OpenGL is by replacing `GLEnum` function
//! parameters with special enum types that only contain variants that are valid options for that
//! function.
#![feature(const_fn)]
#![allow(bad_style)]
#[macro_use]
mod macros;
#[cfg(target_os = "windows")]
#[path="windows.rs"]
pub mod platform;
#[cfg(target_os = "linux")]
#[path="linux.rs"]
pub mod platform;
pub mod types;
use std::mem;
pub use types::*;
pub use platform::*;
pub fn buffer_data<T>(target: BufferTarget, data: &[T], usage: BufferUsage) {
unsafe {
buffer_data_raw(
target,
(data.len() * mem::size_of::<T>()) as isize,
data.as_ptr() as *const _,
usage,
);
}
}
pub fn gen_buffer() -> Option<BufferName> {
let mut buffer_name = BufferName::null();
unsafe {
gen_buffers(1, &mut buffer_name);
}
if buffer_name.is_null() {
None
} else {
Some(buffer_name)
}
}
pub fn gen_vertex_array() -> Option<VertexArrayName> {
let mut vertex_array_name = VertexArrayName::null();
unsafe {
gen_vertex_arrays(1, &mut vertex_array_name);
}
if vertex_array_name.is_null() {
None
} else {
Some(vertex_array_name)
}
}
gl_proc!(glActiveTexture:
/// Selects active texture unit.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glActiveTexture)
///
/// Core since version 1.3
///
/// Selects which texture unit subsequent texture state calls will affect. The number of
/// texture units an implementation supports is implementation dependent, but must be at least
/// 96 (80 in GL 4.2, 48 in GL 3.3).
fn active_texture(texture: u32));
gl_proc!(glAttachShader:
/// Attaches a shader object to a program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glAttachShader)
///
/// Core since version 2.0
///
/// In order to create a complete shader program, there must be a way to specify the list of
/// things that will be linked together. Program objects provide this mechanism. Shaders
/// that are to be linked together in a program object must first be attached to that program
/// object. `attach_shader` attaches the shader object specified by shader to the program
/// object specified by program. This indicates that shader will be included in link
/// operations that will be performed on program.
///
/// All operations that can be performed on a shader object are valid whether or not the
/// shader object is attached to a program object. It is permissible to attach a shader
/// object to a program object before source code has been loaded into the shader object or
/// before the shader object has been compiled. It is permissible to attach multiple shader
/// objects of the same type because each may contain a portion of the complete shader. It
/// is also permissible to attach a shader object to more than one program object. If a
/// shader object is deleted while it is attached to a program object, it will be flagged for
/// deletion, and deletion will not occur until `detach_shader` is called to detach it from
/// all program objects to which it is attached.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if either program or shader is not a value generated by
/// OpenGL.
/// - `glInvalidOperation` is generated if program is not a program object.
/// - `glInvalidOperation` is generated if shader is not a shader object.
/// - `glInvalidOperation` is generated if shader is already attached to program.
fn attach_shader(program: ProgramObject, shader: ShaderObject));
gl_proc!(glBeginQuery:
/// Delimits the start of a query object.
///
/// TODO: Add documentation.
fn begin_query(query_type: QueryType, query: QueryObject));
gl_proc!(glBindBuffer:
/// Binds a named buffer object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glBindBuffer)
///
/// Core since version 1.5
///
/// Binds a buffer object to the specified buffer binding point. Calling `bind_buffer` with target
/// set to one of the accepted symbolic constants and buffer set to the name of a buffer object
/// binds that buffer object name to the target. If no buffer object with name buffer exists one
/// is created with that name. When a buffer object is bound to a target the previous binding for
/// that target is automatically broken.
///
/// Buffer object names are unsigned integers. The value zero is reserved, but there is no default
/// buffer object for each buffer object target. Instead, buffer set to zero effectively unbinds
/// any buffer object previously bound, and restores client memory usage for that buffer object
/// target (if supported for that target). Buffer object names and the corresponding buffer object
/// contents are local to the shared object space of the current GL rendering context; two
/// rendering contexts share buffer object names only if they explicitly enable sharing between
/// contexts through the appropriate GL windows interfaces functions.
///
/// `gen_buffers` must be used to generate a set of unused buffer object names.
///
/// A buffer object binding created with `bind_buffer` remains active until a different buffer
/// object name is bound to the same target or until the bound buffer object is deleted with
/// `delete_buffers`.
///
/// Once created, a named buffer object may be re-bound to any target as often as needed. However,
/// the GL implementation may make choices about how to optimize the storage of a buffer object
/// based on its initial binding target.
///
/// # Buffer Targets
///
/// The state of a buffer object immediately after it is first bound is an unmapped zero-sized
/// memory buffer with `GL_READ_WRITE` access and `GL_STATIC_DRAW` usage.
///
/// While a non-zero buffer object name is bound GL operations on the target to which it is bound
/// affect the bound buffer object and queries of the target to which it is bound return state
/// from the bound buffer object. While buffer object name zero is bound, as in the initial state,
/// attempts to modify or query state on the target to which it is bound generates an
/// `GL_INVALID_OPERATION` error.
///
/// When a non-zero buffer object is bound to the `BufferTarget::Array` target the vertex array
/// pointer parameter is interpreted as an offset within the buffer object measured in basic
/// machine units (bytes).
///
/// When a non-zero buffer object is bound to the `BufferTarget::DrawIndirect` target parameters
/// for draws issued through `draw_arrays_indirect` and `draw_elements_indirect` are sourced from
/// the specified offset in that buffer object's data store.
///
/// When a non-zero buffer object is bound to the `BufferTarget::DispatchIndirect` target, the
/// parameters for compute dispatches issued through `dispatch_compute_indirect` are sourced from
/// the specified offset in that buffer object's data store.
///
/// While a non-zero buffer object is bound to the `BufferTarget::ElementArray` target the indices
/// parameter of `draw_elements`, `draw_elements_instanced`, `draw_elements_base_vertex`,
/// `draw_range_elements`, `draw_range_elements_base_vertex`, `multi_draw_elements`, or
/// `multi_draw_elements_base_vertex` is interpreted as an offset within the buffer object
/// measured in basic machine units (bytes).
///
/// While a non-zero buffer object is bound to the `BufferTarget::PixelPack` target the following
/// commands are affected: `get_compressed_tex_image`, `get_tex_image`, and `read_pixels`. The
/// pointer parameter is interpreted as an offset within the buffer object measured in basic
/// machine units (bytes).
///
/// While a non-zero buffer object is bound to the `BufferTarget::PixelUnpack` target the
/// following commands are affected: `compressed_tex_image_1d`, `compressed_tex_image_2d`,
/// `compressed_tex_image_3d`, `compressed_tex_sub_image_1d`, `compressed_tex_sub_image_2d`,
/// `compressed_tex_sub_image_3d`, `tex_image_1d`, `tex_image_2d`, `tex_image_3d`,
/// `tex_sub_image_1d`, `tex_sub_image_2d`, and `tex_sub_image_3d`. The pointer parameter is
/// interpreted as an offset within the buffer object measured in basic machine units (bytes).
///
/// The buffer targets `BufferTarget::CopyRead` and `BufferTarget::CopyWrite` are provided to
/// allow `copy_buffer_sub_data` to be used without disturbing the state of other bindings.
/// However, `copy_buffer_sub_data` may be used with any pair of buffer binding points.
///
/// The `BufferTarget::TransformFeedback` buffer binding point may be passed to `bind_buffer`, but
/// will not directly affect transform feedback state. Instead, the indexed
/// `BufferTarget::TransformFeedback` bindings must be used through a call to `bind_buffer_base` or
/// `bind_buffer_range`. This will affect the generic `BufferTarget::TransformFeedback` binding.
///
/// Likewise, the `BufferTarget::Uniform`, `BufferTarget::AtomicCounter` and
/// `BufferTarget::ShaderStorage` buffer binding points may be used but do not directly affect
/// uniform buffer, atomic counter buffer, or shader storage buffer state, respectively.
/// `bind_buffer_base` or `bind_buffer_range` must be used to bind a buffer to an indexed uniform
/// buffer, atomic counter buffer, or storage buffer binding point.
///
/// The `BufferTarget::Query` binding point is used to specify a buffer object that is to receive
/// the results of query objects through calls to the `get_query_object` family of commands.
///
/// # Version Availability
///
/// - The `Read`, `Uniform`, and `Texture` targets are available only if the GL version is 3.1 or
/// greater.
/// - The `AtomicCounter` target is available only if the GL version is 4.2 or greater.
/// - The `DispatchIndirect` and `ShaderStorage` targets are available only if the GL version is
/// 4.3 or greater.
/// - The `Query` target is available only if the GL version is 4.4 or greater.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if buffer is not a name previously returned from a call to
/// `gen_buffers`.
fn bind_buffer(target: BufferTarget, buffer: BufferName));
gl_proc!(glBindTexture:
/// Binds a named texture to a texturing target.
///
/// Lets you create or use a named texture. Calling `bind_texture` with target set to
/// `Texture1d`, `Texture2d`, `Texture3d`, `Texture1dArray`, `Texture2dArray`,
/// `TextureRectangle`, `TextureCubeMap`, `TextureCubeMapArray`, `TextureBuffer`,
/// `Texture2dMultisample` or `Texture2dMultisampleArray` and texture set to the name of the
/// new texture binds the texture name to the target. When a texture is bound to a target
/// the previous binding for that target is automatically broken.
///
/// Texture names are `u32` values. The value zero is reserved to represent the default
/// texture for each texture target. Texture names and the corresponding texture contents are
/// local to the shared object space of the current GL rendering context; two rendering
/// contexts share texture names only if they explicitly enable sharing between contexts
/// through the appropriate GL windows interfaces functions.
///
/// You must use `gen_textures` to generate a set of new texture names.
///
/// When a texture is first bound it assumes the specified target: A texture first bound to
/// `Texture1d` becomes one-dimensional texture, a texture first bound to `Texture2d` becomes
/// two-dimensional texture, a texture first bound to `Texture3d` becomes three-dimensional
/// texture, a texture first bound to `Texture1dArray` becomes one-dimensional array texture,
/// a texture first bound to `Texture2dArray` becomes two-dimensional arary texture, a
/// texture first bound to `TextureRectangle` becomes rectangle texture, a texture first
/// bound to `TextureCubeMap` becomes a cube-mapped texture, a texture first bound to
/// `TextureCubeMapArray` becomes a cube-mapped array texture, a texture first bound to
/// `TextureBuffer` becomes a buffer texture, a texture first bound to `Texture2dMultisample`
/// becomes a two-dimensional multisampled texture, and a texture first bound to
/// `Texture2dMultisampleArray` becomes a two-dimensional multisampled array texture. The
/// state of a one-dimensional texture immediately after it is first bound is equivalent to
/// the state of the default `Texture1d` at GL initialization, and similarly for the other
/// texture types.
///
/// While a texture is bound, GL operations on the target to which it is bound affect the
/// bound texture, and queries of the target to which it is bound return state from the bound
/// texture. In effect, the texture targets become aliases for the textures currently bound
/// to them, and the texture name zero refers to the default textures that were bound to them
/// at initialization.
///
/// A texture binding created with `bind_texture` remains active until a different texture
/// is bound to the same target, or until the bound texture is deleted with
/// `delete_textures`.
///
/// Once created, a named texture may be re-bound to its same original target as often as
/// needed. It is usually much faster to use `bind_texture` to bind an existing named
/// texture to one of the texture targets than it is to reload the texture image using
/// `tex_image_1d`, `tex_image_2d`, `tex_image_3d` or another similar function.
///
/// # Notes
///
/// * The `Texture2dMultisample` and `Texture2dMultisampleArray` targets are available only
/// if the GL version is 3.2 or higher.
///
/// # Errors
///
/// * `GL_INVALID_VALUE` is generated if target is not a name returned from a previous call
/// to `gen_textures`.
/// * `GL_INVALID_OPERATION` is generated if texture was previously created with a target
/// that doesn't match that of target.
fn bind_texture(target: TextureBindTarget, texture: TextureObject));
gl_proc!(glBindVertexArray:
/// Binds a named vertex array object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glBindVertexArray)
///
/// Core since version 3.0
///
/// Binds the vertex array object with `name`. `name` is the name of a vertex array object
/// previously returned from a call to `gen_vertex_arrays`, or zero to break the existing vertex
/// array object binding.
///
/// If no vertex array object with name array exists, one is created when array is first bound.
/// If the bind is successful no change is made to the state of the vertex array object, and any
/// previous vertex array object binding is broken.
///
/// # Errors
///
/// - `GL_INVALID_OPERATION` is generated if array is not zero or the name of a vertex array
/// object previously returned from a call to `gen_vertex_arrays`.
fn bind_vertex_array(name: VertexArrayName));
gl_proc!(glBlendFunc:
/// Specifies pixel arithmetic for both RGB and alpha components.
///
/// Pixels can be drawn using a function that blends the incoming (source) RGBA values with
/// the RGBA values that are already in the frame buffer (the destination values). Blending is
/// initially disabled. Use `enable` and `disable` with argument `ServerCapability::Blend` to
/// enable and disable blending.
///
/// `blend_func` is equivalent to calling `blend_func_separate` with `src_factor` for both the
/// `src_rbg` and `src_alpha` parameters, and `dest_factor` for both the `dest_rbg` and
/// `dest_alpha` parameters.
///
/// In the table and in subsequent equations, first source, second source and destination
/// color components are referred to as (Rs0, Gs0, Bs0, As0), (Rs1, Gs1, Bs1, As1) and (Rd,
/// Gd, Bd, Ad), respectively. The color specified by glBlendColor is referred to as (Rc, Gc,
/// Bc, Ac).
///
/// Source and destination scale factors are referred to as (sR, sG, sB, sA) and (dR, dG, dB,
/// dA).
///
/// | Parameter | RGB Factor | Alpha Factor |
/// |-----------------------|-----------------------------|--------------|
/// | Zero | (0, 0, 0) | 0 |
/// | One | (1, 1, 1) | 1 |
/// | SourceColor | (Rs0, Gs0, Bs0) | As0 |
/// | OneMinusSourceColor | (1, 1, 1) - (Rs0, Gs0, Bs0) | 1 - As0 |
/// | DestColor | (Rd, Gd, Bd) | Ad |
/// | OneMinusDestColor | (1, 1, 1) - (Rd, Gd, Bd) | 1 - Ad |
/// | SourceAlpha | (As0, As0, As0) | As0 |
/// | OneMinusSourceAlpha | (1, 1, 1) - (As0, As0, As0) | 1 - As0 |
/// | DestAlpha | (Ad, Ad, Ad) | Ad |
/// | OneMinusDestAlpha | (1, 1, 1) - (Ad, Ad, Ad) | Ad |
/// | ConstantColor | (Rc, Gc, Bc) | Ac |
/// | OneMinusConstantColor | (1, 1, 1) - (Rc, Gc, Bc) | 1 - Ac |
/// | ConstantAlpha | (Ac, Ac, Ac) | Ac |
/// | OneMinusConstantAlpha | (1, 1, 1) - (Ac, Ac, Ac) | 1 - Ac |
/// | SourceAlphaSaturate | (i, i, i) | 1 |
/// | Source1Color | (Rs1, Gs1, Bs1) | As1 |
/// | OneMinusSourceColor | (1, 1, 1) - (Rs1, Gs1, Bs1) | 1 - As1 |
/// | Source1Alpha | (As1, As1, As1) | As1 |
/// | OneMinusSourceAlpha | (1, 1, 1) - (As1, As1, As1) | 1 - As1 |
///
/// In the table,
///
/// ```
/// i = min(As0, (1 - Ad))
/// ```
///
/// Despite the apparent precision of the above equations, blending arithmetic is not exactly
/// specified, because blending operates with imprecise integer color values. However, a blend
/// factor that should be equal to 1 is guaranteed not to modify its multiplicand, and a blend
/// factor equal to 0 reduces its multiplicand to 0. For example, when `src_factor` is
/// `SourceAlpha`, `dest_factor` is `OneMinusSourceAlpha`, and `As0` is equal to 1, the
/// equations reduce to simple replacement:
///
/// ```
/// Rd = Rs0
/// Gd = Gs0
/// Bd = Bs0
/// Ad = As0
/// ```
///
/// # Notes
///
/// - When more than one color buffer is enabled for drawing the GL performs blending
/// separately for each enabled buffer, using the contents of that buffer for destination
/// color (See `draw_buffer`).
/// - When dual source blending is enabled (i.e. one of the blend factors requiring the second
/// color input is used), the maximum number of enabled draw buffers is given by
/// `GL_MAX_DUAL_SOURCE_DRAW_BUFFERS`, which may be lower than `GL_MAX_DRAW_BUFFERS`.
fn blend_func(src_factor: SourceFactor, dest_factor: DestFactor));
gl_proc!(glBufferData:
/// Creates and initializes a buffer object's data store.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glBufferData)
///
/// Core since version 1.5
///
/// Creates a new data store for the buffer object currently bound to target. Any pre-existing
/// data store is deleted. The new data store is created with the specified size in bytes and
/// usage. If data is not null, the data store is initialized with data from this pointer. In its
/// initial state the new data store is not mapped, it has a null mapped pointer, and its mapped
/// access is `GL_READ_WRITE`.
///
/// # Buffer Usage
///
/// `usage` is a hint to the GL implementation as to how a buffer object's data store will be
/// accessed. This enables the GL implementation to make more intelligent decisions that may
/// significantly impact buffer object performance. It does not, however, constrain the actual
/// usage of the data store. usage can be broken down into two parts: first, the frequency of
/// access (modification and usage), and second, the nature of that access. The frequency of
/// access may be one of these:
///
/// - **STREAM** - The data store contents will be modified once and used at most a few times.
/// - **STATIC** - The data store contents will be modified once and used many times.
/// - **DYNAMIC** - The data store contents will be modified repeatedly and used many times.
///
/// The nature of access may be one of these:
///
/// - **DRAW** - The data store contents are modified by the application, and used as the source
/// for GL drawing and image specification commands.
/// - **READ** - The data store contents are modified by reading data from the GL, and used to
/// return that data when queried by the application.
/// - **COPY** - The data store contents are modified by reading data from the GL, and used as the
/// source for GL drawing and image specification commands.
///
/// # Notes
///
/// - If `data` is null a data store of the specified size is still created but its contents remain
/// uninitialized and thus undefined.
/// - Clients must align data elements consistent with the requirements of the client platform, with
/// an additional base-level requirement that an offset within a buffer to a datum comprising N
/// bytes be a multiple of N.
/// - The `AtomicCounter` target is available only if the GL version is 4.2 or greater.
/// - The `DispatchIndirect` and `ShaderStorage` targets are available only if the GL version is
/// 4.3 or greater.
/// - The `Query` target is available only if the GL version is 4.4 or greater.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if `size` is negative.
/// - `GL_INVALID_OPERATION` is generated if the reserved buffer object name 0 is bound to target.
/// - `GL_OUT_OF_MEMORY` is generated if the GL is unable to create a data store with the
/// specified size.
fn buffer_data_raw(target: BufferTarget, size: isize, data: *const (), usage: BufferUsage));
gl_proc!(glClear:
/// Clears buffers to preset values.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glClear)
///
/// Core since version 1.0
///
/// Sets the bitplane area of the window to values previously selected by `clear_color`,
/// `clear_depth`, and `clear_stencil`. Multiple color buffers can be cleared simultaneously by
/// selecting more than one buffer at a time using `draw_buffers`.
///
/// The pixel ownership test, the scissor test, dithering, and the buffer writemasks affect the
/// operation of `clear`. The scissor box bounds the cleared region. Alpha function, blend
/// function, logical operation, stenciling, texture mapping, and depth-buffering are ignored by
/// `clear`.
///
/// `clear` takes a single argument that is the bitwise OR of several values indicating which
/// buffer is to be cleared.
///
/// The values are as follows:
///
/// - `ClearBufferMask::Color` - Indicates the buffers currently enabled for color writing.
/// - `ClearBufferMask::Depth` - Indicates the depth buffer.
/// - `ClearBufferMask::Stencil` - Indicates the stencil buffer.
///
/// The value to which each buffer is cleared depends on the setting of the clear value for that
/// buffer.
///
/// # Notes
///
/// - If a buffer is not present, then a `clear` call directed at that buffer has no effect.
fn clear(mask: ClearBufferMask));
gl_proc!(glClearColor:
fn clear_color(red: f32, green: f32, blue: f32, alpha: f32));
gl_proc!(glCompileShader:
/// Compiles a shader object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glCompileShader)
///
/// Core since version 2.0
///
/// Compiles the source code strings that have been stored in the shader object specified
/// by shader.
///
/// The compilation status will be stored as part of the shader object's state. This value
/// will be set to `true` if the shader was compiled without errors and is ready for use,
/// and `false` otherwise. It can be queried by calling `get_shader` with arguments `shader`
/// and `GL_COMPILE_STATUS`.
///
/// Compilation of a shader can fail for a number of reasons as specified by the OpenGL
/// Shading Language Specification. Whether or not the compilation was successful, information
/// about the compilation can be obtained from the shader object's information log by
/// calling `get_shader_info_log`.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if shader is not a value generated by OpenGL.
fn compile_shader(shader: ShaderObject));
gl_proc!(glCreateProgram:
/// Creates a program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glCreateProgram)
///
/// Core since version 2.0
///
/// Creates an empty program object and returns a non-zero value by which it can be
/// referenced. A program object is an object to which shader objects can be attached.
/// This provides a mechanism to specify the shader objects that will be linked to create a
/// program. It also provides a means for checking the compatibility of the shaders that will
/// be used to create a program (for instance, checking the compatibility between a vertex
/// shader and a fragment shader). When no longer needed as part of a program object, shader
/// objects can be detached.
///
/// One or more executables are created in a program object by successfully attaching shader
/// objects to it with `attach_shader`, successfully compiling the shader objects with
/// `compile_shader`, and successfully linking the program object with `link_program`. These
/// executables are made part of current state when `use_program` is called. Program objects
/// can be deleted by calling `delete_program`. The memory associated with the program object
/// will be deleted when it is no longer part of current rendering state for any context.
///
/// # Notes
///
/// - Like buffer and texture objects, the name space for program objects may be shared
/// across a set of contexts, as long as the server sides of the contexts share the same
/// address space. If the name space is shared across contexts, any attached objects and
/// the data associated with those attached objects are shared as well.
/// - Applications are responsible for providing the synchronization across API calls when
/// objects are accessed from different execution threads.
///
/// # Errors
///
/// - This function returns 0 (the null program object) if an error occurs creating the
/// program object.
fn create_program() -> ProgramObject);
gl_proc!(glCreateShader:
/// Creates a shader object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glCreateShader)
///
/// Core since version 2.0
///
/// Creates an empty shader object and returns a non-zero value by which it can be referenced.
/// A shader object is used to maintain the source code strings that define a shader.
/// `shader_type` indicates the type of shader to be created. The following types are
/// supported:
///
/// - `VertexShader`
/// - `TessControlShader`
/// - `TessEvaluationShader`
/// - `GeometryShader`
/// - `FragmentShader`
/// - `ComputeShader`
///
/// When created, a shader object's `GL_SHADER_TYPE` parameter is set to the `shader_type`.
///
/// # Notes
///
/// - Like buffer and texture objects, the name space for shader objects may be shared across a
/// set of contexts, as long as the server sides of the contexts share the same address space.
/// If the name space is shared across contexts, any attached objects and the data associated
/// with those attached objects are shared as well.
/// - Applications are responsible for providing the synchronization across API calls when
/// objects are accessed from different execution threads.
/// - `ComputeShader` is available only if the GL version is 4.3 or higher.
///
/// # Errors
///
/// - This function returns 0 (the null shader object) if an error occurs creating the shader
/// object.
fn create_shader(shader_type: ShaderType) -> ShaderObject);
gl_proc!(glCullFace:
/// Specifies whether front- or back-faces should be culled.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glCullFace)
///
/// Core since version 1.0
///
/// Specifies whether front- or back-facing facets are culled (as specified by mode) when
/// facet culling is enabled. Facet culling is initially disabled. To enable and disable facet
/// culling, call `enable` and `disable` commands with the argument `CullFace`. Facets include
/// triangles, quadrilaterals, polygons, and rectangles.
///
/// `front_face` specifies which of the clockwise and counterclockwise facets are front-facing
/// and back-facing.
///
/// # Notes
///
/// - If `mode` is `FrontAndBack` no facets are drawn but other primitives such as points and
/// lines are drawn.
fn cull_face(mode: Face));
gl_proc!(glDebugMessageCallback:
fn debug_message_callback(
callback: Option<DebugMessageCallback>,
user_param: *mut ()
));
gl_proc!(glDeleteBuffers:
/// Deletes named buffer objects.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glDeleteBuffers)
///
/// Core since version 1.5
///
/// Deletes n buffer objects named by the elements of the array buffers. After a buffer object is
/// deleted, it has no contents, and its name is free for reuse (for example by glGenBuffers). If
/// a buffer object that is currently bound is deleted, the binding reverts to 0 (the absence of
/// any buffer object).
///
/// glDeleteBuffers silently ignores 0's and names that do not correspond to existing buffer
/// objects.
///
/// # Errors
///
/// `GL_INVALID_VALUE` is generated if `num_buffers` is negative.
fn delete_buffers(num_buffers: i32, buffers: *const BufferName));
gl_proc!(glDeleteProgram:
/// Deletes a program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glDeleteProgram)
///
/// Core since version 2.0
///
/// Frees the memory and invalidates the name associated with the program object specified by
/// `program_object`. This command effectively undoes the effects of a call to
/// `create_program`.
///
/// If a program object is in use as part of current rendering state it will be flagged for
/// deletion but it will not be deleted until it is no longer part of current state for any
/// rendering context. If a program object to be deleted has shader objects attached to it
/// those shader objects will be automatically detached but not deleted unless they have
/// already been flagged for deletion by a previous call to `delete_shader`.
///
/// A value of 0 (a "null" program object) for `program_object` will be silently ignored.
///
/// To determine whether a program object has been flagged for deletion call
/// `get_program_param` with arguments `program_object` and `DeleteStatus`.
fn delete_program(program_object: ProgramObject));
gl_proc!(glDeleteShader:
/// Deletes a shader object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glDeleteShader)
///
/// Core since version 2.0
///
/// Frees the memory and invalidates the name associated with the shader object specified by
/// `shader_object`. This command effectively undoes the effects of a call to `create_shader`.
///
/// If a shader object to be deleted is attached to a program object it will be flagged for
/// deletion but it will not be deleted until it is no longer attached to any program object,
/// for any rendering context (i.e., it must be detached from wherever it was attached before
/// it will be deleted).
///
/// To determine whether an object has been flagged for deletion call `get_shader_param` with
/// arguments `shader_object` and `DeleteStatus`.
fn delete_shader(shader_object: ShaderObject));
gl_proc!(glDeleteQueries:
/// Deletes named query objects.
///
/// [Official docs](https://www.opengl.org/sdk/docs/man/docbook4/xhtml/glDeleteQueries.xml)
///
/// Core since version 1.5
///
/// Deletes `count` query objects named by the elements of the array `queries`. After a
/// query object is deleted, it has no contents, and its name is free for reuse (for
/// example by `gen_queries()`).
///
/// `delete_queries` silently ignores 0's and names that do not correspond to existing query
/// objects. If one of the query objects to be deleted is currently active, the name becomes
/// unused, but the underlying query object is not deleted until it is no longer active.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if `count` is negative.
fn delete_queries(count: i32, queries: *const QueryObject));
gl_proc!(glDeleteTextures:
/// Deletes named textures.
///
/// Deletes `count` textures named by the elements of the array `textures`. After a texture
/// is deleted it has no contents or dimensionality and its name is free for reuse (for
/// example by `gen_textures`). If a texture that is currently bound is deleted the binding
/// reverts to 0 (the default texture).
///
/// `delete_textures` silently ignores 0's and names that do not correspond to existing
/// textures.
fn delete_textures(count: u32, textures: *mut TextureObject));
gl_proc!(glDeleteVertexArrays:
/// Deletes name vertex array objects.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glDeleteVertexArrays)
///
/// Core since version 3.0
///
/// Deletes n vertex array objects whose names are stored in the array addressed by arrays. Once a
/// vertex array object is deleted it has no contents and its name is again unused. If a vertex
/// array object that is currently bound is deleted, the binding for that object reverts to zero
/// and the default vertex array becomes current. Unused names in arrays are silently ignored, as
/// is the value zero.
///
/// # Errors
///
/// `GL_INVALID_VALUE` is generated if `num_arrays` is negative.
fn delete_vertex_arrays(num_arrays: i32, arrays: *const VertexArrayName));
gl_proc!(glDepthFunc:
/// Specifies the value used for the depth buffer comparison.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glDepthFunc)
///
/// Core since version 1.0
///
/// Specifies the function used to compare each incoming pixel depth value with the depth
/// value present in the depth buffer. The comparison is performed only if depth testing is
/// enabled (see `enable` and `disable` of `DepthTest`).
///
/// `func` specifies the conditions under which the pixel will be drawn. The comparison
/// functions are as follows:
///
/// - `Never` - Never passes.
/// - `Less` - Passes if the incoming depth value is less than the stored depth value.
/// - `Equal` - Passes if the incoming depth value is equal to the stored depth value.
/// - `LessThanOrEqual` - Passes if the incoming depth value is less than or equal to the
/// stored depth value.
/// - `Greater` - Passes if the incoming depth value is greater than the stored depth value.
/// - `NotEqual` - Passes if the incoming depth value is not equal to the stored depth value.
/// - `GreaterThanOrEqual` - Passes if the incoming depth value is greater than or equal to
/// the stored depth value.
/// - `Always` - Always passes.
///
/// The initial value of `func` is `Less`. Initially depth testing is disabled. If depth
/// testing is disabled or if no depth buffer exists it is as if the depth test always passes.
fn depth_func(func: Comparison));
gl_proc!(glDetachShader:
/// Detaches a shader object from a program object to which it is attached.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glDetachShader)
///
/// Cores since version 2.0
///
/// Detaches the shader object specified by `shader_object` from the program object specified
/// by `program_object`. This command can be used to undo the effect of the command
/// `attach_shader`.
///
/// If `shader_object` has already been flagged for deletion by a call to `delete_shader` and
/// it is not attached to any other program object it will be deleted after it has been
/// detached.
///
/// # Errors
///
/// - `GL_INVALID_OPERATION` is generated if `shader_object` is not attached to
/// `program_object`.
fn detach_shader(program_object: ProgramObject, shader_object: ShaderObject));
gl_proc!(glDisable:
/// Disables server-side GL capabilities.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glEnable)
///
/// Core since version 1.0
///
/// Disables various server capabilities. Use `is_enabled` or `get` to determine the current
/// setting of any capability. The initial value for each capability with the exception of
/// `Diter` and `Multisample` is `false`. The initial value for `Dither` and `Multisample` is
/// `true`.
fn disable(capability: ServerCapability));
gl_proc!(glDisableVertexAttribArray:
/// Disables a generic vertex attribute array.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glEnableVertexAttribArray)
///
/// Core since version 2.0
///
/// Disables the generic vertex attribute array specified by `attrib`. By default, all client-side
/// capabilities are disabled, including all generic vertex attribute arrays. If enabled the
/// values in the generic vertex attribute array will be accessed and used for rendering when
/// calls are made to vertex array commands such as `draw_arrays`, `draw_elements`,
/// `draw_range_elements`, `multi_draw_elements`, or `multi_draw_arrays`.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if the index represented by `attrib` is greater than or
/// equal to `GL_MAX_VERTEX_ATTRIBS`.
/// - `GL_INVALID_OPERATION` is generated if no vertex array object is bound.
fn disable_vertex_attrib_array(attrib: AttributeLocation));
gl_proc!(glDrawArrays:
/// Renders primitives from array data.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glDrawArrays)
///
/// Core since version 1.1
///
/// Specifies multiple geometric primitives with very few subroutine calls. Instead of calling a
/// GL procedure to pass each individual vertex, normal, texture coordinate, edge flag, or color,
/// you can prespecify separate arrays of vertices, normals, and colors and use them to construct
/// a sequence of primitives with a single call to `draw_arrays`.
///
/// When `draw_arrays` is called it uses `count` sequential elements from each enabled array to
/// construct a sequence of geometric primitives beginning with element `first`. `mode` specifies
/// what kind of primitives are constructed and how the array elements construct those primitives.
///
/// Vertex attributes that are modified by `draw_arrays` have an unspecified value after
/// `draw_arrays` returns. Attributes that aren't modified remain well defined.
///
/// # Notes
///
/// - `GL_LINE_STRIP_ADJACENCY`, `GL_LINES_ADJACENCY`, `GL_TRIANGLE_STRIP_ADJACENCY`, and
/// `GL_TRIANGLES_ADJACENCY` are available only if the GL version is 3.2 or greater.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if `count` is negative.
/// - `GL_INVALID_OPERATION` is generated if a non-zero buffer object name is bound to an enabled
/// array and the buffer object's data store is currently mapped.
/// - `GL_INVALID_OPERATION` is generated if a geometry shader is active and mode is incompatible
/// with the input primitive type of the geometry shader in the currently installed program
/// object.
fn draw_arrays(mode: DrawMode, first: i32, count: i32));
gl_proc!(glDrawElements:
/// Renders primitives from array data.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glDrawElements)
///
/// Core since version 1.1
///
/// Specifies multiple geometric primitives with very few subroutine calls. Instead of calling
/// a GL function to pass each individual vertex, normal, texture coordinate, edge flag, or
/// color, you can prespecify separate arrays of vertices, normals, and so on, and use them
/// to construct a sequence of primitives with a single call to `draw_elements`.
///
/// When `draw_elements` is called it uses `count` sequential elements from an enabled array,
/// starting at `offset` (interpreted as a byte count) to construct a sequence of geometric
/// primitives. `mode` specifies what kind of primitives are constructed and how the array
/// elements construct these primitives. If more than one array is enabled, each is used.
///
/// Vertex attributes that are modified by `draw_elements` have an unspecified value after
/// `draw_elements` returns. Attributes that aren't modified maintain their previous values.
///
/// # Notes
///
/// - `GL_LINE_STRIP_ADJACENCY`, `GL_LINES_ADJACENCY`, `GL_TRIANGLE_STRIP_ADJACENCY` and
/// `GL_TRIANGLES_ADJACENCY` are available only if the GL version is 3.2 or greater.
/// - `draw_elements` is included in display lists. If `draw_elements` is entered into a
/// display list the necessary array data (determined by the array pointers and enables)
/// is also entered into the display list. Because the array pointers and enables are
/// client-side state their values affect display lists when the lists are created, not
/// when the lists are executed.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if count is negative.
/// - `GL_INVALID_OPERATION` is generated if a geometry shader is active and mode is
/// incompatible with the input primitive type of the geometry shader in the currently
/// installed program object.
/// - `GL_INVALID_OPERATION` is generated if a non-zero buffer object name is bound to an
/// enabled array or the element array and the buffer object's data store is currently
/// mapped.
fn draw_elements(mode: DrawMode, count: i32, index_type: IndexType, offset: usize));
gl_proc!(glEnable:
/// Enables server-side GL capabilities.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glEnable)
///
/// Core since version 1.0
///
/// Enables various server capabilities. Use `is_enabled` or `get` to determine the current
/// setting of any capability. The initial value for each capability with the exception of
/// `Diter` and `Multisample` is `false`. The initial value for `Dither` and `Multisample` is
/// `true`.
fn enable(capability: ServerCapability));
gl_proc!(glEndQuery:
/// Delimits the end of a query object.
///
/// TODO: Add documentation.
fn end_query(query_type: QueryType));
gl_proc!(glEnableVertexAttribArray:
/// Enables a generic vertex attribute array.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glEnableVertexAttribArray)
///
/// Core since version 2.0
///
/// Enables the generic vertex attribute array specified by `attrib`. By default, all client-side
/// capabilities are disabled, including all generic vertex attribute arrays. If enabled the
/// values in the generic vertex attribute array will be accessed and used for rendering when
/// calls are made to vertex array commands such as `draw_arrays`, `draw_elements`,
/// `draw_range_elements`, `multi_draw_elements`, or `multi_draw_arrays`.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if the index represented by `attrib` is greater than or
/// equal to `GL_MAX_VERTEX_ATTRIBS`.
/// - `GL_INVALID_OPERATION` is generated if no vertex array object is bound.
fn enable_vertex_attrib_array(attrib: AttributeLocation));
gl_proc!(glFinish:
/// TODO: Add documentation.
fn finish());
gl_proc!(glFlush:
/// TODO: Add documentation.
fn flush());
gl_proc!(glFrontFace:
/// Defines front- and back-facing polygons.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glFrontFace)
///
/// Core since version 1.0
///
/// In a scene composed entirely of opaque closed surfaces, back-facing polygons are never
/// visible. Eliminating these invisible polygons has the obvious benefit of speeding up the
/// rendering of the image. To enable and disable elimination of back-facing polygons, call
/// `enable` and `disable` with argument `CullFace`.
///
/// The projection of a polygon to window coordinates is said to have clockwise winding if an
/// imaginary object following the path from its first vertex, its second vertex, and so on,
/// to its last vertex, and finally back to its first vertex, moves in a clockwise direction
/// about the interior of the polygon. The polygon's winding is said to be counterclockwise if
/// the imaginary object following the same path moves in a counterclockwise direction about
/// the interior of the polygon. `front_face` specifies whether polygons with clockwise
/// winding in window coordinates, or counterclockwise winding in window coordinates, are
/// taken to be front-facing. Passing `CounterClockwise` to `mode` selects counterclockwise
/// polygons as front-facing; `Clockwise` selects clockwise polygons as front-facing.
/// By default counterclockwise polygons are taken to be front-facing.
fn front_face(mode: WindingOrder));
gl_proc!(glGenBuffers:
/// Generates buffer object names.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGenBuffers)
///
/// Core since version 1.5
///
/// glGenBuffers returns n buffer object names in buffers. There is no guarantee that the names
/// form a contiguous set of integers; however, it is guaranteed that none of the returned names
/// was in use immediately before the call to glGenBuffers.
///
/// Buffer object names returned by a call to glGenBuffers are not returned by subsequent calls,
/// unless they are first deleted with glDeleteBuffers.
///
/// No buffer objects are associated with the returned buffer object names until they are first
/// bound by calling glBindBuffer.
///
/// # Errors
///
/// `GL_INVALID_VALUE` is generated if `num_buffers` is negative.
fn gen_buffers(num_buffers: i32, buffers: *mut BufferName));
gl_proc!(glGenTextures:
/// Generates texture names.
///
/// Returns `count` texture names in `textures`. There is no guarantee that the names form a
/// contiguous set of integers; however, it is guaranteed that none of the returned names
/// was in use immediately before the call to `gen_textures`.
///
/// The generated textures have no dimensionality; they assume the dimensionality of the
/// texture target to which they are first bound (see `bind_texture`).
///
/// Texture names returned by a call to `gen_textures` are not returned by subsequent calls,
/// unless they are first deleted with `delete_textures`.
fn gen_textures(count: u32, textures: *mut TextureObject));
gl_proc!(glGenQueries:
/// Generates query object names.
///
/// Returns `count` query object names in `queries`. There is no guarantee that the names
/// form a contiguous set of integers; however, it is guaranteed that none of the returned
/// names was in use immediately before the call to `gen_queries()`.
///
/// Query object names returned by a call to `gen_queries()` are not returned by subsequent
/// calls, unless they are first deleted with `delete_queries()`.
///
/// No query objects are associated with the returned query object names until they are first
/// used by calling `begin_query()`.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if `count` is negative.
fn gen_queries(count: i32, queries: *mut QueryObject));
gl_proc!(glGenVertexArrays:
/// Generates vertex array object names.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGenVertexArrays)
///
/// Core since version 3.0
///
/// Returns `num_arrays` vertex array object names in arrays. There is no guarantee that the names
/// form a contiguous set of integers; however, it is guaranteed that none of the returned names
/// was in use immediately before the call to `gen_vertex_arrays`.
///
/// Vertex array object names returned by a call to `gen_vertex_arrays` are not returned by
/// subsequent calls, unless they are first deleted with `delete_vertex_arrays`.
///
/// The names returned in arrays are marked as used, for the purposes of `gen_vertex_arrays` only,
/// but they acquire state and type only when they are first bound.
///
/// # Errors
///
/// `GL_INVALID_VALUE` is generated if `num_arrays` is negative.
fn gen_vertex_arrays(num_arrays: i32, arrays: *mut VertexArrayName));
gl_proc!(glGetAttribLocation:
/// Returns the location of an attribute variable.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGetAttribLocation)
///
/// Core since 2.0
///
/// Queries the previously linked program object specified by `program` for the attribute
/// variable specified by `name` and returns the index of the generic vertex attribute that is
/// bound to that attribute variable. If `name` is a matrix attribute variable, the index of
/// the first column of the matrix is returned. If the named attribute variable is not an
/// active attribute in the specified program object or if name starts with the reserved
/// prefix "gl_" a value of -1 is returned.
///
/// The association between an attribute variable name and a generic attribute index can be
/// specified at any time by calling `bind_attrib_location`. Attribute bindings do not go
/// into effect until `link_program` is called. After a program object has been linked
/// successfully, the index values for attribute variables remain fixed until the next link
/// command occurs. The attribute values can only be queried after a link if the link was
/// successful. `get_attrib_location` returns the binding that actually went into effect the
/// last time `link_program` was called for the specified program object. Attribute bindings
/// that have been specified since the last link operation are not returned by
/// `get_attrib_location`.
///
/// # Errors
///
/// - `GL_INVALID_OPERATION` is generated if `program` has not been successfully linked.
fn get_attrib_location(program: ProgramObject, name: *const u8) -> i32);
gl_proc!(glGetInteger64v:
/// Returns the value for simple state variables.
///
/// TODO: Add documentation.
fn get_i64v(name: Integer64Name, params: *mut i64));
gl_proc!(glGetIntegerv:
/// Returns the value for simple state variables.
///
/// These four commands return values for simple state variables in GL. `name` is a symbolic
/// constant indicating the state variable to be returned, and params is a pointer to an
/// array of the indicated type in which to place the returned data.
///
/// Type conversion is performed if params has a different type than the state variable
/// value being requested. If glGetBooleanv is called, a floating-point (or integer) value
/// is converted to GL_FALSE if and only if it is 0.0 (or 0). Otherwise, it is converted to
/// GL_TRUE. If glGetIntegerv is called, boolean values are returned as GL_TRUE or GL_FALSE,
/// and most floating-point values are rounded to the nearest integer value. Floating-point
/// colors and normals, however, are returned with a linear mapping that maps 1.0 to the
/// most positive representable integer value and -1.0-1.0 to the most negative representable
/// integer value. If glGetFloatv or glGetDoublev is called, boolean values are returned as
/// GL_TRUE or GL_FALSE, and integer values are converted to floating-point values.
///
/// The following values for `name` are accepted:
///
/// - `MajorVersion` - `params` returns one value, the major version number of the OpenGL API
/// supported by the current context.
/// - `MinorVersion` - `params` returns one value, the minor version number of the OpenGL API
/// supported by the current context.
/// - GL_NUM_EXTENSIONS - `params` returns one value, the number of extensions supported by
/// the GL implementation for the current context. See `get_string`.
fn get_integers(name: IntegerName, params: *mut i32));
gl_proc!(glGetProgramInfoLog:
/// Returns the information log for the program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGetProgramInfoLog)
///
/// Core since version 2.0
///
/// Returns the information log for the specified program object. The information log for
/// a program object is modified when the program object is linked or validated. The string
/// that is returned will be null terminated.
///
/// `get_program_info_log` returns in `log_out` as much of the information log as it can,
/// up to a maximum of `max_length` characters. The number of characters actually returned,
/// excluding the null termination character, is specified by `length_out`. If the length of
/// the returned string is not required, a value of 0 can be passed in the length argument.
/// The size of the buffer required to store the returned information log can be obtained by
/// calling `get_program` with the value `InfoLogLength`.
///
/// The information log for a program object is either an empty string, or a string
/// containing information about the last link operation, or a string containing information
/// about the last validation operation. It may contain diagnostic messages, warning
/// messages, and other information. When a program object is created, its information log
/// will be a string of length 0.
///
/// # Notes
///
/// - The information log for a program object is the OpenGL implementer's primary mechanism
/// for conveying information about linking and validating. Therefore, the information log
/// can be helpful to application developers during the development process, even when
/// these operations are successful. Application developers should not expect different
/// OpenGL implementations to produce identical information logs.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if program is not a value generated by OpenGL.
/// - `GL_INVALID_OPERATION` is generated if program is not a program object.
/// - `GL_INVALID_VALUE` is generated if `max_length` is less than 0.
fn get_program_info_log(
program: ProgramObject,
max_length: i32,
length_out: *mut i32,
log_out: *mut u8));
gl_proc!(glGetProgramiv:
/// Returns a parameter from a program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGetProgram)
///
/// Core since version 2.0
///
/// Returns in `param_out` the value of a parameter for a specific program object. The
/// following parameters are defined:
///
/// - `DeleteStatus` - `param_out` returns `true` if program is currently flagged for
/// deletion, and `false` otherwise.
/// - `LinkStatus` - `param_out` returns `true` if the last link operation on program was
/// successful, and `false` otherwise.
/// - `ValidateStatus` - `param_out` returns `true` or if the last validation operation on
/// program was successful, and `false` otherwise.
/// - `InfoLogLength` - `param_out` returns the number of characters in the information log
/// for program including the null termination character (i.e., the size of the character
/// buffer required to store the information log). If program has no information log, a
/// value of 0 is returned.
/// - `AttachedShaders` - `param_out` returns the number of shader objects attached to program.
/// - `ActiveAtomicCounterBuffers` - `param_out` returns the number of active attribute
/// atomic counter buffers used by program.
/// - `ActiveAttributes` - `param_out` returns the number of active attribute variables
/// for program.
/// - `ActiveAttributeMaxLength` - `param_out` returns the length of the longest active
/// attribute name for program, including the null termination character (i.e., the size of
/// the character buffer required to store the longest attribute name). If no active
/// attributes exist, 0 is returned.
/// - `ActiveUniforms` - `param_out` returns the number of active uniform variables for program.
/// - `ActiveUniformMaxLength` - `param_out` returns the length of the longest active
/// uniform variable name for program, including the null termination character (i.e., the
/// size of the character buffer required to store the longest uniform variable name). If
/// no active uniform variables exist, 0 is returned.
/// - `ProgramBinaryLength` - `param_out` returns the length of the program binary, in bytes
/// that will be returned by a call to `get_program_binary`. When a progam's `LinkStatus`
/// is `false`, its program binary length is zero.
/// - `ComputeWorkGroupSize` - `param_out` returns an array of three integers containing the
/// local work group size of the compute program as specified by its input layout
/// qualifier(s). program must be the name of a program object that has been previously
/// linked successfully and contains a binary for the compute shader stage.
/// - `TransformFeedbackBufferMode` - `param_out` returns a symbolic constant indicating the
/// buffer mode used when transform feedback is active. This may be `SeparateAttribs`
/// or `InterleavedAttribs`.
/// - `TransformFeedbackVaryings` - `param_out` returns the number of varying variables to
/// capture in transform feedback mode for the program.
/// - `TransformFeedbackVaryingMaxLength` - `param_out` returns the length of the longest
/// variable name to be used for transform feedback, including the null-terminator.
/// - `GeometryVerticesOut` - `param_out` returns the maximum number of vertices that the
/// geometry shader in program will output.
/// - `GeometryInputType` - `param_out` returns a symbolic constant indicating the primitive
/// type accepted as input to the geometry shader contained in program.
/// - `GeometryOutputType` - `param_out` returns a symbolic constant indicating the primitive
/// type that will be output by the geometry shader contained in program.
///
/// # Notes
///
/// - `ActiveUniformBlocks` and `ActiveUniformBlockMaxNameLength` are available only if the
/// GL version 3.1 or greater.
/// - `GeometryVerticesOut`, `GeometryInputType` and `GeometryOutputType` are accepted only
/// if the GL version is 3.2 or greater.
/// - `ComputeWorkGroupSize` is accepted only if the GL version is 4.3 or greater.
/// - If an error is generated, no change is made to the contents of params.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if program is not a value generated by OpenGL.
/// - `GL_INVALID_OPERATION` is generated if program does not refer to a program object.
/// - `GL_INVALID_OPERATION` is generated if `param_type` is `GeometryVerticesOut`,
/// `GeometryInputType`, or `GeometryOutputType`, and program does not contain a
/// geometry shader.
/// - `GL_INVALID_OPERATION` is generated if `param_type` is `ComputeWorkGroupSize` and
/// program does not contain a binary for the compute shader stage.
fn get_program_param(
program: ProgramObject,
param_type: ProgramParam,
param_out: *mut i32));
gl_proc!(glGetQueryObjecti64v:
/// Returns the parameters of a query object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGetQueryObject)
///
/// Core since version 3.3
///
/// Returns in `params` a selected parameter of the query object specified by `query`.
///
/// TODO: Add documentation.
fn get_query_object_i64v(query: QueryObject, result_type: QueryResultType, params: *mut i64));
gl_proc!(glGetQueryObjectui64v:
/// Returns the parameters of a query object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGetQueryObject)
///
/// Core since version 3.3
///
/// Returns in `params` a selected parameter of the query object specified by `query`.
///
/// TODO: Add documentation.
fn get_query_object_u64v(query: QueryObject, result_type: QueryResultType, params: *mut u64));
gl_proc!(glGetShaderInfoLog:
/// Returns the information log for a shader object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGetShaderInfoLog)
///
/// Core since version 2.0
///
/// Returns the information log for the specified shader object. The information log for a
/// shader object is modified when the shader is compiled. The string that is returned will
/// be null terminated.
///
/// `get_shader_info_log` returns in `log_out` as much of the information log as it can, up
/// to a maximum of `max_length` characters. The number of characters actually returned,
/// excluding the null termination character, is specified by `length_out`. If the length of the
/// returned string is not required, a value of 0 can be passed in the `length_out` argument. The
/// size of the buffer required to store the returned information log can be obtained by
/// calling `get_shader` with the value `InfoLogLength`.
///
/// The information log for a shader object is a string that may contain diagnostic messages,
/// warning messages, and other information about the last compile operation. When a shader
/// object is created, its information log will be a string of length 0.
///
/// # Notes
///
/// - The information log for a shader object is the OpenGL implementer's primary mechanism
/// for conveying information about the compilation process. Therefore, the information
/// log can be helpful to application developers during the development process, even when
/// compilation is successful. Application developers should not expect different OpenGL
/// implementations to produce identical information logs.
///
/// # Errors
///
/// - `InvalidValue` is generated if shader is not a value generated by OpenGL.
/// - `InvalidOperation` is generated if shader is not a shader object.
/// - `InvalidValue` is generated if maxLength is less than 0.
fn get_shader_info_log(
shader: ShaderObject,
max_length: i32,
length_out: *mut i32,
log_out: *mut u8));
gl_proc!(glGetShaderiv:
/// Returns a parameter from a shader object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGetShader)
///
/// Core since version 2.0
///
/// glGetShader returns in params the value of a parameter for a specific shader object. The following parameters are defined:
///
/// - `ShaderType` - params returns `VertexShader` if shader is a vertex shader object,
/// `GeometryShader` if shader is a geometry shader object, and `FragmentShader` if shader
/// is a fragment shader object.
/// - `DeleteStatus` - params returns `tre` if shader is currently flagged for deletion, and
/// `false` otherwise.
/// - `CompileStatus` - params returns `true` if the last compile operation on shader was
/// successful, and `false` otherwise.
/// - `InfoLogLength` - params returns the number of characters in the information log for
/// shader including the null termination character (i.e., the size of the character buffer
/// required to store the information log). If shader has no information log, a value of 0
/// is returned.
/// - `ShaderSourceLength` - params returns the length of the concatenation of the source
/// strings that make up the shader source for the shader, including the null termination
/// character. (i.e., the size of the character buffer required to store the shader source).
/// If no source code exists 0 is returned.
///
/// # Notes
///
/// - If an error is generated, no change is made to the contents of params.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if shader is not a value generated by OpenGL.
/// - `GL_INVALID_OPERATION` is generated if shader does not refer to a shader object.
fn get_shader_param(shader: ShaderObject, param_type: ShaderParam, param_out: *mut i32));
gl_proc!(glGetString:
/// Returns a string describing the current OpenGL.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGetString)
///
/// Core since version 1.0
///
/// Returns a pointer to a static string describing some aspect of the current GL
/// connection. name can be one of the following:
/// - `Vendor` - Returns the company responsible for this GL implementation. This name does
/// not change from release to release.
/// - `Renderer` - Returns the name of the renderer. This name is typically specific to a
/// particular configuration of a hardware platform. It does not change from release to
/// release.
/// - `Version` - Returns a version or release number.
/// - `ShadingLanguageVersion` - Returns a version or release number for the shading language.
///
/// Strings `Vendor` and `Renderer` together uniquely specify a platform. They do not change
/// from release to release and should be used by platform-recognition algorithms.
///
/// The `Version` and `ShadingLanguageVersion` strings retrieved from `get_string()` begin
/// with a version number. The version number uses one of these forms:
///
/// ```
/// major_number.minor_number
/// ```
///
/// or
///
/// ```
/// major_number.minor_number.release_number
/// ```
///
/// Vendor-specific information may follow the version number. Its format depends on the
/// implementation, but a space always separates the version number and the vendor-specific
/// information.
fn get_string(name: StringName) -> *const i8);
gl_proc!(glUniform1f:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_f32x1` operates on the program object that was made part
/// of current state by calling `use_program`.
///
/// The command `uniform_f32x1` is used to change the value of the uniform variable specified by
/// `location` using the value passed as arguments. The number specified in the command should
/// match the number of components in the data type of the specified uniform variable (i.e.
/// `uniform_f32x1` should be used to set a `float` variable).
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_f32x1(location: UniformLocation, value: f32));
gl_proc!(glUniform1fv:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_f32x1` operates on the program object that was made part
/// of current state by calling `use_program`.
///
/// The command `uniform_f32x4v` can be used to modify a single uniform variable or a uniform
/// variable array. These commands pass a count and a pointer to the values to be loaded into
/// a uniform variable or a uniform variable array. A count of 1 should be used if modifying
/// the value of a single uniform variable, and a count of 1 or greater can be used to modify
/// an entire array or part of an array. When loading n elements starting at an arbitrary
/// position m in a uniform variable array, elements m + n - 1 in the array will be replaced
/// with the new values. If m + n - 1 is larger than the size of the uniform variable array,
/// values for all array elements beyond the end of the array will be ignored.
///
/// The number of `f32` values pointed to by `data` should be 4 * `count`.
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_f32x1v(uniform: UniformLocation, count: i32, data: *const f32));
gl_proc!(glUniform1ui:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location()`. `uniform_u32x1()` operates on the program object that was made part
/// of current state by calling `use_program()`.
///
/// The command `uniform_u32x1()` is used to change the value of the uniform variable specified by
/// `location` using the value passed as arguments. The number specified in the command should
/// match the number of components in the data type of the specified uniform variable (i.e.
/// `uniform_u32x1()` should be used to set a `uint` variable).
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Notes
///
/// - `uniform_i32x1()` and `uniform_i32v()` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_u32x1(location: UniformLocation, value: u32));
gl_proc!(glUniform2f:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_f32x2` operates on the program object that was made part
/// of current state by calling `use_program`.
///
/// The command `uniform_f32x2` is used to change the value of the uniform variable specified by
/// `location` using the value passed as arguments. The number specified in the command should
/// match the number of components in the data type of the specified uniform variable (i.e.
/// `uniform_f32x2` should be used to set a `vec2` variable).
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_f32x2(location: UniformLocation, x: f32, y: f32));
gl_proc!(glUniform3f:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_f32x3` operates on the program object that was made part
/// of current state by calling `use_program`.
///
/// The command `uniform_f32x4` is used to change the value of the uniform variable specified by
/// `location` using the value passed as arguments. The number specified in the command should
/// match the number of components in the data type of the specified uniform variable (i.e.
/// `uniform_f32x3` should be used to set a `vec3` variable).
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_f32x3(location: UniformLocation, x: f32, y: f32, z: f32));
gl_proc!(glUniform4f:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_f32x4` operates on the program object that was made part
/// of current state by calling `use_program`.
///
/// The command `uniform_f32x4` is used to change the value of the uniform variable specified by
/// `location` using the value passed as arguments. The number specified in the command should
/// match the number of components in the data type of the specified uniform variable (i.e.
/// `uniform_f32x4` should be used to set a `vec4` variable).
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_f32x4(location: UniformLocation, x: f32, y: f32, z: f32, w: f32));
gl_proc!(glUniform1i:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_i32x1` operates on the program object that was made part
/// of current state by calling `use_program`.
///
/// The command `uniform_i32x1` is changes the value of the uniform variable specified by
/// `location` using the value passed as arguments. The number specified in the command should
/// match the number of components in the data type of the specified uniform variable (i.e.
/// `uniform_i32x1` should be used to set an `int` or sampler variable).
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32x1v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_i32x1(location: UniformLocation, value: i32));
gl_proc!(glUniform1iv:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_i32x1v` operates on the program object that was made part
/// of current state by calling `use_program`.
///
/// The command `uniform_i32x1v` can be used to modify a single uniform variable or a uniform
/// variable array. This command passes a count and a pointer to the values to be loaded into
/// a uniform variable or a uniform variable array. A count of 1 should be used if modifying
/// the value of a single uniform variable, and a count of 1 or greater can be used to modify
/// an entire array or part of an array. When loading n elements starting at an arbitrary
/// position m in a uniform variable array, elements `m + n - 1` in the array will be replaced
/// with the new values. If m` + n - 1` is larger than the size of the uniform variable array,
/// values for all array elements beyond the end of the array will be ignored.
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32x1v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_i32x1v(location: UniformLocation, count: i32, data: *const i32));
gl_proc!(glUniform3fv:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_f32x1` operates on the program object that was made part
/// of current state by calling `use_program`.
///
/// The command `uniform_f32x4v` can be used to modify a single uniform variable or a uniform
/// variable array. These commands pass a count and a pointer to the values to be loaded into
/// a uniform variable or a uniform variable array. A count of 1 should be used if modifying
/// the value of a single uniform variable, and a count of 1 or greater can be used to modify
/// an entire array or part of an array. When loading n elements starting at an arbitrary
/// position m in a uniform variable array, elements m + n - 1 in the array will be replaced
/// with the new values. If m + n - 1 is larger than the size of the uniform variable array,
/// values for all array elements beyond the end of the array will be ignored.
///
/// The number of `f32` values pointed to by `data` should be 4 * `count`.
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_f32x3v(uniform: UniformLocation, count: i32, data: *const f32));
gl_proc!(glUniform4fv:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_f32x1` operates on the program object that was made part
/// of current state by calling `use_program`.
///
/// The command `uniform_f32x4v` can be used to modify a single uniform variable or a uniform
/// variable array. These commands pass a count and a pointer to the values to be loaded into
/// a uniform variable or a uniform variable array. A count of 1 should be used if modifying
/// the value of a single uniform variable, and a count of 1 or greater can be used to modify
/// an entire array or part of an array. When loading n elements starting at an arbitrary
/// position m in a uniform variable array, elements m + n - 1 in the array will be replaced
/// with the new values. If m + n - 1 is larger than the size of the uniform variable array,
/// values for all array elements beyond the end of the array will be ignored.
///
/// The number of `f32` values pointed to by `data` should be 4 * `count`.
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_f32x4v(uniform: UniformLocation, count: i32, data: *const f32));
gl_proc!(glUniformMatrix4fv:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_matrix_f32x4v` operates on the program object that was
/// made part of current state by calling `use_program`.
///
/// The command `uniform_matrix_f32x4v` is used to modify a 4x4 matrix of `f32` values. If
/// `transpose` is `False` each matrix is assumed to be supplied in column major order. If
/// transpose is `True` each matrix is assumed to be supplied in row major order. The `count`
/// argument indicates the number of matrices to be passed. A count of 1 should be used if
/// modifying the value of a single matrix, and a count greater than 1 can be used to modify
/// an array of matrices.
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Params
///
/// - `location` - Specifies the location of the uniform value to be modified.
/// - `count` - Specifies the number of matrices that are to be modified. This should be 1 if
/// the targeted uniform variable is not an array of matrices, and 1 or more if it is an
/// array of matrices.
/// - `transpose` - Specifies whether to transpose the matrix as the values are loaded into
/// the uniform variable.
/// - `values` - Specifies a pointer to an array of `count` * 16 `f32` values that will be
/// used to update the specified uniform variable.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_matrix_f32x4v(
uniform: UniformLocation,
count: i32,
transpose: Boolean,
values: *const f32));
gl_proc!(glUniformMatrix3fv:
/// Specify the value of a uniform variable for the current program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUniform)
///
/// Core since version 2.0
///
/// Modifies the value of a uniform variable. The location of the uniform variable to be
/// modified is specified by `location`, which should be a value returned by
/// `get_uniform_location`. `uniform_matrix_f32x3v` operates on the program object that was
/// made part of current state by calling `use_program`.
///
/// The command `uniform_matrix_f32x3v` is used to modify a 3x3 matrix of `f32` values. If
/// `transpose` is `False` each matrix is assumed to be supplied in column major order. If
/// transpose is `True` each matrix is assumed to be supplied in row major order. The `count`
/// argument indicates the number of matrices to be passed. A count of 1 should be used if
/// modifying the value of a single matrix, and a count greater than 1 can be used to modify
/// an array of matrices.
///
/// All active uniform variables defined in a program object are initialized to 0 when the
/// program object is linked successfully. They retain the values assigned to them by a call
/// to `uniform_*` until the next successful link operation occurs on the program object,
/// when they are once again initialized to 0.
///
/// # Params
///
/// - `location` - Specifies the location of the uniform value to be modified.
/// - `count` - Specifies the number of matrices that are to be modified. This should be 1 if
/// the targeted uniform variable is not an array of matrices, and 1 or more if it is an
/// array of matrices.
/// - `transpose` - Specifies whether to transpose the matrix as the values are loaded into
/// the uniform variable.
/// - `values` - Specifies a pointer to an array of `count` * 16 `f32` values that will be
/// used to update the specified uniform variable.
///
/// # Notes
///
/// - `uniform_i32x1` and `uniform_i32v` are the only two functions that may be used to load
/// uniform variables defined as opaque types. Loading opaque types with any other function
/// will result in a `GL_INVALID_OPERATION` error.
/// - If count is greater than 1 and the indicated uniform variable is not an array, a
/// `GL_INVALID_OPERATION` error is generated and the specified uniform variable will remain
/// unchanged.
/// - Other than the preceding exceptions, if the type and size of the uniform variable as
/// defined in the shader do not match the type and size specified in the name of the
/// command used to load its value, a `GL_INVALID_OPERATION` error will be generated and
/// the specified uniform variable will remain unchanged.
/// - If `location` is a value other than -1 and it does not represent a valid uniform variable
/// location in the current program object, an error will be generated, and no changes will
/// be made to the uniform variable storage of the current program object. If location is
/// equal to -1, the data passed in will be silently ignored and the specified uniform
/// variable will not be changed.
fn uniform_matrix_f32x3v(
uniform: UniformLocation,
count: i32,
transpose: Boolean,
values: *const f32));
gl_proc!(glGetUniformLocation:
/// Returns the location of a uniform variable.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glGetUniformLocation)
///
/// Core since verion 2.0
///
/// Returns an integer that represents the location of a specific uniform variable within a
/// program object. name must be a null terminated string that contains no white space. name
/// must be an active uniform variable name in program that is not a structure, an array of
/// structures, or a subcomponent of a vector or a matrix. This function returns -1 if name
/// does not correspond to an active uniform variable in program, if name starts with the
/// reserved prefix "gl_", or if name is associated with an atomic counter or a named
/// uniform block.
///
/// Uniform variables that are structures or arrays of structures may be queried by calling
/// `get_uniform_location_raw` for each field within the structure. The array element
/// operator "[]" and the structure field operator "." may be used in name in order to select
/// elements within an array or fields within a structure. The result of using these
/// operators is not allowed to be another structure, an array of structures, or a
/// subcomponent of a vector or a matrix. Except if the last part of name indicates a
/// uniform variable array, the location of the first element of an array can be retrieved
/// by using the name of the array, or by using the name appended by "[0]".
///
/// The actual locations assigned to uniform variables are not known until the program object
/// is linked successfully. After linking has occurred, the command `get_uniform_location_raw`
/// can be used to obtain the location of a uniform variable. This location value can then be
/// passed to the `uniform_*` functions to set the value of the uniform variable or to
/// `get_uniform` in order to query the current value of the uniform variable. After a program
/// object has been linked successfully, the index values for uniform variables remain fixed
/// until the next link command occurs. Uniform variable locations and values can only be
/// queried after a link if the link was successful.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if program is not a value generated by OpenGL.
/// - `GL_INVALID_OPERATION` is generated if program is not a program object.
/// - `GL_INVALID_OPERATION` is generated if program has not been successfully linked.
fn get_uniform_location(program: ProgramObject, uniform_name: *const u8) -> i32);
gl_proc!(glLinkProgram:
/// Links a program object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glLinkProgram)
///
/// Core since version 2.0
///
/// Links the program object specified by `program`. If any shader objects of type
/// `VertexShader` are attached to `program`, they will be used to create an executable that
/// will run on the programmable vertex processor. If any shader objects of type
/// `GeometryShader` are attached to `program`, they will be used to create an executable that
/// will run on the programmable geometry processor. If any shader objects of type
/// `FragmentShader` are attached to `program`, they will be used to create an executable that
/// will run on the programmable fragment processor.
///
/// The status of the link operation will be stored as part of the program object's state.
/// This value will be set to `true` if the program object was linked without errors and is
/// ready for use, and `false` otherwise. It can be queried by calling `get_program` with
/// arguments program and `LinkStatus`.
///
/// As a result of a successful link operation, all active user-defined uniform variables
/// belonging to program will be initialized to 0, and each of the program object's active
/// uniform variables will be assigned a location that can be queried by calling
/// `get_uniform_location`. Also, any active user-defined attribute variables that have not
/// been bound to a generic vertex attribute index will be bound to one at this time.
///
/// Linking of a program object can fail for a number of reasons as specified in the OpenGL
/// Shading Language Specification. The following lists some of the conditions that will
/// cause a link error.
///
/// - The number of active attribute variables supported by the implementation has been
/// exceeded.
/// - The storage limit for uniform variables has been exceeded.
/// - The number of active uniform variables supported by the implementation has been exceeded.
/// - The main function is missing for the vertex, geometry or fragment shader.
/// - A varying variable actually used in the fragment shader is not declared in the same way
/// (or is not declared at all) in the vertex shader, or geometry shader shader if present.
/// - A reference to a function or variable name is unresolved.
/// - A shared global is declared with two different types or two different initial values.
/// - One or more of the attached shader objects has not been successfully compiled.
/// - Binding a generic attribute matrix caused some rows of the matrix to fall outside the
/// allowed maximum of `GL_MAX_VERTEX_ATTRIBS`.
/// - Not enough contiguous vertex attribute slots could be found to bind attribute matrices.
/// - The program object contains objects to form a fragment shader but does not contain
/// objects to form a vertex shader.
/// - The program object contains objects to form a geometry shader but does not contain
/// objects to form a vertex shader.
/// - The program object contains objects to form a geometry shader and the input primitive
/// type, output primitive type, or maximum output vertex count is not specified in any
/// compiled geometry shader object.
/// - The program object contains objects to form a geometry shader and the input primitive
/// type, output primitive type, or maximum output vertex count is specified differently
/// in multiple geometry shader objects.
/// - The number of active outputs in the fragment shader is greater than the value of
/// `GL_MAX_DRAW_BUFFERS`.
/// - The program has an active output assigned to a location greater than or equal to the
/// value of `GL_MAX_DUAL_SOURCE_DRAW_BUFFERS` and has an active output assigned an index
/// greater than or equal to one.
/// - More than one varying out variable is bound to the same number and index.
/// - The explicit binding assigments do not leave enough space for the linker to
/// automatically assign a location for a varying out array, which requires multiple
/// contiguous locations.
/// - The count specified by glTransformFeedbackVaryings is non-zero, but the program object
/// has no vertex or geometry shader.
/// - Any variable name specified to `transform_feedback_varyings` in the varyings array is
/// not declared as an output in the vertex shader (or the geometry shader, if active).
/// - Any two entries in the varyings array given `transform_feedback_varyings` specify the
/// same varying variable.
/// - The total number of components to capture in any transform feedback varying variable
/// is greater than the constant `GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS` and the
/// buffer mode is `GL_SEPARATE_ATTRIBS`.
/// - When a program object has been successfully linked, the program object can be made
/// part of current state by calling `use_program`. Whether or not the link operation was
/// successful, the program object's information log will be overwritten. The information
/// log can be retrieved by calling `get_program_info_log`.
///
/// `link_program` will also install the generated executables as part of the current
/// rendering state if the link operation was successful and the specified program object is
/// already currently in use as a result of a previous call to `use_program`. If the program
/// object currently in use is relinked unsuccessfully, its link status will be set to
/// `false`, but the executables and associated state will remain part of the current state
/// until a subsequent call to `use_program` removes it from use. After it is removed from
/// use, it cannot be made part of current state until it has been successfully relinked.
///
/// If program contains shader objects of type `VertexShader`, and optionally of type
/// `GeometryShader`, but does not contain shader objects of type `FragmentShader`, the
/// vertex shader executable will be installed on the programmable vertex processor, the
/// geometry shader executable, if present, will be installed on the programmable geometry
/// processor, but no executable will be installed on the fragment processor. The results of
/// rasterizing primitives with such a program will be undefined.
///
/// The program object's information log is updated and the program is generated at the time
/// of the link operation. After the link operation, applications are free to modify attached
/// shader objects, compile attached shader objects, detach shader objects, delete shader
/// objects, and attach additional shader objects. None of these operations affects the
/// information log or the program that is part of the program object.
///
/// # Notes
///
/// - If the link operation is unsuccessful any information about a previous link operation
/// on program is lost (i.e., a failed link does not restore the old state of program ).
/// Certain information can still be retrieved from program even after an unsuccessful
/// link operation. See for instance `get_active_attrib` and `get_active_uniform`.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if program is not a value generated by OpenGL.
/// - `GL_INVALID_OPERATION` is generated if program is not a program object.
/// - `GL_INVALID_OPERATION` is generated if program is the currently active program object
/// and transform feedback mode is active.
fn link_program(program: ProgramObject));
gl_proc!(glObjectLabel:
/// Labels a named object for use in debug messages.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glObjectLabel)
///
/// Core since version 4.3
///
/// Labels the object identified by `name` within the namespace given by `identifier`.
///
/// `label` points to a string that will be used to label the object. `length` contains the
/// number of characters in `label`. If `length` is negative, it is implied that label
/// contains a null-terminated string. If label is `NULL`, any debug label is effectively
/// removed from the object.
fn set_object_label(identifier: DebugMessageId, name: u32, length: i32, label: u8));
gl_proc!(glPolygonMode:
/// Selects the polygon rasterization mode.
///
/// [Wiki page](http://docs.gl/gl2/glPolygonMode)
///
/// Core since version 1.0
///
/// Controls the interpretation of polygons for rasterization. `face` describes which polygons
/// mode applies to: The polygon mode affects only the final rasterization of polygons. In
/// particular, a polygon's vertices are lit and the polygon is clipped and possibly culled
/// before these modes are applied.
///
/// Three modes are defined and can be specified in mode:
///
/// - `Point` - Polygon vertices that are marked as the start of a boundary edge are drawn as
/// points. Point attributes such as `GL_POINT_SIZE` and `GL_POINT_SMOOTH` control the
/// rasterization of the points. Polygon rasterization attributes other than
/// `GL_POLYGON_MODE` have no effect.
/// - `Line` - Boundary edges of the polygon are drawn as line segments. Line attributes such
/// as `GL_LINE_WIDTH` and `GL_LINE_SMOOTH` control the rasterization of the lines. Polygon
/// rasterization attributes other than `GL_POLYGON_MODE` have no effect.
/// - `Fill` - The interior of the polygon is filled. Polygon attributes such as
/// `GL_POLYGON_SMOOTH` control the rasterization of the polygon.
///
/// # Notes
///
/// Vertices are marked as boundary or nonboundary with an edge flag. Edge flags are generated
/// internally by the GL when it decomposes polygons; they can be set explicitly using
/// `edge_flag`.
fn polygon_mode(face: Face, mode: PolygonMode));
gl_proc!(glQueryCounter:
/// Records the GL time into a query object after all previous commands have reached the GL
/// server.
///
/// [Official docs](https://www.opengl.org/sdk/docs/man4/html/glQueryCounter.xhtml)
///
/// Core since version 3.3
///
/// Causes the GL to record the current time into the query object named `query`. The time
/// is recorded after all previous commands on the GL client and server state and the
/// framebuffer have been fully realized. When the time is recorded, the query result for
/// that object is marked available. `query_counter()` timer queries can be used within a
/// `begin_query()` / `end_query()` block where the target is `TimeElapsed` and it does not
/// affect the result of that query object.
///
/// # Errors
///
/// - `GL_INVALID_OPERATION` is generated if `query` is the name of a query object that is
/// already in use within a `begin_query()` / `end_query()` block.
/// - `GL_INVALID_VALUE` is generated if `query` is not the name of a query object returned
/// from a previous call to `gen_queries()`.
fn query_counter(query: QueryObject, target: QueryCounterTarget));
gl_proc!(glShaderSource:
/// Replaces the source code in a shader object.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glShaderSource)
///
/// Core since version 2.0
///
/// Sets the source code in `shader` to the source code in the array of strings specified by
/// `strings`. Any source code previously stored in the shader object is completely replaced.
/// The number of strings in the array is specified by count. If length is null, each string
/// is assumed to be null terminated. If length is a value other than 0, it points to an
/// array containing a string length for each of the corresponding elements of string. Each
/// element in the length array may contain the length of the corresponding string (the null
/// character is not counted as part of the string length) or a value less than 0 to indicate
/// that the string is null terminated. The source code strings are not scanned or parsed at
/// this time; they are simply copied into the specified shader object.
///
/// # Notes
///
/// - OpenGL copies the shader source code strings when glShaderSource is called, so an
/// application may free its copy of the source code strings immediately after the function
/// returns.
///
/// # Errors
///
/// - `GL_INVALID_OPERATION` is generated if shader is not a shader object.
/// - `GL_INVALID_VALUE` is generated if count is less than 0.
fn shader_source(
shader: ShaderObject,
count: i32,
strings: *const *const u8,
length: *const i32));
gl_proc!(glTexImage2D:
/// Specifies a two-dimensional texture image.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glTexImage2D)
///
/// Core since version 1.0
///
/// Texturing allows elements of an image array to be read by shaders.
///
/// To define texture images, call `tex_image_2d`. The arguments describe the parameters of
/// the texture image, such as height, width, width of the border, level-of-detail number
/// (see `tex_parameter`), and number of color components provided. The last three arguments
/// describe how the image is represented in memory.
///
/// If target is `ProxyTexture2d`, `ProxyTexture1dArray`, `ProxyTextureCubeMap`, or
/// `ProxyTextureRectangle`, no data is read from data, but all of the texture image state
/// is recalculated, checked for consistency, and checked against the implementation's
/// capabilities. If the implementation cannot handle a texture of the requested texture
/// size, it sets all of the image state to 0, but does not generate an error (see
/// `get_error`). To query for an entire mipmap array, use an image array level greater than
/// or equal to 1.
///
/// If target is `Texture2d`, `TextureRectangle` or one of the `TextureCubeMap` targets, data
/// is read from `data` as a sequence of signed or unsigned bytes, shorts, or longs, or
/// single-precision floating-point values, depending on type. These values are grouped into
/// sets of one, two, three, or four values, depending on format, to form elements. Each
/// byte in `data` is treated as eight 1-bit elements, with bit ordering determined by `UnpackLsbFirst`
/// (see `pixel_store`).
///
/// If target is `Texture1dArray`, data is interpreted as an array of one-dimensional images.
///
/// If a non-zero named buffer object is bound to the `PixelUnpackBuffer` target (see
/// `bind_buffer`) while a texture image is specified, data is treated as a byte offset into
/// the buffer object's data store.
///
/// The first element corresponds to the lower left corner of the texture image. Subsequent
/// elements progress left-to-right through the remaining texels in the lowest row of the
/// texture image, and then in successively higher rows of the texture image. The final
/// element corresponds to the upper right corner of the texture image.
///
/// format determines the composition of each element in data. It can assume one of these
/// symbolic values:
///
/// - `Red` - Each element is a single red component. The GL converts it to floating point
/// and assembles it into an RGBA element by attaching 0 for green and blue, and 1 for
/// alpha. Each component is clamped to the range [0,1].
/// - `Rg` - Each element is a red/green double. The GL converts it to floating point and
/// assembles it into an RGBA element by attaching 0 for blue, and 1 for alpha. Each
/// component is clamped to the range [0,1].
/// - `Rgb`, `Bgr` - Each element is an RGB (or BGR) triple. The GL converts it to floating point and
/// assembles it into an RGBA element by attaching 1 for alpha. Each component is clamped
/// to the range [0,1].
/// - `Rgba`, `Bgra` - Each element contains all four components. Each component is clamped
/// to the range [0,1].
/// - `DepthComponent` - Each element is a single depth value. The GL converts it to floating
/// point and clamps to the range [0,1].
/// - `DepthStencil` - Each element is a pair of depth and stencil values. The depth
/// component of the pair is interpreted as in `DepthComponent`. The stencil component is
/// interpreted based on specified the depth + stencil internal format.
///
/// If an application wants to store the texture at a certain resolution or in a certain
/// format, it can request the resolution and format with internalFormat. The GL will choose
/// an internal representation that closely approximates that requested by internalFormat,
/// but it may not match exactly. (The representations specified by `Red`, `Rg`, `Rgb`, and
/// `Rgba` must match exactly.)
///
/// `internal_format` may be one of the formats from the tables below:
///
/// > TODO: Add tables. Blech that's a lot of info to copy in.
///
/// # Parameters
///
/// * `target` - Specifies the target texture.
/// * `level` - Specifies the level-of-detail number. Level 0 is the base image level. Level
/// n is the nth mipmap reduction image. If target is `TextureRectangle` or
/// `ProxyTextureRectangle`, `level` must be 0.
/// * `internal_format` - Specifies the number of color components in the texture. Must be
/// one of base internal formats given in Table 1, one of the sized internal formats given
/// in Table 2, or one of the compressed internal formats given in Table 3, below.
/// * `width` - Specifies the width of the texture image. All implementations support texture
/// images that are at least 1024 texels wide.
/// * `height` - Specifies the height of the texture image, or the number of layers in a
/// texture array, in the case of the `Texture1dArray` and `ProxyTexture1dArray` targets.
/// All implementations support 2D texture images that are at least 1024 texels high, and
/// texture arrays that are at least 256 layers deep.
/// * `border` - This value must be 0.
/// * `format` - Specifies the format of the pixel data. For transfers of depth, stencil, or
/// depth/stencil data, you must use `DepthComponent`, `StencilIndex`, or `DepthStencil`,
/// where appropriate. For transfers of normalized integer or floating-point color image
/// data, you must use one of the following: `Red`, `Green`, `Blue`, `Rg`, `Rgb`, `Bgr`,
/// `Rgba`, and `Bgra`. For transfers of non-normalized integer data, you must use one of
/// the following: `RedInteger`, `GreenInteger`, `BlueInteger`, `RgInteger`, `RgbInteger`,
/// `BgrInteger`, `RgbaInteger`, and `BgraInteger`.
/// * `type` - Specifies the data type of the pixel data.
/// * `data` - Specifies a pointer to the image data in memory, or if a buffer is bound to
/// `PixelUnpackBuffer`, this provides an integer offset into the bound buffer object. If
/// a buffer is not bound to `PixelUnpackBuffer`, and this parameter is NULL, no
/// Pixel Transfer will be performed.
fn texture_image_2d(
target: Texture2dTarget,
level: i32,
internal_format: TextureInternalFormat,
width: i32,
height: i32,
border: i32,
format: TextureFormat,
data_type: TextureDataType,
data: *const ()));
gl_proc!(glTexParameteri:
/// Sets texture parameters.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glTexParameter)
///
/// Core since version 1.0
///
/// TODO: Ugh the docs for this one are annoying.
fn texture_parameter_i32(
target: TextureParameterTarget,
name: TextureParameterName,
param: i32));
gl_proc!(glUseProgram:
/// Installs a program as part of the current rendering state.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glUseProgram)
///
/// Core since version 2.0
///
/// Installs the program object specified by `program` as part of current rendering state.
/// One or more executables are created in a program object by successfully attaching shader
/// objects to it with `attach_shader`, successfully compiling the shader objects with
/// `compile_shader`, and successfully linking the program object with `link_program`.
///
/// A program object will contain an executable that will run on the vertex processor if it
/// contains one or more shader objects of type `VertexShader` that have been successfully
/// compiled and linked. A program object will contain an executable that will run on the
/// geometry processor if it contains one or more shader objects of type `GeometryShader` that
/// have been successfully compiled and linked. Similarly, a program object will contain an
/// executable that will run on the fragment processor if it contains one or more shader
/// objects of type `FragmentShader` that have been successfully compiled and linked.
///
/// While a program object is in use, applications are free to modify attached shader
/// objects, compile attached shader objects, attach additional shader objects, and detach
/// or delete shader objects. None of these operations will affect the executables that are
/// part of the current state. However, relinking the program object that is currently in
/// use will install the program object as part of the current rendering state if the link
/// operation was successful (see `link_program`). If the program object currently in use is
/// relinked unsuccessfully, its link status will be set to `false`, but the executables and
/// associated state will remain part of the current state until a subsequent call to
/// `use_program` removes it from use. After it is removed from use, it cannot be made part
/// of current state until it has been successfully relinked.
///
/// If `program` is zero (the null program object), then the current rendering state refers to
/// an invalid program object and the results of shader execution are undefined. However, this
/// is not an error.
///
/// If program does not contain shader objects of type `FragmentShader`, an executable will
/// be installed on the vertex, and possibly geometry processors, but the results of fragment
/// shader execution will be undefined.
///
/// # Notes
///
/// - Like buffer and texture objects, the name space for program objects may be shared
/// across a set of contexts, as long as the server sides of the contexts share the same
/// address space. If the name space is shared across contexts, any attached objects and
/// the data associated with those attached objects are shared as well.
/// - Applications are responsible for providing the synchronization across API calls when
/// objects are accessed from different execution threads.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if program is neither 0 nor a value generated by OpenGL.
/// - `GL_INVALID_OPERATION` is generated if program is not a program object.
/// - `GL_INVALID_OPERATION` is generated if program's most recent link operation was not
/// successful.
/// - `GL_INVALID_OPERATION` is generated if transform feedback mode is active.
fn use_program(program: ProgramObject));
gl_proc!(glVertexAttribPointer:
/// Defines an array of generic vertex attribute data.
///
/// [Wiki page](https://www.opengl.org/wiki/GLAPI/glVertexAttribPointer)
///
/// Core since version 2.0
///
/// Specifies the location and data format of the array of generic vertex attributes to use when
/// rendering.
///
/// If `normalize` is set to `true` it indicates that values stored in an integer format are to be
/// mapped to the range [-1,1] (for signed values) or [0,1] (for unsigned values) when they are
/// accessed and converted to floating point. Otherwise, values will be converted to floats
/// directly without normalization.
///
/// `vertex_attrib_pointer` specifies state for a generic vertex attribute array associated with a
/// shader attribute variable declared with 64-bit double precision components. `gl_type` must be
/// `Double`.
///
/// If offset is not 0 a non-zero named buffer object must be bound to the `BufferTarget::Array`
/// target (see `bind_buffer`), otherwise an error is generated. `offset` is treated as a byte
/// offset into the buffer object's data store. The buffer object binding
/// (`GL_ARRAY_BUFFER_BINDING`) is saved as generic vertex attribute array state
/// (`GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING`) for `attrib`.
///
/// When a generic vertex attribute array is specified `size`, `gl_type`, `normalize`, `stride`,
/// and `offset` are saved as vertex array state, in addition to the current vertex array buffer
/// object binding.
///
/// To enable and disable a generic vertex attribute array, call `enable_vertex_attrib_array` and
/// `disable_vertex_attrib_array`. If enabled the generic vertex attribute array is used when
/// `draw_arrays`, `multi_draw_arrays`, `draw_elements`, `multi_draw_elements`, or
/// `draw_range_elements` is called.
///
/// # Parameters
///
/// - `attrib` - Specifies the generic vertex attribute to be modified.
/// - `size` - Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4.
/// Additionally, the symbolic constant `GL_BGRA` is accepted by `vertex_attrib_pointer`. The
/// initial value is 4.
/// - `type` - Specifies the data type of each component in the array. The different functions
/// take different values. The initial value is `Float`.
/// - `normalize` - Specifies whether fixed-point data values should
/// be normalized (`true`) or converted directly as fixed-point values (`false`) when they are
/// accessed.
/// - `stride` - Specifies the byte offset between consecutive generic vertex attributes. If
/// stride is 0 the generic vertex attributes are understood to be tightly packed in the array.
/// The initial value is 0.
/// - `offset` - Specifies the offset of the first component of the first generic vertex
/// attribute in the array in the data store of the buffer currently bound to the `ArrayBuffer`
/// target. The initial value is 0.
///
/// # Notes
///
/// - Each generic vertex attribute array is initially disabled and isn't accessed when
/// `draw_arrays`, `multi_draw_arrays`, `draw_elements`, `multi_draw_elements`, or
/// `draw_range_elements` is called.
/// - `GL_UNSIGNED_INT_10F_11F_11F_REV` is accepted for `gl_type` only if the GL version is 4.4 or
/// higher.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if index is greater than or equal to `GL_MAX_VERTEX_ATTRIBS`.
/// - `GL_INVALID_VALUE` is generated if size is not 1, 2, 3, 4, or `GL_BGRA`.
/// - `GL_INVALID_ENUM` is generated if type is not an accepted value.
/// - `GL_INVALID_VALUE` is generated if stride is negative.
/// - `GL_INVALID_OPERATION` is generated if size is `GL_BGRA` and type is not `UByte`,
/// `GL_INT_2_10_10_10_REV`, or `GL_UNSIGNED_INT_2_10_10_10_REV`.
/// - `GL_INVALID_OPERATION` is generated if type is `GL_INT_2_10_10_10_REV` or
/// `GL_UNSIGNED_INT_2_10_10_10_REV` and size is not 4 or `GL_BGRA`.
/// - `GL_INVALID_OPERATION` is generated if type is `GL_UNSIGNED_INT_10F_11F_11F_REV` and size is
/// not 3.
/// - `GL_INVALID_OPERATION` is generated by if size is `GL_BGRA` and noramlized is `false`.
/// - `GL_INVALID_OPERATION` is generated if zero is bound to the `BufferTarget::Array` buffer
/// object binding point and the offset argument is not 0.
/// - `GL_INVALID_OPERATION` is generated if no vertex array object is bound.
fn vertex_attrib_pointer(
attrib: AttributeLocation,
size: i32,
gl_type: GlType,
normalize: Boolean,
stride: i32,
offset: usize));
gl_proc!(glViewport:
/// Sets the viewport.
///
/// [Wiki Page](https://www.opengl.org/wiki/GLAPI/glViewport)
///
/// Core since 1.0
///
/// Specifies the affine transformation of `x` and `y` from normalized device coordinates to
/// window coordinates. Let `(xnd, ynd)` be normalized device coordinates. Then the window
/// coordinates `(xw, yw)` are computed as follows:
///
/// ```
/// xw = (xnd + 1)(width / 2) + x
/// yw = (ynd + 1)(height / 2) + y
/// ```
///
/// Viewport width and height are silently clamped to a range that depends on the
/// implementation. To query this range, call glGet with argument `GL_MAX_VIEWPORT_DIMS`.
///
/// # Errors
///
/// - `GL_INVALID_VALUE` is generated if either width or height is negative.
fn viewport(x: i32, y: i32, width: i32, height: i32));
#[cfg(target_os = "windows")]
pub mod wgl {
pub use platform::{
create_context_attribs,
get_extension_string,
get_swap_interval,
set_swap_interval,
};
}
|
use crate::time_frame::TimeFrame;
#[derive(Clone, Debug)]
pub struct ChallengeData {
pub name: String,
pub time_frame: TimeFrame,
}
|
use std::env;
// test if rustc forced against libunwind instead of libgcc_s
// passes a simple example application
// $ rustc test.rs
// $ ldd test
// should contain libunwind by default
// application should work too without crashing
// rust-bin uses libgcc_s but a symlink to libunwind inside
// /opt/rust-bin-$VERSION/lib/rustlib/x86_64-unknown-linux-gnu/lib
// libgcc_s.so -> /usr/lib64/libunwind.so
// makes rustc link binaries to libunwind.so (verify with ldd)
// and they seem to work
fn test() -> i32
{
println!("test");
return 1;
}
fn main()
{
println!("{}", test());
for argument in env::args()
{
println!("{}", argument);
}
}
|
struct Cardinal;
struct BlueJay;
struct Turpial;
struct Tucan;
struct Turkey;
trait Red {}
trait Blue {}
trait Yellow {}
trait MultiColor {}
impl Red for Cardinal {}
impl Blue for BlueJay {}
impl Yellow for Turpial {}
impl MultiColor for Tucan {}
// These functions are only valid for types which implement these
// traits. The fact that the traits are empty is irrelevant.
fn red<T: Red>(_: &T) -> &'static str { "red" }
fn blue<T: Blue>(_: &T) -> &'static str { "blue" }
fn yellow<T: Yellow>(_: &T) -> &'static str { "yellow" }
fn multicolor<T: MultiColor>(_: &T) -> &'static str { "multicolor" }
fn main() {
let cardinal = Cardinal;
let blue_jay = BlueJay;
let turpial = Turpial;
let tucan = Tucan;
let _turkey = Turkey;
// `red()` won't work on a blue jay nor vice versa
// because of the bounds.
println!("A cardinal is {}", red(&cardinal));
println!("A blue jay is {}", blue(&blue_jay));
println!("A turpial is {}", yellow(&turpial));
println!("A tucan is {}", multicolor(&tucan));
//println!("A turkey is {}", red(&_turkey));
// ^ TODO: Try uncommenting this line.
}
|
const FIXED: i32 = 10;
static GLOBAL : &str = "GLOBAL VAR";
fn is_big(nr :i32) -> bool{
nr > FIXED
}
fn main(){
let nr = 16;
println!("{GLOBAL}");
println!("{} is {}", nr, if is_big(nr) {"big"}else{"small"});
} |
use super::simd::*;
use super::math::*;
use super::collide::*;
use super::world::*;
pub trait Hitable {
fn hit(&self, ray: Ray, t_min: f32, t_max: f32, world: &World, out_hit: &mut HitRecord) -> bool;
}
#[derive(Copy, Clone, Default)]
pub struct PackedIdx {
value: i32
}
/// A QBVHNode has up to four children that it stores the bounds of.
/// This allows fast intersection testing by testing all 4 at once through SIMD.
struct QBVHNode {
bb_min_x: [f32;4],
bb_min_y: [f32;4],
bb_min_z: [f32;4],
bb_max_x: [f32;4],
bb_max_y: [f32;4],
bb_max_z: [f32;4],
children: [PackedIdx; 4],
}
impl PackedIdx {
fn new_joint(idx: u32) -> PackedIdx {
PackedIdx {
value: (idx as i32) & !i32::MIN
}
}
fn joint_get_idx(&self) -> u32 {
debug_assert!(!self.is_leaf());
self.value as u32
}
fn new_empty_leaf() -> PackedIdx {
PackedIdx {
value: i32::MIN
}
}
const MAX_IDX: u32 = 8388607;
const MAX_COUNT: u32 = 255;
/// Encodes bits as: IsChild:[1] Number of primitves:[8] start idx[23]:
fn new_leaf(idx: u32, count: u32) -> PackedIdx {
debug_assert!(idx <= PackedIdx::MAX_IDX, "Val: {}, Max: {}", idx, PackedIdx::MAX_IDX);
debug_assert!(count <= PackedIdx::MAX_COUNT, "Val: {}, Max: {}", count, PackedIdx::MAX_COUNT);
let packed_idx = ((!0 >> 9) & idx) as i32;
let packed_count = (count << 23) as i32;
PackedIdx {
value: i32::MIN | packed_count | packed_idx
}
}
fn is_leaf(&self) -> bool {
(self.value & i32::MIN) == i32::MIN
}
fn is_empty_leaf(&self) -> bool {
self.value == i32::MIN
}
fn leaf_get_idx_count(&self) -> (u32, u32) {
debug_assert!(self.is_leaf());
let idx = self.value as u32 & (!0 >> 9);
let count = (self.value & !i32::MIN) >> 23;
(idx as u32, count as u32)
}
}
#[cfg(test)]
mod packed_idx_tests {
use super::*;
#[test]
fn test_is_leaf()
{
let a = PackedIdx::new_leaf(4023, 15);
assert!(a.is_leaf());
let b = PackedIdx::new_empty_leaf();
assert!(b.is_leaf());
let c = PackedIdx::new_joint(u32::MAX);
assert!(c.is_leaf() == false);
let d = PackedIdx::new_joint(239);
assert!(d.is_leaf() == false);
}
#[test]
fn test_get_leaf_data() {
{
let idx = 4023;
let count = 15;
let x = PackedIdx::new_leaf(idx, count);
let (i, c) = x.leaf_get_idx_count();
assert_eq!(idx, i);
assert_eq!(count, c);
}
{
let x = PackedIdx::new_empty_leaf();
let (i, c) = x.leaf_get_idx_count();
assert_eq!(i, 0);
assert_eq!(c, 0);
}
{
let x = PackedIdx::new_leaf(PackedIdx::MAX_IDX, PackedIdx::MAX_COUNT);
let (i, c) = x.leaf_get_idx_count();
assert_eq!(i, PackedIdx::MAX_IDX);
assert_eq!(c, PackedIdx::MAX_COUNT);
}
}
}
impl QBVHNode {
fn new() -> QBVHNode {
QBVHNode {
bb_min_x: [0.0, 0.0, 0.0, 0.0],
bb_min_y: [0.0, 0.0, 0.0, 0.0],
bb_min_z: [0.0, 0.0, 0.0, 0.0],
bb_max_x: [0.0, 0.0, 0.0, 0.0],
bb_max_y: [0.0, 0.0, 0.0, 0.0],
bb_max_z: [0.0, 0.0, 0.0, 0.0],
children: [PackedIdx::new_empty_leaf(), PackedIdx::new_empty_leaf(), PackedIdx::new_empty_leaf(), PackedIdx::new_empty_leaf()],
}
}
fn set_child_joint_node(&mut self, child: usize, index: usize) {
self.children[child] = PackedIdx::new_joint(index as u32)
}
fn set_child_leaf_node(&mut self, child: usize, size: usize, index: usize) {
if size != 0 {
self.children[child] = PackedIdx::new_leaf(index as u32, size as u32)
}
else {
self.children[child] = PackedIdx::new_empty_leaf()
}
}
fn set_bounds(&mut self, child: usize, bounds: &AABB) {
self.bb_min_x[child] = bounds.min.x;
self.bb_min_y[child] = bounds.min.y;
self.bb_min_z[child] = bounds.min.z;
self.bb_max_x[child] = bounds.max.x;
self.bb_max_y[child] = bounds.max.y;
self.bb_max_z[child] = bounds.max.z;
}
}
pub const SIMD_WIDTH: usize = 4;
#[inline(never)]
fn hit_simd(world: &World, start: usize, len: usize, r: Ray, t_min: f32, t_max: f32, out_hit: &mut HitRecord) -> bool {
let ro_x = f32x4::splat(r.origin.x);
let ro_y = f32x4::splat(r.origin.y);
let ro_z = f32x4::splat(r.origin.z);
let rd_x = f32x4::splat(r.direction.x);
let rd_y = f32x4::splat(r.direction.y);
let rd_z = f32x4::splat(r.direction.z);
let t_min4 = f32x4::splat(t_min);
let zero_4 = f32x4::splat(0.0);
let mut id = i32x4::splat(-1);
let mut closest_t = f32x4::splat(t_max);
let first_idx = start as i32;
let mut cur_id = i32x4::set(first_idx, first_idx + 1, first_idx + 2, first_idx + 3);
// let end = start + len - (len % SIMD_WIDTH);
assert!((len % SIMD_WIDTH) == 0);
let end = start + len;
for i in (start..end).step_by(SIMD_WIDTH) {
let sc_x = f32x4::loadu(&world.sphere_x[i..i+4]);
let sc_y = f32x4::loadu(&world.sphere_y[i..i+4]);
let sc_z = f32x4::loadu(&world.sphere_z[i..i+4]);
let _radius = f32x4::loadu(&world.sphere_r[i..i+4]);
let sq_radius = f32x4::mul(_radius, _radius);
let co_x = f32x4::sub(sc_x, ro_x);
let co_y = f32x4::sub(sc_y, ro_y);
let co_z = f32x4::sub(sc_z, ro_z);
// Note: nb is minus b, avoids having to negate b (and the sign cancels out in c).
let a = f32x4::add(f32x4::add(f32x4::mul(rd_x, rd_x), f32x4::mul(rd_y, rd_y)), f32x4::mul(rd_z, rd_z));
let nb = f32x4::add(f32x4::add(f32x4::mul(co_x, rd_x), f32x4::mul(co_y, rd_y)), f32x4::mul(co_z, rd_z));
let c = f32x4::sub(f32x4::add(f32x4::add(f32x4::mul(co_x, co_x), f32x4::mul(co_y, co_y)), f32x4::mul(co_z, co_z)), sq_radius);
let discr = {
let nb_2 = f32x4::mul(nb, nb);
let a_mul_c = f32x4::mul(a, c);
f32x4::sub(nb_2, a_mul_c)
};
let discr_gt_0 = f32x4::cmp_gt(discr, zero_4);
// See if any of the four spheres have a solution.
if discr_gt_0.any() {
let discr_root = f32x4::sqrt(discr);
let t0 = f32x4::div(f32x4::sub(nb, discr_root), a);
let t1 = f32x4::div(f32x4::add(nb, discr_root), a);
let best_t = f32x4::blendv(t0, t1, f32x4::cmp_gt(t0, t_min4)); // If t0 is above min, take it (since it's the earlier hit), else try t1.
let mask = u32x4::and(u32x4::and(discr_gt_0, f32x4::cmp_gt(best_t, t_min4)), f32x4::cmp_lt(best_t, closest_t));
// if hit, take it
id = i32x4::blendv(id, cur_id, mask);
closest_t = f32x4::blendv(best_t, closest_t, mask);
}
cur_id = i32x4::add(cur_id, i32x4::splat(SIMD_WIDTH as i32));
}
// We found the four best hits, lets see if any are actually close.
let min_t = f32x4::hmin(closest_t);
if min_t < t_max {
let min_t_channel = f32x4::cmp_eq(closest_t, f32x4::splat(min_t));
let min_t_mask = f32x4::movemask(min_t_channel);
if min_t_mask != 0 {
let mut id_scalar : [i32;4] = [0, 0, 0, 0];
let mut closest_t_scalar : [f32;4] = [0.0, 0.0, 0.0, 0.0];
i32x4::storeu(id, &mut id_scalar);
f32x4::storeu(closest_t, &mut closest_t_scalar);
// Map the lowest set bit of the value indexed with.
let mask_to_channel : [i32;16] =
[
0, 0, 1, 0, // 00xx
2, 0, 1, 0, // 01xx
3, 0, 1, 0, // 10xx
2, 0, 1, 0, // 11xx
];
let lane = mask_to_channel[min_t_mask as usize];
let hit_id = id_scalar[lane as usize] as usize;
let final_t = closest_t_scalar[lane as usize];
out_hit.point = r.at(final_t);
out_hit.normal = (out_hit.point - world.sphere_c[hit_id]) / world.sphere_r[hit_id];
out_hit.set_face_and_normal(r, out_hit.normal);
out_hit.t = final_t;
out_hit.obj_id = hit_id as usize;
return true;
}
}
false
}
fn hit(world: &World, start: usize, len: usize, ray: Ray, t_min: f32, t_max: f32, out_hit: &mut HitRecord) -> bool {
let mut closest_t = t_max;
let mut hit_id = -1;
let end = start + len;
for i in start..end {
let center = world.sphere_c[i];
let radius = world.sphere_r[i];
let oc = ray.origin - center;
let a = dot(ray.direction, ray.direction);
let b = dot(oc, ray.direction);
let c = dot(oc, oc) - radius * radius;
let discriminant = b*b - a*c;
if discriminant > 0.0 {
let d_root = discriminant.sqrt();
let t1 = (-b - d_root) / a;
let t2 = (-b + d_root) / a;
if t1 < closest_t && t1 > t_min {
closest_t = t1;
hit_id = i as i32;
}
else if t2 < closest_t && t2 > t_min {
closest_t = t2;
hit_id = i as i32;
}
}
}
if hit_id != -1 {
let center = world.sphere_c[hit_id as usize];
let radius = world.sphere_r[hit_id as usize];
out_hit.t = closest_t;
out_hit.obj_id = hit_id as usize;
out_hit.point = ray.at(closest_t);
let outward_normal = (out_hit.point - center) / radius;
out_hit.set_face_and_normal(ray, outward_normal);
true
}
else {
false
}
}
pub struct QBVH {
tree: Vec<QBVHNode>
}
impl QBVH {
pub fn new() -> QBVH {
QBVH { tree: Vec::new() }
}
fn hit_node_children(node: &QBVHNode, r: Ray, t_min: f32, t_max: f32) -> ([bool;4], bool) {
let min_x = f32x4::loadu(&node.bb_min_x);
let min_y = f32x4::loadu(&node.bb_min_y);
let min_z = f32x4::loadu(&node.bb_min_z);
let max_x = f32x4::loadu(&node.bb_max_x);
let max_y = f32x4::loadu(&node.bb_max_y);
let max_z = f32x4::loadu(&node.bb_max_z);
let ro_x = f32x4::splat(r.origin.x);
let ro_y = f32x4::splat(r.origin.y);
let ro_z = f32x4::splat(r.origin.z);
let inv_rd_x = f32x4::splat(1.0 / r.direction.x);
let inv_rd_y = f32x4::splat(1.0 / r.direction.y);
let inv_rd_z = f32x4::splat(1.0 / r.direction.z);
let zero_4 = f32x4::splat(0.0);
let mut t_min_4 = f32x4::splat(t_min);
let mut t_max_4 = f32x4::splat(t_max);
let any_x_miss;
{
let t0_x = f32x4::mul(f32x4::sub(min_x, ro_x), inv_rd_x);
let t1_x = f32x4::mul(f32x4::sub(max_x, ro_x), inv_rd_x);
let inv_rd_x_lt0 = f32x4::cmp_lt(inv_rd_x, zero_4);
let swap_t0_x = f32x4::blendv(t1_x, t0_x, inv_rd_x_lt0);
let swap_t1_x = f32x4::blendv(t0_x, t1_x, inv_rd_x_lt0);
t_min_4 = f32x4::max(t_min_4, swap_t0_x);
t_max_4 = f32x4::min(t_max_4, swap_t1_x);
any_x_miss = f32x4::cmp_le(t_max_4, t_min_4);
}
let any_y_miss;
{
let t0_y = f32x4::mul(f32x4::sub(min_y, ro_y), inv_rd_y);
let t1_y = f32x4::mul(f32x4::sub(max_y, ro_y), inv_rd_y);
let inv_rd_y_lt0 = f32x4::cmp_lt(inv_rd_y, zero_4);
let swap_t0_y = f32x4::blendv(t1_y, t0_y, inv_rd_y_lt0);
let swap_t1_y = f32x4::blendv(t0_y, t1_y, inv_rd_y_lt0);
t_min_4 = f32x4::max(t_min_4, swap_t0_y);
t_max_4 = f32x4::min(t_max_4, swap_t1_y);
any_y_miss = f32x4::cmp_le(t_max_4, t_min_4);
}
let any_z_miss;
{
let t0_z = f32x4::mul(f32x4::sub(min_z, ro_z), inv_rd_z);
let t1_z = f32x4::mul(f32x4::sub(max_z, ro_z), inv_rd_z);
let inv_rd_z_lt0 = f32x4::cmp_lt(inv_rd_z, zero_4);
let swap_t0_z = f32x4::blendv(t1_z, t0_z, inv_rd_z_lt0);
let swap_t1_z = f32x4::blendv(t0_z, t1_z, inv_rd_z_lt0);
t_min_4 = f32x4::max(t_min_4, swap_t0_z);
t_max_4 = f32x4::min(t_max_4, swap_t1_z);
any_z_miss = f32x4::cmp_le(t_max_4, t_min_4);
}
let any_miss = u32x4::not(u32x4::or(u32x4::or(any_x_miss, any_y_miss), any_z_miss));
(u32x4::get_flags(any_miss), any_miss.any())
}
pub fn hit_qbvh(bvh: &QBVH, r: Ray, t_min: f32, t_max: f32, world: &World, nodes_to_check: &mut Vec<PackedIdx>, out_hit: &mut HitRecord) -> bool {
nodes_to_check.clear();
nodes_to_check.push(PackedIdx::new_joint(0));
let mut hit_any_node = false;
let mut closest_t = t_max;
while nodes_to_check.len() > 0 {
let next_node = nodes_to_check.pop().unwrap();
if next_node.is_leaf() {
let (c_idx, c_count) = next_node.leaf_get_idx_count();
if hit_simd(world, c_idx as usize, c_count as usize, r, t_min, closest_t, out_hit) {
// if hit(world, c_idx as usize, c_count as usize, r, t_min, closest_t, out_hit) {
hit_any_node = true;
closest_t = out_hit.t;
}
} else {
let bvh_node = &bvh.tree[next_node.joint_get_idx() as usize];
let (hit_mask, any_hit) = QBVH::hit_node_children(bvh_node, r, t_min, t_max);
if any_hit {
if hit_mask[0] { nodes_to_check.push(bvh_node.children[0]) };
if hit_mask[1] { nodes_to_check.push(bvh_node.children[1]) };
if hit_mask[2] { nodes_to_check.push(bvh_node.children[2]) };
if hit_mask[3] { nodes_to_check.push(bvh_node.children[3]) };
}
}
}
hit_any_node
}
}
fn pick_split_axis(objects: &mut [Sphere], start: usize, end: usize) -> (Axis, f32) {
let mut bounds = objects[start].calc_aabb();
for i in start+1..end {
bounds = AABB::merge(&bounds, &objects[i].calc_aabb())
}
let split_axis = bounds.longest_axis();
let split_point = (bounds.max_at_axis(split_axis) + bounds.min_at_axis(split_axis)) * 0.5;
(split_axis, split_point)
}
fn partition(objects: &mut [Sphere], axis: Axis, position: f32, start: usize, end: usize) -> usize {
let mut split_idx = start;
for i in start..end {
let bounds = objects[i].calc_aabb();
let center = bounds.get_center();
if center.at(axis as usize) <= position {
objects.swap(i, split_idx);
split_idx += 1;
}
}
split_idx
}
impl QBVH {
fn create_leaf_node(&mut self, start: usize, end: usize, mut parent: i32, child: i32, bounds: &AABB) {
if parent < 0 { // root is a leaf node
self.tree.push(QBVHNode::new());
parent = 0;
}
self.tree[parent as usize].set_bounds(child as usize, bounds);
self.tree[parent as usize].set_child_leaf_node(child as usize, end - start, start);
}
fn create_joint_node(&mut self, parent: i32, child: i32, bounds: &AABB) -> i32 {
let new_node_idx = self.tree.len();
self.tree.push(QBVHNode::new());
if parent >= 0 {
self.tree[parent as usize].set_child_joint_node(child as usize, new_node_idx);
self.tree[parent as usize].set_bounds(child as usize, bounds);
}
new_node_idx as i32
}
pub fn build(&mut self, objects: &mut[Sphere], start: usize, end: usize, parent: i32, child: i32, depth: u32) {
let max_elem_in_leaf = 16;
let mut bounds = objects[start].calc_aabb();
for i in start+1..end {
bounds = AABB::merge(&bounds, &objects[i].calc_aabb());
}
if (end - start) <= max_elem_in_leaf {
let group_width = end - start;
let aligned_width = ((group_width + (SIMD_WIDTH - 1)) / SIMD_WIDTH) * SIMD_WIDTH;
let (aligned_start, aligned_end) = {
let misalignment = aligned_width - group_width;
if misalignment > 0 {
if (end + misalignment) < objects.len() {
(start, end + misalignment)
} else {
(start - misalignment, end)
}
} else {
(start, end)
}
};
self.create_leaf_node(aligned_start, aligned_end, parent, child, &bounds);
return;
}
let (split_axis, split_point) = pick_split_axis(objects, start, end);
let split_idx = partition(objects, split_axis, split_point, start, end);
let current; let left; let right;
if depth % 2 == 1 {
current = parent;
left = child;
right = child + 1;
}
else {
current = self.create_joint_node(parent, child, &bounds);
left = 0;
right = 2;
}
self.build(objects, start, split_idx, current as i32, left, depth + 1);
self.build(objects, split_idx, end, current as i32, right, depth + 1);
}
}
|
pub struct Solution;
#[derive(Debug, PartialEq, Eq)]
pub enum NestedInteger {
Int(i32),
List(Vec<NestedInteger>),
}
impl Solution {
pub fn deserialize(s: String) -> NestedInteger {
let mut stack = vec![Vec::new()];
let mut chars = s.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'0'..='9' => {
let mut num = ch.to_digit(10).unwrap() as i32;
while chars.peek().map_or(false, |ch| ch.is_digit(10)) {
num = num * 10 + chars.next().unwrap().to_digit(10).unwrap() as i32;
}
stack.last_mut().unwrap().push(NestedInteger::Int(num));
}
'-' => {
let mut num = 0;
while chars.peek().map_or(false, |ch| ch.is_digit(10)) {
num = num * 10 + chars.next().unwrap().to_digit(10).unwrap() as i32;
}
stack.last_mut().unwrap().push(NestedInteger::Int(-num));
}
',' => {
// do nothing
}
'[' => {
stack.push(Vec::new());
}
']' => {
let list = stack.pop().unwrap();
stack.last_mut().unwrap().push(NestedInteger::List(list));
}
_ => unreachable!(),
}
}
stack.pop().unwrap().pop().unwrap()
}
}
#[test]
fn test0385() {
fn case(s: &str, want: NestedInteger) {
let got = Solution::deserialize(s.to_string());
assert_eq!(got, want);
}
case("324", NestedInteger::Int(324));
case(
"[123,[456,[789]]]",
NestedInteger::List(vec![
NestedInteger::Int(123),
NestedInteger::List(vec![
NestedInteger::Int(456),
NestedInteger::List(vec![NestedInteger::Int(789)]),
]),
]),
);
}
|
use std::io;
use std::io::prelude::*;
use std::collections::HashMap;
type int = i64;
#[derive(Debug)]
enum Instruction {
Add(int, int, usize),
Eq(int, int, usize),
Hlt,
Inp(usize),
Jnz(int, usize),
Jz(int, usize),
Lt(int, int, usize),
Mul(int, int, usize),
Out(int),
Rbo(int),
}
#[derive(Clone)]
struct IntCodeVM {
pc: usize,
mem: Vec<int>,
input: int,
relative_base: int
}
impl IntCodeVM {
fn new(starting_memory: &[int], input: int) -> IntCodeVM {
let mut mem = starting_memory.to_vec();
mem.resize(mem.len() + 4096, 0); // YOLO
IntCodeVM {
pc: 0,
mem,
input,
relative_base: 0
}
}
fn next_output(&mut self) -> Option<int> {
use Instruction::*;
loop {
match self.current_opcode_decode() {
Add(a, b, out) => { self.mem[out] = a + b; self.pc += 4; }
Mul(a, b, out) => { self.mem[out] = a * b; self.pc += 4; }
Inp(out) => { self.mem[out] = self.input; self.pc += 2; }
Out(a) => { self.pc += 2; return Some(a) }
Jnz(a, b) => self.pc = if a != 0 { b } else { self.pc + 3 },
Jz(a, b) => self.pc = if a == 0 { b } else { self.pc + 3 },
Lt(a, b, out) => { self.mem[out] = if a < b { 1 } else { 0 }; self.pc += 4 }
Eq(a, b, out) => { self.mem[out] = if a == b { 1 } else { 0 }; self.pc += 4; }
Rbo(a) => { self.relative_base += a; self.pc += 2 }
Hlt => return None
}
}
}
fn collect_output(&mut self) -> Vec<int> {
let mut out = Vec::new();
while let Some(n) = self.next_output() {
out.push(n)
}
out
}
fn set_input(&mut self, i: int) {
self.input = i;
}
#[inline(always)]
fn current_opcode_decode(&self) -> Instruction {
let param = |n: usize| {
let p = self.mem[self.pc + n];
match self.mem[self.pc] / (10 * 10_u32.pow(n as u32) as int) % 10 {
1 => p,
2 => self.mem[(self.relative_base + p) as usize],
_ => self.mem[p as usize]
}
};
let dest = |n: usize| {
let p = self.mem[self.pc + n];
match self.mem[self.pc] / (10 * 10_u32.pow(n as u32) as int) % 10 {
1 => panic!("immidiate output paramter"),
2 => (self.relative_base + p) as usize,
_ => p as usize
}
};
use Instruction::*;
match self.mem[self.pc] % 100 {
1 => Add(param(1), param(2), dest(3)),
2 => Mul(param(1), param(2), dest(3)),
3 => Inp(dest(1)),
4 => Out(param(1)),
5 => Jnz(param(1), param(2) as usize),
6 => Jz(param(1), param(2) as usize),
7 => Lt(param(1), param(2), dest(3)),
8 => Eq(param(1), param(2), dest(3)),
9 => Rbo(param(1)),
99 => Hlt,
code => panic!("unknown opcode {}", code)
}
}
}
#[derive(Debug)]
struct Robot {
d: i8,
x: i64,
y: i64,
}
const UP: i8 = 0;
const RIGHT: i8 = 1;
const DOWN: i8 = 2;
const LEFT: i8 = 3;
fn modulo(a: i8, b: i8) -> i8 {
((a % b) + b) % b
}
impl Robot {
fn new() -> Robot {
Robot { d: UP, x: 0, y: 0, }
}
fn turn_and_move(&mut self, n: u8) {
match n {
0 => self.d = modulo(self.d - 1, 4),
1 => self.d = modulo(self.d + 1, 4),
e => panic!("wrong turn: {}", e)
}
match self.d {
UP => self.y -= 1,
RIGHT => self.x += 1,
DOWN => self.y += 1,
LEFT => self.x -= 1,
e => panic!("wrong direction: {}", e)
}
}
}
fn paint(starting_memory: &[int], inp: int) -> HashMap<(i64, i64), u8> {
let mut robot = Robot::new();
let mut vm = IntCodeVM::new(&starting_memory, inp);
let mut map: HashMap<(i64, i64), u8> = HashMap::new();
map.insert((0,0), inp as u8);
loop {
if let Some(color) = vm.next_output() {
assert!(color < 2);
map.insert((robot.x, robot.y), color as u8);
} else {
break;
}
if let Some(turn) = vm.next_output() {
robot.turn_and_move(turn as u8);
vm.set_input(*map.get(&(robot.x, robot.y)).unwrap_or(&0) as int);
} else {
break;
}
}
map
}
fn pretty_print(map: &HashMap<(i64, i64), u8>) {
for y in -5..10 {
for x in -10..80 {
let c = match map.get(&(x, y)) {
Some(1) => '█',
_ => ' ',
};
print!("{}", c);
}
println!();
}
}
fn main() {
let stdin = io::stdin();
let input = stdin.lock().lines().next().unwrap().unwrap().split(',').map(|n| n.parse().unwrap()).collect::<Vec<int>>();
let part1 = paint(&input, 0).len();
println!("Part 1: {}", part1);
pretty_print(&paint(&input, 1));
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::Error,
fidl_fuchsia_bluetooth::{self, Int8},
fidl_fuchsia_bluetooth_control::{AdapterInfo, AdapterState, RemoteDevice},
std::{
fs::{File, OpenOptions},
path::Path,
},
};
/// Macro to help build bluetooth fidl statuses.
/// No Args is a success
/// One Arg is the error type
/// Two Args is the error type & a description
#[macro_export]
macro_rules! bt_fidl_status {
() => {
fidl_fuchsia_bluetooth::Status { error: None }
};
($error_code:ident) => {
fidl_fuchsia_bluetooth::Status {
error: Some(Box::new(fidl_fuchsia_bluetooth::Error {
description: None,
protocol_error_code: 0,
error_code: fidl_fuchsia_bluetooth::ErrorCode::$error_code,
})),
}
};
($error_code:ident, $description:expr) => {
fidl_fuchsia_bluetooth::Status {
error: Some(Box::new(fidl_fuchsia_bluetooth::Error {
description: Some($description.to_string()),
protocol_error_code: 0,
error_code: fidl_fuchsia_bluetooth::ErrorCode::$error_code,
})),
}
};
}
/// Open a file with read and write permissions.
pub fn open_rdwr<P: AsRef<Path>>(path: P) -> Result<File, Error> {
OpenOptions::new().read(true).write(true).open(path).map_err(|e| e.into())
}
/// The following functions allow FIDL types to be cloned. These are currently necessary as the
/// auto-generated binding types do not derive `Clone`.
/// Clone Adapter Info
pub fn clone_host_info(a: &AdapterInfo) -> AdapterInfo {
let state = match a.state {
Some(ref s) => Some(Box::new(clone_host_state(&**s))),
None => None,
};
AdapterInfo {
identifier: a.identifier.clone(),
technology: a.technology.clone(),
address: a.address.clone(),
state: state,
}
}
/// Clone Bluetooth Fidl bool type
pub fn clone_bt_fidl_bool(a: &fidl_fuchsia_bluetooth::Bool) -> fidl_fuchsia_bluetooth::Bool {
fidl_fuchsia_bluetooth::Bool { value: a.value }
}
/// Clone Adapter State
pub fn clone_host_state(a: &AdapterState) -> AdapterState {
let discoverable = match a.discoverable {
Some(ref disc) => Some(Box::new(clone_bt_fidl_bool(disc))),
None => None,
};
let discovering = match a.discovering {
Some(ref disc) => Some(Box::new(clone_bt_fidl_bool(disc))),
None => None,
};
AdapterState {
local_name: a.local_name.clone(),
discovering: discovering,
discoverable: discoverable,
local_service_uuids: a.local_service_uuids.clone(),
}
}
/// Clone RemoteDevice data, as clone is not implemented for FIDL types
pub fn clone_remote_device(d: &RemoteDevice) -> RemoteDevice {
fn copy_option_int8(opt: &Option<Box<Int8>>) -> Option<Box<Int8>> {
match opt {
Some(i) => Some(Box::new(Int8 { value: i.value })),
None => None,
}
}
RemoteDevice {
identifier: d.identifier.clone(),
address: d.address.clone(),
technology: d.technology.clone(),
name: d.name.clone(),
appearance: d.appearance.clone(),
rssi: copy_option_int8(&d.rssi),
tx_power: copy_option_int8(&d.tx_power),
connected: d.connected,
bonded: d.bonded,
service_uuids: d.service_uuids.iter().cloned().collect(),
}
}
|
use std::env;
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use std::collections::HashSet;
fn accumulated_frequency(start_freq: i32, adjustments: &[i32]) -> i32 {
let mut sum = start_freq;
for adj in adjustments {
sum += adj;
}
sum
}
fn first_repeated_cumulative_freq(start_freq: i32, adjustments: &[i32]) -> i32 {
let mut observations = HashSet::new();
let mut current_freq = start_freq;
loop {
for adj in adjustments {
if observations.contains(¤t_freq) {
return current_freq;
} else {
observations.insert(current_freq);
current_freq += adj;
}
}
}
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 3 { panic!("Too few arguments!") }
let f = File::open(&args[1]).expect("File not found!");
let reader = BufReader::new(&f);
let part: u32 = args[2].parse().expect("Invalid part!");
let adjustments: Vec<i32> = reader.
lines().
map(|l| l.unwrap().trim().parse::<i32>().unwrap()).
collect();
let start_freq = 0;
if part == 1 {
let freq = accumulated_frequency(start_freq, &adjustments);
println!("Final frequency is: {}", freq);
} else {
let freq = first_repeated_cumulative_freq(start_freq, &adjustments);
println!("First duplicate frequency is: {}", freq);
}
}
|
//! A simple `!Unpin` I/O backend for async-std, designed for use in tests.
//!
//! This crate provides the `PinCursor` struct which wraps around `async_std::io::Cursor`
//! but is explicitly **not** `Unpin`. It is a little building block to help write tests
//! where you want to ensure that your own asynchronous IO code behaves correctly when reading from
//! or writing to something that is *definitely* `!Unpin`.
//!
//! - It can be backed by any `Unpin` data buffer that can be slotted into `async_std::io::Cursor`.
//! Usually `Vec<u8>` or `&mut [u8]` (e. g. from an array) are used.
//! - It implements `async_std::io::{Read, Write, Seek}`, so you can poll these traits' methods
//! in your own futures.
//! - At the same time, it provides several high-level methods through which you can manipulate
//! the PinCursor in a simple `async {}` block.
//!
//! # Examples
//!
//! ```
//! # use async_std::task::block_on;
//! use pin_cursor::PinCursor;
//! use async_std::io::{prelude::*, Cursor};
//! use std::io::SeekFrom;
//! use std::pin::Pin;
//!
//! // Construct a async_std::io::Cursor however you like...
//! let mut data: Vec<u8> = Vec::new();
//! let cursor = Cursor::new(&mut data);
//! // ... then wrap it in PinCursor and a pinned pointer, thus losing the Unpin privileges.
//! let mut cursor: Pin<Box<PinCursor<_>>> = Box::pin(PinCursor::wrap(cursor));
//! // Note that we have to make an owning pointer first -
//! // making a Pin<&mut PinCursor<_>> directly is impossible!
//! // (There is a more complex way to allocate on stack - see the features section.)
//!
//! // Methods of PinCursor mostly return futures and are designed for use in async contexts.
//! # block_on(
//! async {
//! // You can write!
//! assert_eq!(cursor.as_mut().write(&[1u8, 2u8, 3u8]).await.unwrap(), 3);
//!
//! // You can seek!
//! assert_eq!(cursor.position(), 3);
//! assert_eq!(cursor.as_mut().seek(SeekFrom::Start(1)).await.unwrap(), 1);
//! assert_eq!(cursor.position(), 1);
//!
//! // You can read!
//! let mut buf = [0u8; 1];
//! assert_eq!(cursor.as_mut().read(buf.as_mut()).await.unwrap(), 1);
//! assert_eq!(buf[0], 2);
//!
//! // There's also this way of seeking that doesn't involve futures.
//! cursor.as_mut().set_position(0);
//! assert_eq!(cursor.as_mut().read(buf.as_mut()).await.unwrap(), 1);
//! assert_eq!(buf[0], 1);
//! }
//! # );
//! ```
//!
//! # Features
//!
//! The optional feature `stackpin` enables integration with [stackpin], a crate that provides
//! a way to allocate `!Unpin` structures on stack.
//!
//! ```ignore
//! # use pin_cursor::PinCursor;
//! # use async_std::io::Cursor;
//! # use std::pin::Pin;
//! use stackpin::stack_let;
//!
//! let mut data: Vec<u8> = vec![1, 2];
//! stack_let!(mut cursor : PinCursor<_> = Cursor::new(&mut data));
//! let cursor_ptr: Pin<&mut PinCursor<_>> = Pin::as_mut(&mut cursor);
//! ```
//!
//! Now you have a correctly pinned `PinCursor` that's allocated on stack instead of in a box.
//!
//! [stackpin]: https://docs.rs/stackpin/0.0.2
use std::future::Future;
use std::io::{IoSlice, IoSliceMut, Result, SeekFrom};
use std::marker::PhantomPinned;
use std::pin::Pin;
use std::task::{Context, Poll};
use async_std::io::Cursor;
use async_std::io::prelude::*;
use pin_project_lite::pin_project;
#[cfg(feature = "stackpin")]
mod impl_stackpin;
pin_project! {
pub struct PinCursor<T> {
c: Cursor<T>,
#[pin]
_p: PhantomPinned
}
}
impl<T> PinCursor<T>
where T: Unpin,
Cursor<T>: Write + Read + Seek
{
pub fn wrap(c: Cursor<T>) -> Self {
Self { c, _p: PhantomPinned }
}
pub fn unwrap(self) -> Cursor<T> {
self.c
}
pub fn position(&self) -> u64 {
self.c.position()
}
pub fn set_position(self: Pin<&mut Self>, pos: u64) {
self.project().c.set_position(pos)
}
pub fn write<'a>(self: Pin<&'a mut Self>, buf: &'a [u8]) -> impl Future<Output=Result<usize>> + 'a {
self.project().c.write(buf)
}
pub fn read<'a>(self: Pin<&'a mut Self>, buf: &'a mut [u8]) -> impl Future<Output=Result<usize>> + 'a {
self.project().c.read(buf)
}
pub fn seek(self: Pin<&mut Self>, pos: SeekFrom) -> impl Future<Output=Result<u64>> + '_ {
self.project().c.seek(pos)
}
}
impl<T> Read for PinCursor<T>
where T: Unpin,
Cursor<T>: Read
{
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize>> {
Pin::new(self.project().c).poll_read(cx, buf)
}
fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>]) -> Poll<Result<usize>> {
Pin::new(self.project().c).poll_read_vectored(cx, bufs)
}
}
impl<T> Write for PinCursor<T>
where T: Unpin,
Cursor<T>: Write
{
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> {
Pin::new(self.project().c).poll_write(cx, buf)
}
fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) -> Poll<Result<usize>> {
Pin::new(self.project().c).poll_write_vectored(cx, bufs)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
Pin::new(self.project().c).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
Pin::new(self.project().c).poll_close(cx)
}
}
impl<T> Seek for PinCursor<T>
where T: Unpin,
Cursor<T>: Seek
{
fn poll_seek(self: Pin<&mut Self>, cx: &mut Context<'_>, pos: SeekFrom) -> Poll<Result<u64>> {
Pin::new(self.project().c).poll_seek(cx, pos)
}
}
#[cfg(test)]
mod tests {
use static_assertions::{assert_impl_all, assert_not_impl_all};
use super::*;
#[test]
fn impls() {
assert_not_impl_all!(PinCursor<Vec<u8>>: Unpin);
assert_impl_all!(PinCursor<Vec<u8>>: Read, Write, Seek);
}
}
|
use std::fs;
use std::str;
#[test]
fn validate_9_1() {
assert_eq!(algorithm("src/day_9/input_test.txt", 5), 127);
}
fn algorithm(file_location: &str, preamble: usize) -> i64 {
let content = fs::read_to_string(file_location).unwrap();
let mut xmas_codes: Vec<i64> = vec![];
let mut preamble_codes: Vec<i64> = vec![];
let mut curr_code: i64 = -1;
for (index, line) in content.lines().enumerate() {
let xmas_code = line.parse().unwrap();
if index < preamble {
preamble_codes.push(xmas_code);
} else {
xmas_codes.push(xmas_code);
}
}
for xmas_code in xmas_codes {
let mut valid = false;
curr_code = xmas_code;
for preamble_code in preamble_codes.clone() {
let remainder = xmas_code - preamble_code;
if preamble_codes.contains(&remainder) {
valid = true;
break;
}
}
if !valid {
break;
}
preamble_codes.remove(0);
preamble_codes.push(xmas_code);
}
curr_code
}
pub fn run() {
println!(
"The first number that does not have the property is {}.",
algorithm("src/day_9/input.txt", 25)
);
}
|
use std::collections::HashMap;
use std::fmt;
use std::fs::File;
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::error::Error;
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Stroke(String);
#[derive(Debug, Deserialize, PartialEq, Eq, Hash)]
pub struct Translation(String);
#[derive(Debug, Deserialize)]
pub struct Dictionary(HashMap<Stroke, Translation>);
#[derive(Debug, PartialEq, Eq)]
pub struct InvertedDictionary(HashMap<Translation, Vec<Stroke>>);
impl fmt::Display for Stroke {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl Dictionary {
pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
let file = File::open(path)?;
serde_json::from_reader(file).map_err(Error::from)
}
pub fn invert(self) -> InvertedDictionary {
let dict = self.0;
let inverse = dict.into_iter().fold(
HashMap::new(),
|mut inverse: HashMap<_, Vec<_>>, (stroke, translation)| {
inverse.entry(translation).or_default().push(stroke);
inverse
},
);
InvertedDictionary(inverse)
}
}
impl InvertedDictionary {
pub fn get(&self, translation: String) -> Option<&Vec<Stroke>> {
self.0.get(&Translation(translation))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_invert() {
let dict = Dictionary(
vec![
(Stroke("TEFT".to_string()), Translation("test".to_string())),
(Stroke("TEF".to_string()), Translation("test".to_string())),
]
.into_iter()
.collect(),
);
let expected = InvertedDictionary(
vec![(
Translation("test".to_string()),
vec![Stroke("TEF".to_string()), Stroke("TEFT".to_string())],
)]
.into_iter()
.collect(),
);
// Ensure order of items is predictable for comparison in assert_eq
let mut inverted = dict.invert();
inverted
.0
.iter_mut()
.for_each(|(_, strokes)| strokes.sort());
assert_eq!(expected, inverted);
}
}
|
use std::error::Error;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::{TcpListener, TcpStream};
use tokio_rustls::rustls::ServerConfig;
use tokio_rustls::server::TlsStream;
use tokio_rustls::TlsAcceptor;
use crate::session::{create_session, Session};
type Upstream = TcpStream;
type Downstream = TlsStream<TcpStream>;
type ServerSession = Session<Upstream, Downstream>;
pub struct Server {
upstream: SocketAddr,
tcp_listener: TcpListener,
tls_acceptor: TlsAcceptor,
}
impl Server {
pub async fn start(
bind_to: SocketAddr,
upstream: SocketAddr,
server_config: ServerConfig,
) -> Result<Self, Box<dyn Error>> {
Ok(Self {
upstream,
tcp_listener: TcpListener::bind(bind_to).await?,
tls_acceptor: TlsAcceptor::from(Arc::new(server_config)),
})
}
pub async fn wait_for_session(&mut self) -> Result<ServerSession, Box<dyn Error>> {
let (downstream, peer_addr) = self.tcp_listener.accept().await?;
let downstream = self.tls_acceptor.clone().accept(downstream).await?;
let upstream = TcpStream::connect(self.upstream).await?;
Ok(create_session(peer_addr, upstream, downstream))
}
}
|
use criterion::{
criterion_group, criterion_main, measurement::WallTime, BatchSize, BenchmarkGroup, BenchmarkId,
Criterion, Throughput,
};
use rustpython_compiler::Mode;
use rustpython_vm::{AsObject, Interpreter, PyResult, Settings};
use std::{
ffi, fs, io,
path::{Path, PathBuf},
};
// List of microbenchmarks to skip.
//
// These result in excessive memory usage, some more so than others. For example, while
// exception_context.py consumes a lot of memory, it still finishes. On the other hand,
// call_kwargs.py seems like it performs an excessive amount of allocations and results in
// a system freeze.
// In addition, the fact that we don't yet have a GC means that benchmarks which might consume
// a bearable amount of memory accumulate. As such, best to skip them for now.
const SKIP_MICROBENCHMARKS: [&str; 8] = [
"call_simple.py",
"call_kwargs.py",
"construct_object.py",
"define_function.py",
"define_class.py",
"exception_nested.py",
"exception_simple.py",
"exception_context.py",
];
pub struct MicroBenchmark {
name: String,
setup: String,
code: String,
iterate: bool,
}
fn bench_cpython_code(group: &mut BenchmarkGroup<WallTime>, bench: &MicroBenchmark) {
let gil = cpython::Python::acquire_gil();
let py = gil.python();
let setup_code = ffi::CString::new(&*bench.setup).unwrap();
let setup_name = ffi::CString::new(format!("{}_setup", bench.name)).unwrap();
let setup_code = cpy_compile_code(py, &setup_code, &setup_name).unwrap();
let code = ffi::CString::new(&*bench.code).unwrap();
let name = ffi::CString::new(&*bench.name).unwrap();
let code = cpy_compile_code(py, &code, &name).unwrap();
let bench_func = |(globals, locals): &mut (cpython::PyDict, cpython::PyDict)| {
let res = cpy_run_code(py, &code, globals, locals);
if let Err(e) = res {
e.print(py);
panic!("Error running microbenchmark")
}
};
let bench_setup = |iterations| {
let globals = cpython::PyDict::new(py);
// setup the __builtins__ attribute - no other way to do this (other than manually) as far
// as I can tell
let _ = py.run("", Some(&globals), None);
let locals = cpython::PyDict::new(py);
if let Some(idx) = iterations {
globals.set_item(py, "ITERATIONS", idx).unwrap();
}
let res = cpy_run_code(py, &setup_code, &globals, &locals);
if let Err(e) = res {
e.print(py);
panic!("Error running microbenchmark setup code")
}
(globals, locals)
};
if bench.iterate {
for idx in (100..=1_000).step_by(200) {
group.throughput(Throughput::Elements(idx as u64));
group.bench_with_input(BenchmarkId::new("cpython", &bench.name), &idx, |b, idx| {
b.iter_batched_ref(
|| bench_setup(Some(*idx)),
bench_func,
BatchSize::LargeInput,
);
});
}
} else {
group.bench_function(BenchmarkId::new("cpython", &bench.name), move |b| {
b.iter_batched_ref(|| bench_setup(None), bench_func, BatchSize::LargeInput);
});
}
}
unsafe fn cpy_res(
py: cpython::Python<'_>,
x: *mut python3_sys::PyObject,
) -> cpython::PyResult<cpython::PyObject> {
cpython::PyObject::from_owned_ptr_opt(py, x).ok_or_else(|| cpython::PyErr::fetch(py))
}
fn cpy_compile_code(
py: cpython::Python<'_>,
s: &ffi::CStr,
fname: &ffi::CStr,
) -> cpython::PyResult<cpython::PyObject> {
unsafe {
let res =
python3_sys::Py_CompileString(s.as_ptr(), fname.as_ptr(), python3_sys::Py_file_input);
cpy_res(py, res)
}
}
fn cpy_run_code(
py: cpython::Python<'_>,
code: &cpython::PyObject,
locals: &cpython::PyDict,
globals: &cpython::PyDict,
) -> cpython::PyResult<cpython::PyObject> {
use cpython::PythonObject;
unsafe {
let res = python3_sys::PyEval_EvalCode(
code.as_ptr(),
locals.as_object().as_ptr(),
globals.as_object().as_ptr(),
);
cpy_res(py, res)
}
}
fn bench_rustpy_code(group: &mut BenchmarkGroup<WallTime>, bench: &MicroBenchmark) {
let mut settings = Settings::default();
settings.path_list.push("Lib/".to_string());
settings.dont_write_bytecode = true;
settings.no_user_site = true;
Interpreter::with_init(settings, |vm| {
for (name, init) in rustpython_stdlib::get_module_inits() {
vm.add_native_module(name, init);
}
})
.enter(|vm| {
let setup_code = vm
.compile(&bench.setup, Mode::Exec, bench.name.to_owned())
.expect("Error compiling setup code");
let bench_code = vm
.compile(&bench.code, Mode::Exec, bench.name.to_owned())
.expect("Error compiling bench code");
let bench_func = |scope| {
let res: PyResult = vm.run_code_obj(bench_code.clone(), scope);
vm.unwrap_pyresult(res);
};
let bench_setup = |iterations| {
let scope = vm.new_scope_with_builtins();
if let Some(idx) = iterations {
scope
.locals
.as_object()
.set_item("ITERATIONS", vm.new_pyobj(idx), vm)
.expect("Error adding ITERATIONS local variable");
}
let setup_result = vm.run_code_obj(setup_code.clone(), scope.clone());
vm.unwrap_pyresult(setup_result);
scope
};
if bench.iterate {
for idx in (100..=1_000).step_by(200) {
group.throughput(Throughput::Elements(idx as u64));
group.bench_with_input(
BenchmarkId::new("rustpython", &bench.name),
&idx,
|b, idx| {
b.iter_batched(
|| bench_setup(Some(*idx)),
bench_func,
BatchSize::LargeInput,
);
},
);
}
} else {
group.bench_function(BenchmarkId::new("rustpython", &bench.name), move |b| {
b.iter_batched(|| bench_setup(None), bench_func, BatchSize::LargeInput);
});
}
})
}
pub fn run_micro_benchmark(c: &mut Criterion, benchmark: MicroBenchmark) {
let mut group = c.benchmark_group("microbenchmarks");
bench_cpython_code(&mut group, &benchmark);
bench_rustpy_code(&mut group, &benchmark);
group.finish();
}
pub fn criterion_benchmark(c: &mut Criterion) {
let benchmark_dir = Path::new("./benches/microbenchmarks/");
let dirs: Vec<fs::DirEntry> = benchmark_dir
.read_dir()
.unwrap()
.collect::<io::Result<_>>()
.unwrap();
let paths: Vec<PathBuf> = dirs.iter().map(|p| p.path()).collect();
let benchmarks: Vec<MicroBenchmark> = paths
.into_iter()
.map(|p| {
let name = p.file_name().unwrap().to_os_string();
let contents = fs::read_to_string(p).unwrap();
let iterate = contents.contains("ITERATIONS");
let (setup, code) = if contents.contains("# ---") {
let split: Vec<&str> = contents.splitn(2, "# ---").collect();
(split[0].to_string(), split[1].to_string())
} else {
("".to_string(), contents)
};
let name = name.into_string().unwrap();
MicroBenchmark {
name,
setup,
code,
iterate,
}
})
.collect();
for benchmark in benchmarks {
if SKIP_MICROBENCHMARKS.contains(&benchmark.name.as_str()) {
continue;
}
run_micro_benchmark(c, benchmark);
}
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
pub struct Solution;
use std::path::{
Component::{Normal, ParentDir},
Path,
};
impl Solution {
pub fn simplify_path(path: String) -> String {
let mut parts = Vec::new();
for component in Path::new(&path).components() {
match component {
Normal(s) => {
parts.push(s.to_str().unwrap());
}
ParentDir => {
parts.pop();
}
_ => {}
}
}
if parts.is_empty() {
String::from("/")
} else {
let mut res = String::new();
for part in parts {
res.push('/');
res.push_str(part)
}
res
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn check(src: &str, expected: &str) {
assert_eq!(
Solution::simplify_path(String::from(src)),
String::from(expected)
);
}
#[test]
fn example1() {
check("/home/", "/home");
}
#[test]
fn example2() {
check("/../", "/");
}
#[test]
fn example3() {
check("/home//foo/", "/home/foo");
}
#[test]
fn example4() {
check("/a/./b/../../c/", "/c");
}
}
|
// Merge k Sorted Lists
// https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3615/
use crate::linked_list::ListNode;
pub struct Solution;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
impl PartialOrd<ListNode> for ListNode {
fn partial_cmp(&self, other: &ListNode) -> Option<Ordering> {
other.val.partial_cmp(&self.val)
}
}
impl Ord for ListNode {
fn cmp(&self, other: &Self) -> Ordering {
other.val.cmp(&self.val)
}
}
impl Solution {
pub fn merge_k_lists(
mut lists: Vec<Option<Box<ListNode>>>,
) -> Option<Box<ListNode>> {
let mut heap = BinaryHeap::with_capacity(lists.len());
for list in lists.iter_mut() {
if list.is_some() {
heap.push(list.take());
}
}
let mut leader: Box<ListNode> = Box::new(ListNode::new(0));
let mut current = &mut leader;
while let Some(list) = heap.pop() {
current.next = list;
current = current.next.as_mut().unwrap();
let next = current.next.take();
if next.is_some() {
heap.push(next)
};
}
leader.next
}
}
#[cfg(test)]
mod tests {
use super::*;
fn check(src: &[&[i32]], expected: &[i32]) {
let lists = src.iter().copied().map(ListNode::from_slice).collect();
let res = ListNode::to_vec(&mut Solution::merge_k_lists(lists));
assert_eq!(&res, expected);
}
#[test]
fn exmaple1() {
check(
&[&[1, 4, 5], &[1, 3, 4], &[2, 6]],
&[1, 1, 2, 3, 4, 4, 5, 6],
);
}
#[test]
fn exmaple2() {
check(&[], &[]);
}
#[test]
fn exmaple3() {
check(&[&[]], &[]);
}
}
|
// error-pattern: Unsatisfied precondition constraint (for example, even(y
fn print_even(y: int) : even(y) {
log y;
}
pred even(y: int) -> bool {
true
}
fn main() {
let y: int = 42;
check even(y);
do {
print_even(y);
do {
do {
do {
y += 1;
} while (true);
} while (true);
} while (true);
} while (true);
}
|
use super::*;
#[test]
fn with_locked_adds_heap_message_to_mailbox_and_returns_message() {
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(&strategy::term(arc_process.clone()), |message| {
let destination = arc_process.pid_term();
prop_assert_eq!(result(&arc_process, destination, message), Ok(message));
prop_assert!(has_process_message(&arc_process, message));
Ok(())
})
.unwrap();
});
}
#[test]
fn without_locked_adds_process_message_to_mailbox_and_returns_message() {
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(&strategy::term(arc_process.clone()), |message| {
let different_arc_process = test::process::child(&arc_process);
let destination = different_arc_process.pid_term();
prop_assert_eq!(result(&arc_process, destination, message), Ok(message));
prop_assert!(has_process_message(&different_arc_process, message));
Ok(())
})
.unwrap();
});
}
|
/*
* Open Service Cloud API
*
* Open Service Cloud API to manage different backend cloud services.
*
* The version of the OpenAPI document: 0.0.3
* Contact: wanghui71leon@gmail.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudServerRequestFragmentNics {
#[serde(rename = "subnet_id")]
pub subnet_id: String,
}
impl CloudServerRequestFragmentNics {
pub fn new(subnet_id: String) -> CloudServerRequestFragmentNics {
CloudServerRequestFragmentNics {
subnet_id: subnet_id,
}
}
}
|
extern crate docopt;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate walkdir;
extern crate image;
extern crate img_hash;
use std::io::{self, BufWriter, Stderr, Stdout, Write};
use docopt::Docopt;
use img_hash::{ImageHash, HashType};
use walkdir::{DirEntry, WalkDir};
const USAGE: &'static str = "
Usage:
rdedup [options] [<dir> ...]
Options:
-h, --help
-L, --follow-links Follow symlinks.
--min-depth NUM Minimum depth.
--max-depth NUM Maximum depth.
-n, --fd-max NUM Maximum open file descriptors. [default: 32]
-x, --same-file-system Stay on the same file system.
";
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Args {
arg_dir: Option<Vec<String>>,
flag_follow_links: bool,
flag_min_depth: Option<usize>,
flag_max_depth: Option<usize>,
flag_fd_max: usize,
flag_same_file_system: bool,
}
macro_rules! wout { ($($tt:tt)*) => { {writeln!($($tt)*)}.unwrap() } }
fn is_hidden(entry: &DirEntry) -> bool {
entry.file_name()
.to_str()
.map(|s| s.starts_with("."))
.unwrap_or(false)
}
fn print_image_details(out: &mut BufWriter<Stdout>, eout: &mut Stderr, dent: DirEntry) {
let image = image::open(dent.path());
match image {
Err(err) => {
out.flush().unwrap();
wout!(eout, "ERROR: {}", err);
}
Ok(image) => {
let hash = ImageHash::hash(&image, 8, HashType::DCT);
let path = dent.path().canonicalize();
wout!(out, "{}\t{}", hash.to_base64(), path.unwrap().display());
}
}
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
let mind = args.flag_min_depth.unwrap_or(0);
let maxd = args.flag_max_depth.unwrap_or(::std::usize::MAX);
for dir in args.arg_dir.unwrap_or(vec![".".to_string()]) {
let walkdir = WalkDir::new(dir)
.max_open(args.flag_fd_max)
.follow_links(args.flag_follow_links)
.min_depth(mind)
.max_depth(maxd)
.same_file_system(args.flag_same_file_system);
let it = walkdir.into_iter();
let mut out = io::BufWriter::new(io::stdout());
let mut eout = io::stderr();
for dent in it.filter_entry(|e| !is_hidden(e)) {
match dent {
Err(err) => {
out.flush().unwrap();
wout!(eout, "ERROR: {}", err);
}
Ok(dent) => {
if !dent.file_type().is_dir() {
print_image_details(&mut out, &mut eout, dent);
}
}
}
}
}
} |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialGraphInteropFrameOfReferencePreview(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialGraphInteropFrameOfReferencePreview {
type Vtable = ISpatialGraphInteropFrameOfReferencePreview_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa8271b23_735f_5729_a98e_e64ed189abc5);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialGraphInteropFrameOfReferencePreview_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::Numerics::Matrix4x4) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialGraphInteropPreviewStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialGraphInteropPreviewStatics {
type Vtable = ISpatialGraphInteropPreviewStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc042644c_20d8_4ed0_aef7_6805b8e53f55);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialGraphInteropPreviewStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nodeid: ::windows::core::GUID, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nodeid: ::windows::core::GUID, relativeposition: super::super::super::Foundation::Numerics::Vector3, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nodeid: ::windows::core::GUID, relativeposition: super::super::super::Foundation::Numerics::Vector3, relativeorientation: super::super::super::Foundation::Numerics::Quaternion, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nodeid: ::windows::core::GUID, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialGraphInteropPreviewStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialGraphInteropPreviewStatics2 {
type Vtable = ISpatialGraphInteropPreviewStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2490b15f_6cbd_4b1e_b765_31e462a32df2);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialGraphInteropPreviewStatics2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, relativeposition: super::super::super::Foundation::Numerics::Vector3, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, relativeposition: super::super::super::Foundation::Numerics::Vector3, relativeorientation: super::super::super::Foundation::Numerics::Quaternion, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialGraphInteropFrameOfReferencePreview(pub ::windows::core::IInspectable);
impl SpatialGraphInteropFrameOfReferencePreview {
pub fn CoordinateSystem(&self) -> ::windows::core::Result<super::SpatialCoordinateSystem> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::SpatialCoordinateSystem>(result__)
}
}
pub fn NodeId(&self) -> ::windows::core::Result<::windows::core::GUID> {
let this = self;
unsafe {
let mut result__: ::windows::core::GUID = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn CoordinateSystemToNodeTransform(&self) -> ::windows::core::Result<super::super::super::Foundation::Numerics::Matrix4x4> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::Numerics::Matrix4x4 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Numerics::Matrix4x4>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SpatialGraphInteropFrameOfReferencePreview {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.Preview.SpatialGraphInteropFrameOfReferencePreview;{a8271b23-735f-5729-a98e-e64ed189abc5})");
}
unsafe impl ::windows::core::Interface for SpatialGraphInteropFrameOfReferencePreview {
type Vtable = ISpatialGraphInteropFrameOfReferencePreview_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa8271b23_735f_5729_a98e_e64ed189abc5);
}
impl ::windows::core::RuntimeName for SpatialGraphInteropFrameOfReferencePreview {
const NAME: &'static str = "Windows.Perception.Spatial.Preview.SpatialGraphInteropFrameOfReferencePreview";
}
impl ::core::convert::From<SpatialGraphInteropFrameOfReferencePreview> for ::windows::core::IUnknown {
fn from(value: SpatialGraphInteropFrameOfReferencePreview) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialGraphInteropFrameOfReferencePreview> for ::windows::core::IUnknown {
fn from(value: &SpatialGraphInteropFrameOfReferencePreview) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialGraphInteropFrameOfReferencePreview {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a SpatialGraphInteropFrameOfReferencePreview {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialGraphInteropFrameOfReferencePreview> for ::windows::core::IInspectable {
fn from(value: SpatialGraphInteropFrameOfReferencePreview) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialGraphInteropFrameOfReferencePreview> for ::windows::core::IInspectable {
fn from(value: &SpatialGraphInteropFrameOfReferencePreview) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialGraphInteropFrameOfReferencePreview {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a SpatialGraphInteropFrameOfReferencePreview {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialGraphInteropFrameOfReferencePreview {}
unsafe impl ::core::marker::Sync for SpatialGraphInteropFrameOfReferencePreview {}
pub struct SpatialGraphInteropPreview {}
impl SpatialGraphInteropPreview {
pub fn CreateCoordinateSystemForNode<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(nodeid: Param0) -> ::windows::core::Result<super::SpatialCoordinateSystem> {
Self::ISpatialGraphInteropPreviewStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), nodeid.into_param().abi(), &mut result__).from_abi::<super::SpatialCoordinateSystem>(result__)
})
}
#[cfg(feature = "Foundation_Numerics")]
pub fn CreateCoordinateSystemForNodeWithPosition<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::Numerics::Vector3>>(nodeid: Param0, relativeposition: Param1) -> ::windows::core::Result<super::SpatialCoordinateSystem> {
Self::ISpatialGraphInteropPreviewStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), nodeid.into_param().abi(), relativeposition.into_param().abi(), &mut result__).from_abi::<super::SpatialCoordinateSystem>(result__)
})
}
#[cfg(feature = "Foundation_Numerics")]
pub fn CreateCoordinateSystemForNodeWithPositionAndOrientation<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::Numerics::Vector3>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::Numerics::Quaternion>>(nodeid: Param0, relativeposition: Param1, relativeorientation: Param2) -> ::windows::core::Result<super::SpatialCoordinateSystem> {
Self::ISpatialGraphInteropPreviewStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), nodeid.into_param().abi(), relativeposition.into_param().abi(), relativeorientation.into_param().abi(), &mut result__).from_abi::<super::SpatialCoordinateSystem>(result__)
})
}
pub fn CreateLocatorForNode<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(nodeid: Param0) -> ::windows::core::Result<super::SpatialLocator> {
Self::ISpatialGraphInteropPreviewStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), nodeid.into_param().abi(), &mut result__).from_abi::<super::SpatialLocator>(result__)
})
}
pub fn TryCreateFrameOfReference<'a, Param0: ::windows::core::IntoParam<'a, super::SpatialCoordinateSystem>>(coordinatesystem: Param0) -> ::windows::core::Result<SpatialGraphInteropFrameOfReferencePreview> {
Self::ISpatialGraphInteropPreviewStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), &mut result__).from_abi::<SpatialGraphInteropFrameOfReferencePreview>(result__)
})
}
#[cfg(feature = "Foundation_Numerics")]
pub fn TryCreateFrameOfReferenceWithPosition<'a, Param0: ::windows::core::IntoParam<'a, super::SpatialCoordinateSystem>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::Numerics::Vector3>>(coordinatesystem: Param0, relativeposition: Param1) -> ::windows::core::Result<SpatialGraphInteropFrameOfReferencePreview> {
Self::ISpatialGraphInteropPreviewStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), relativeposition.into_param().abi(), &mut result__).from_abi::<SpatialGraphInteropFrameOfReferencePreview>(result__)
})
}
#[cfg(feature = "Foundation_Numerics")]
pub fn TryCreateFrameOfReferenceWithPositionAndOrientation<'a, Param0: ::windows::core::IntoParam<'a, super::SpatialCoordinateSystem>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::Numerics::Vector3>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::Numerics::Quaternion>>(coordinatesystem: Param0, relativeposition: Param1, relativeorientation: Param2) -> ::windows::core::Result<SpatialGraphInteropFrameOfReferencePreview> {
Self::ISpatialGraphInteropPreviewStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), relativeposition.into_param().abi(), relativeorientation.into_param().abi(), &mut result__).from_abi::<SpatialGraphInteropFrameOfReferencePreview>(result__)
})
}
pub fn ISpatialGraphInteropPreviewStatics<R, F: FnOnce(&ISpatialGraphInteropPreviewStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialGraphInteropPreview, ISpatialGraphInteropPreviewStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ISpatialGraphInteropPreviewStatics2<R, F: FnOnce(&ISpatialGraphInteropPreviewStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialGraphInteropPreview, ISpatialGraphInteropPreviewStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for SpatialGraphInteropPreview {
const NAME: &'static str = "Windows.Perception.Spatial.Preview.SpatialGraphInteropPreview";
}
|
#[cfg(test)]
mod tests {
use crate::chip8::cpu::{Cpu, PROGRAM_COUNTER_START_ADDR};
use crate::modules::display::BYTES_PER_CHARACTER;
#[test]
fn test_ret() {
let mut cpu = init(vec!(0x00, 0xEE));
cpu.push(0xFF);
cpu.run();
assert_eq!(cpu.program_counter, 0xFF);
}
#[test]
fn test_jmp() {
let mut cpu = init(vec!(0x10, 0xFF));
cpu.run();
assert_eq!(cpu.program_counter, 0x0FF);
}
#[test]
fn test_call() {
let mut cpu = init(vec!(0x2F, 0xFF));
let pc = cpu.program_counter + 2;
cpu.run();
assert_eq!(cpu.program_counter, 0xFFF);
let stack = cpu.pop();
assert_eq!(stack, pc);
}
#[test]
fn test_se_vx_kk() {
// SE V0 kk
let mut cpu = init(vec!(0x30, 12));
cpu.registers[0] = 12;
cpu.run();
assert_eq!(cpu.program_counter, PROGRAM_COUNTER_START_ADDR + 4);
}
#[test]
fn test_sne_vx_kk() {
// SNE V0 kk
let mut cpu = init(vec!(0x40, 12));
cpu.run();
assert_eq!(cpu.program_counter, PROGRAM_COUNTER_START_ADDR + 4);
}
#[test]
fn test_se_vx_vy() {
// SE V0, V1
let mut cpu = init(vec!(0x50, 0x10));
cpu.registers[0] = 1;
cpu.registers[1] = 1;
cpu.run();
assert_eq!(cpu.program_counter, PROGRAM_COUNTER_START_ADDR + 4);
}
#[test]
fn test_ld_vx_kk() {
let mut cpu = init(vec!(0x60, 0x12));
cpu.run();
assert_eq!(cpu.registers[0], 0x12);
}
#[test]
fn test_add_vx_kk() {
let reg: usize = 0;
let mut cpu = init(vec!(0x70, 0x12));
cpu.registers[reg] = 0x05;
cpu.run();
assert_eq!(cpu.registers[reg], 0x12 + 0x05);
}
#[test]
fn test_ld_vx_vy() {
let mut cpu = init(vec!(0x80, 0x10));
cpu.registers[1] = 0xFF;
cpu.run();
assert_eq!(cpu.registers[0], 0xFF);
}
#[test]
fn test_or_vx_vy() {
let mut cpu = init(vec!(0x80, 0x11));
cpu.registers[0] = 0xF0;
cpu.registers[1] = 0x0F;
cpu.run();
assert_eq!(cpu.registers[0], 0xFF);
}
#[test]
fn test_and_vx_vy() {
let mut cpu = init(vec!(0x80, 0x12));
cpu.registers[0] = 0xF0;
cpu.registers[1] = 0xFF;
cpu.run();
assert_eq!(cpu.registers[0], 0xF0);
}
#[test]
fn test_xor_vx_vy() {
let mut cpu = init(vec!(0x80, 0x13));
cpu.registers[0] = 0xF0;
cpu.registers[1] = 0x00;
cpu.run();
assert_eq!(cpu.registers[0], 0xF0);
}
#[test]
fn test_add_vx_vy() {
let mut cpu = init(vec!(0x80, 0x14));
cpu.registers[0] = 5;
cpu.registers[1] = 10;
cpu.run();
assert_eq!(cpu.registers[0], 15);
assert_eq!(cpu.registers[0x0F], 0);
}
#[test]
fn test_add_vx_vy_vf() {
let mut cpu = init(vec!(0x80, 0x14));
cpu.registers[0] = 255;
cpu.registers[1] = 2;
cpu.run();
assert_eq!(cpu.registers[0], 1);
assert_eq!(cpu.registers[0x0F], 1);
}
#[test]
fn test_sub_vx_vy() {
let mut cpu = init(vec!(0x80, 0x15));
cpu.registers[0] = 15;
cpu.registers[1] = 10;
cpu.run();
assert_eq!(cpu.registers[0], 5);
assert_eq!(cpu.registers[0x0F], 1);
}
#[test]
fn test_sub_vx_vy_vf() {
let mut cpu = init(vec!(0x80, 0x15));
cpu.registers[0] = 1;
cpu.registers[1] = 2;
cpu.run();
assert_eq!(cpu.registers[0], 255);
assert_eq!(cpu.registers[0x0F], 0);
}
#[test]
fn test_shr_vx() {
let mut cpu = init(vec!(0x80, 0x06));
cpu.registers[0] = 1;
cpu.run();
assert_eq!(cpu.registers[0], 1 >> 1);
}
#[test]
fn test_shr_vx_vf() {
let mut cpu = init(vec!(0x80, 0x06));
cpu.registers[0] = 0b00001111;
cpu.run();
assert_eq!(cpu.registers[0], 0b00001111 >> 1);
assert_eq!(cpu.registers[0x0F], 1);
}
#[test]
fn test_subn_vx_vy() {
let mut cpu = init(vec!(0x80, 0x17));
cpu.registers[0] = 10;
cpu.registers[1] = 15;
cpu.run();
assert_eq!(cpu.registers[0], 5);
assert_eq!(cpu.registers[0x0F], 1);
}
#[test]
fn test_subn_vx_vy_vf() {
let mut cpu = init(vec!(0x80, 0x17));
cpu.registers[0] = 2;
cpu.registers[1] = 1;
cpu.run();
assert_eq!(cpu.registers[0], 255);
assert_eq!(cpu.registers[0x0F], 0);
}
#[test]
fn test_shl_vx() {
let mut cpu = init(vec!(0x80, 0x0E));
cpu.registers[0] = 2;
cpu.run();
assert_eq!(cpu.registers[0], 4);
assert_eq!(cpu.registers[0x0F], 0);
}
#[test]
fn test_shl_vx_vf() {
let mut cpu = init(vec!(0x80, 0x0E));
cpu.registers[0] = 0xF0;
cpu.run();
assert_eq!(cpu.registers[0], 0xF0 << 1);
assert_eq!(cpu.registers[0x0F], 1);
}
#[test]
fn test_sne_vx_vy() {
let mut cpu = init(vec!(0x90, 0x10));
cpu.registers[0] = 1;
cpu.run();
assert_eq!(cpu.program_counter, PROGRAM_COUNTER_START_ADDR + 4);
}
#[test]
fn test_ld_i_addr() {
let mut cpu = init(vec!(0xAF, 0xFF));
cpu.run();
assert_eq!(cpu.i, 0xFFF);
}
#[test]
fn test_jp_v0() {
let mut cpu = init(vec!(0xBF, 0xFF));
cpu.registers[0] = 1;
cpu.run();
assert_eq!(cpu.program_counter, 0xFFF + 1);
}
#[test]
fn test_ld_vx_dt() {
let mut cpu = init(vec!(0xF0, 0x07));
cpu.delay_timer = 10;
cpu.run();
assert_eq!(cpu.registers[0], 10);
}
#[test]
fn test_ld_dt_vx() {
let mut cpu = init(vec!(0xF0, 0x15));
cpu.registers[0] = 10;
cpu.run();
assert_eq!(cpu.delay_timer, 10 - 1);
}
#[test]
fn test_ld_st_vx() {
let mut cpu = init(vec!(0xF0, 0x18));
cpu.registers[0] = 10;
cpu.run();
assert_eq!(cpu.sound_timer, 10 - 1);
}
#[test]
fn test_add_i_vx() {
let mut cpu = init(vec!(0xF0, 0x1E));
cpu.registers[0] = 10;
cpu.i = 10;
cpu.run();
assert_eq!(cpu.i, 20);
}
#[test]
fn test_ld_f_vx() {
let mut cpu = init(vec!(0xF0, 0x29));
cpu.registers[0] = 10;
cpu.run();
assert_eq!(cpu.i, 10 * BYTES_PER_CHARACTER as usize);
}
fn init(program: Vec<u8>) -> Cpu {
Cpu::new(&program)
}
} |
extern crate windows_winmd as winmd;
#[test]
fn stringable() {
let reader = winmd::TypeReader::get();
let def = reader.expect_type_def(("Windows.Foundation", "IStringable"));
assert!(def.name() == ("Windows.Foundation", "IStringable"));
let methods: Vec<winmd::parsed::MethodDef> = def.methods().collect();
assert!(methods.len() == 1);
let method = methods[0];
assert!(method.name() == "ToString");
}
|
//! LEGO EV3 ultrasonic sensor
use super::{Sensor, SensorPort};
use crate::{sensor_mode, Attribute, Device, Driver, Ev3Error, Ev3Result};
use std::cell::Cell;
/// LEGO EV3 ultrasonic sensor.
#[derive(Debug, Clone, Device, Sensor)]
pub struct UltrasonicSensor {
driver: Driver,
cm_scale: Cell<Option<f32>>,
in_scale: Cell<Option<f32>>,
}
impl UltrasonicSensor {
fn new(driver: Driver) -> Self {
Self {
driver,
cm_scale: Cell::new(None),
in_scale: Cell::new(None),
}
}
findable!(
"lego-sensor",
["lego-ev3-us", "lego-nxt-us"],
SensorPort,
"UltrasonicSensor",
"in"
);
sensor_mode!(
"US-DIST-CM",
MODE_US_DIST_CM,
"Continuous measurement - sets LEDs on, steady. Units in centimeters. Distance (0-2550)",
set_mode_us_dist_cm,
is_mode_us_dist_cm
);
sensor_mode!(
"US-DIST-IN",
MODE_US_DIST_IN,
"Continuous measurement - sets LEDs on, steady. Units in inches. Distance (0-1003)",
set_mode_us_dist_in,
is_mode_us_dist_in
);
sensor_mode!(
"US-LISTEN",
MODE_US_LISTEN,
"Listen - sets LEDs on, blinking. Presence (0-1) #",
set_mode_us_listen,
is_mode_us_listen
);
sensor_mode!(
"US-SI-CM",
MODE_US_SI_CM,
"Single measurement - LEDs on momentarily when mode is set, then off. Units in centimeters. Distance (0-2550)",
set_mode_us_si_cm,
is_mode_us_si_cm
);
sensor_mode!(
"US-SI-IN",
MODE_US_SI_IN,
"Single measurement - LEDs on momentarily when mode is set, then off. Units in inches. Distance (0-1003)",
set_mode_us_si_in,
is_mode_us_si_in
);
sensor_mode!(
"US-DC-CM",
MODE_US_DC_CM,
"??? - sets LEDs on, steady. Units in centimeters. Distance (0-2550)",
set_mode_us_dc_cm,
is_mode_us_dc_cm
);
sensor_mode!(
"US-DC-IN",
MODE_US_DC_IN,
"??? - sets LEDs on, steady. Units in inches. Distance (0-1003)",
set_mode_us_dc_in,
is_mode_us_dc_in
);
/// Measurement of the distance detected by the sensor, unscaled.
pub fn get_distance(&self) -> Ev3Result<i32> {
self.get_value0()
}
/// Measurement of the distance detected by the sensor, in centimeters.
pub fn get_distance_centimeters(&self) -> Ev3Result<f32> {
let scale_field = self.cm_scale.get();
let scale = match scale_field {
Some(s) => s,
None => {
let decimals = self.get_decimals()?;
let s = 10f32.powi(-decimals);
self.cm_scale.set(Some(s));
s
}
};
Ok((self.get_value0()? as f32) * scale)
}
/// Measurement of the distance detected by the sensor, in centimeters.
pub fn get_distance_inches(&self) -> Ev3Result<f32> {
let scale_field = self.in_scale.get();
let scale = match scale_field {
Some(s) => s,
None => {
let decimals = self.get_decimals()?;
let s = 10f32.powi(-decimals);
self.in_scale.set(Some(s));
s
}
};
Ok((self.get_value0()? as f32) * scale)
}
}
|
::windows_sys::core::link ! ( "efswrt.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"] fn ProtectFileToEnterpriseIdentity ( fileorfolderpath : :: windows_sys::core::PCWSTR , identity : :: windows_sys::core::PCWSTR ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`, `\"Win32_Foundation\"`*"] fn SrpCloseThreadNetworkContext ( threadnetworkcontext : *mut HTHREAD_NETWORK_CONTEXT ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`, `\"Win32_Foundation\"`*"] fn SrpCreateThreadNetworkContext ( enterpriseid : :: windows_sys::core::PCWSTR , threadnetworkcontext : *mut HTHREAD_NETWORK_CONTEXT ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"] fn SrpDisablePermissiveModeFileEncryption ( ) -> :: windows_sys::core::HRESULT );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_Packaging_Appx"))]
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`, `\"Win32_Foundation\"`, `\"Win32_Storage_Packaging_Appx\"`*"] fn SrpDoesPolicyAllowAppExecution ( packageid : *const super::super::Storage::Packaging::Appx:: PACKAGE_ID , isallowed : *mut super::super::Foundation:: BOOL ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"] fn SrpEnablePermissiveModeFileEncryption ( enterpriseid : :: windows_sys::core::PCWSTR ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`, `\"Win32_Foundation\"`*"] fn SrpGetEnterpriseIds ( tokenhandle : super::super::Foundation:: HANDLE , numberofbytes : *mut u32 , enterpriseids : *mut :: windows_sys::core::PWSTR , enterpriseidcount : *mut u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`, `\"Win32_Foundation\"`*"] fn SrpGetEnterprisePolicy ( tokenhandle : super::super::Foundation:: HANDLE , policyflags : *mut ENTERPRISE_DATA_POLICIES ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"] fn SrpHostingInitialize ( version : SRPHOSTING_VERSION , r#type : SRPHOSTING_TYPE , pvdata : *const ::core::ffi::c_void , cbdata : u32 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"] fn SrpHostingTerminate ( r#type : SRPHOSTING_TYPE ) -> ( ) );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`, `\"Win32_Foundation\"`*"] fn SrpIsTokenService ( tokenhandle : super::super::Foundation:: HANDLE , istokenservice : *mut u8 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "srpapi.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`, `\"Win32_Foundation\"`*"] fn SrpSetTokenEnterpriseId ( tokenhandle : super::super::Foundation:: HANDLE , enterpriseid : :: windows_sys::core::PCWSTR ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "efswrt.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"] fn UnprotectFile ( fileorfolderpath : :: windows_sys::core::PCWSTR , options : *const FILE_UNPROTECT_OPTIONS ) -> :: windows_sys::core::HRESULT );
pub type IProtectionPolicyManagerInterop = *mut ::core::ffi::c_void;
pub type IProtectionPolicyManagerInterop2 = *mut ::core::ffi::c_void;
pub type IProtectionPolicyManagerInterop3 = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub type ENTERPRISE_DATA_POLICIES = u32;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub const ENTERPRISE_POLICY_NONE: ENTERPRISE_DATA_POLICIES = 0u32;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub const ENTERPRISE_POLICY_ALLOWED: ENTERPRISE_DATA_POLICIES = 1u32;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub const ENTERPRISE_POLICY_ENLIGHTENED: ENTERPRISE_DATA_POLICIES = 2u32;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub const ENTERPRISE_POLICY_EXEMPT: ENTERPRISE_DATA_POLICIES = 4u32;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub type SRPHOSTING_TYPE = i32;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub const SRPHOSTING_TYPE_NONE: SRPHOSTING_TYPE = 0i32;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub const SRPHOSTING_TYPE_WINHTTP: SRPHOSTING_TYPE = 1i32;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub const SRPHOSTING_TYPE_WININET: SRPHOSTING_TYPE = 2i32;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub type SRPHOSTING_VERSION = i32;
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub const SRPHOSTING_VERSION1: SRPHOSTING_VERSION = 1i32;
#[repr(C)]
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"]
pub struct FILE_UNPROTECT_OPTIONS {
pub audit: u8,
}
impl ::core::marker::Copy for FILE_UNPROTECT_OPTIONS {}
impl ::core::clone::Clone for FILE_UNPROTECT_OPTIONS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct HTHREAD_NETWORK_CONTEXT {
pub ThreadId: u32,
pub ThreadContext: super::super::Foundation::HANDLE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for HTHREAD_NETWORK_CONTEXT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for HTHREAD_NETWORK_CONTEXT {
fn clone(&self) -> Self {
*self
}
}
|
use super::conf::{CMutConf, Rc33M};
use super::nav::CursorNav;
use traits::{Leaf, PathInfo, SubOrd};
use node::{Node, NodesPtr, insert_maybe_split};
use std::{fmt, mem};
use std::iter::FromIterator;
use std::marker::PhantomData;
use arrayvec::ArrayVec;
// Note: The working of `CursorMut` is fundamentally different from `Cursor`. `CursorMut` can
// become empty (iff `cur_node` is empty. `cur_node` empty implies `steps` is also empty).
/// A object that can be used to modify internals of `Node` while maintaining balance.
///
/// `CursorMut` is heavier compared to `Cursor`. Even though `CursorMut` does not make any heap
/// allocations for its own operations, most operations tries to make the current node writable
/// using `Arc::make_mut`. This could result in a heap allocation if the number of references to
/// that node is more than one.
///
/// Note: `CursorMut` takes more than 200B on stack (exact size mainly depends on the size of `PI`)
pub struct CursorMut<L, PI, CONF = Rc33M>
where L: Leaf,
CONF: CMutConf<L, PI>,
{
cur_node: Node<L, CONF::Ptr>,
steps: ArrayVec<CONF::MutStepsBuf>,
}
pub struct CMutStep<L, PI, CONF>
where L: Leaf,
CONF: CMutConf<L, PI>,
{
nodes: CONF::Ptr,
idx: usize,
path_info: PI,
__phantom: PhantomData<L>,
}
impl<L, PI, CONF> Clone for CursorMut<L, PI, CONF>
where L: Leaf + Clone,
PI: PathInfo<L::Info>,
CONF: CMutConf<L, PI>,
{
fn clone(&self) -> Self {
CursorMut {
cur_node: self.cur_node.clone(),
steps: self.steps.clone(),
}
}
}
impl<L, PI, CONF> Clone for CMutStep<L, PI, CONF>
where L: Leaf + Clone,
PI: PathInfo<L::Info>,
CONF: CMutConf<L, PI>,
{
fn clone(&self) -> Self {
CMutStep {
nodes: self.nodes.clone(),
idx: self.idx,
path_info: self.path_info.clone(),
__phantom: PhantomData,
}
}
}
impl<L, PI, CONF> CMutStep<L, PI, CONF>
where L: Leaf,
PI: PathInfo<L::Info>,
CONF: CMutConf<L, PI>,
{
fn new(nodes: CONF::Ptr, idx: usize, path_info: PI) -> Self {
let __phantom = PhantomData;
CMutStep { nodes, idx, path_info, __phantom }
}
}
impl<L, PI, CONF> fmt::Debug for CMutStep<L, PI, CONF>
where L: Leaf,
PI: fmt::Debug,
CONF: CMutConf<L, PI>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "CMutStep {{ nodes.len: {}, idx: {}, path_info: {:?} }}",
self.nodes.len(), self.idx, self.path_info)
}
}
impl<L, PI, CONF> CursorMut<L, PI, CONF>
where L: Leaf,
PI: PathInfo<L::Info>,
CONF: CMutConf<L, PI>,
{
pub fn new() -> Self {
CursorMut {
cur_node: Node::never(),
steps: ArrayVec::new(),
}
}
pub fn from_node(node: Node<L, CONF::Ptr>) -> Self {
CursorMut {
cur_node: node,
steps: ArrayVec::new(),
}
}
pub fn into_root(mut self) -> Option<Node<L, CONF::Ptr>> {
self.reset();
self.take_current()
}
pub fn current(&self) -> Option<&Node<L, CONF::Ptr>> {
match self.cur_node {
Node::Never(_) => None,
ref node => Some(node),
}
}
pub fn is_empty(&self) -> bool {
self.current().is_none()
}
/// Height of the current node from leaves.
pub fn height(&self) -> Option<usize> {
self.current().map(|node| node.height())
}
/// Returns a reference to the leaf's value if the current node is a leaf.
pub fn leaf(&self) -> Option<&L> {
match self.cur_node {
Node::Never(_) => None,
ref cur_node => cur_node.leaf(),
}
}
/// Returns whether the cursor is currently at the root of the tree.
///
/// Returns `true` even if the cursor is empty.
pub fn is_root(&self) -> bool {
self.steps.len() == 0
}
/// The cumulative info along the path from root to this node. Returns `PathInfo::identity()`
/// if the current node is root or cursor is empty.
pub fn path_info(&self) -> PI {
match self.steps.last() {
Some(cstep) => cstep.path_info,
None => PI::identity(),
}
}
/// Update the leaf value in-place using `f`. This is a no-op if the current node is not a
/// leaf.
pub fn leaf_update<F>(&mut self, f: F) where F: FnOnce(&mut L) {
self.cur_node.leaf_update(f);
}
/// The `path_info` till this node and after.
///
/// Returns `Some((p, p.extend(current.info())))` where `p` is `path_info()` if cursor is
/// non-empty, `None` otherwise.
pub fn path_interval(&self) -> Option<(PI, PI)> {
match self.current() {
Some(cur_node) => Some({
let path_info = self.path_info();
(path_info, path_info.extend(cur_node.info()))
}),
None => None,
}
}
/// Returns the position of the current node with respect to its sibling nodes. The pair
/// indicate `(left_index, right_index)`, or more simply, the number of siblings to the left
/// and to the right respectively.
pub fn position(&self) -> Option<(usize, usize)> {
self.steps.last().map(|cstep| (cstep.idx, cstep.nodes.len() - cstep.idx - 1))
}
pub fn reset(&mut self) {
while self.ascend().is_some() {}
}
pub fn ascend(&mut self) -> Option<&Node<L, CONF::Ptr>> {
match self.pop_step() {
Some(CMutStep { nodes, idx, .. }) => {
self.ascend_raw(nodes, idx);
Some(&self.cur_node)
}
None => None, // cur_node is the root (or empty)
}
}
pub fn descend_first(&mut self) -> Option<&Node<L, CONF::Ptr>> {
match self.take_current() {
Some(cur_node) => {
let path_info = self.path_info();
match cur_node.into_children() {
Ok(nodes) => {
self.descend_raw(nodes, 0, path_info);
Some(&self.cur_node)
}
Err(mut cur_node) => {
self.cur_node.never_swap(&mut cur_node);
None
}
}
}
None => None, // empty cursor
}
}
pub fn descend_last(&mut self) -> Option<&Node<L, CONF::Ptr>> {
match self.take_current() {
Some(cur_node) => {
let path_info = self.path_info().extend(cur_node.info());
match cur_node.into_children() {
Ok(nodes) => {
let lastidx = nodes.len() - 1;
let lastinfo = nodes[lastidx].info();
self.descend_raw(nodes, lastidx, path_info.extend_inv(lastinfo));
Some(&self.cur_node)
}
Err(mut cur_node) => {
self.cur_node.never_swap(&mut cur_node);
None
}
}
}
None => None, // empty cursor
}
}
pub fn left_sibling(&mut self) -> Option<&Node<L, CONF::Ptr>> {
let &mut CursorMut { ref mut cur_node, ref mut steps } = self;
match steps.last_mut() {
Some(&mut CMutStep { ref mut nodes, ref mut idx, ref mut path_info, .. }) => {
debug_assert!(!cur_node.is_never());
if *idx > 0 {
let nodes = <CONF::Ptr as NodesPtr<L>>::make_mut(nodes);
cur_node.never_swap(&mut nodes[*idx]);
*idx -= 1;
cur_node.never_swap(&mut nodes[*idx]);
*path_info = path_info.extend_inv(cur_node.info());
Some(&*cur_node)
} else {
None
}
}
None => None, // at the root
}
}
pub fn right_sibling(&mut self) -> Option<&Node<L, CONF::Ptr>> {
let &mut CursorMut { ref mut cur_node, ref mut steps } = self;
match steps.last_mut() {
Some(&mut CMutStep { ref mut nodes, ref mut idx, ref mut path_info, .. }) => {
debug_assert!(!cur_node.is_never());
if *idx + 1 < nodes.len() {
*path_info = path_info.extend(cur_node.info());
let nodes = <CONF::Ptr as NodesPtr<L>>::make_mut(nodes);
cur_node.never_swap(&mut nodes[*idx]);
*idx += 1;
cur_node.never_swap(&mut nodes[*idx]);
Some(&*cur_node)
} else {
None
}
}
None => None, // at the root
}
}
pub fn first_leaf(&mut self) -> Option<&L> {
<Self as CursorNav>::first_leaf(self)
}
pub fn last_leaf(&mut self) -> Option<&L> {
<Self as CursorNav>::last_leaf(self)
}
/// Make the cursor point to the next element at the same height.
///
/// If there is no next element, it returns `None` and cursor resets to root.
pub fn next_node(&mut self) -> Option<&Node<L, CONF::Ptr>> {
<Self as CursorNav>::next_node(self)
}
/// Make the cursor point to the previous element at the same height.
///
/// If there is no previous element, it returns `None` and cursor resets to root.
pub fn prev_node(&mut self) -> Option<&Node<L, CONF::Ptr>> {
<Self as CursorNav>::prev_node(self)
}
/// Calls `next_node` and returns the leaf value if it is a leaf node.
pub fn next_leaf(&mut self) -> Option<&L> {
<Self as CursorNav>::next_leaf(self)
}
/// Calls `prev_node` and returns the leaf value if it is a leaf node.
pub fn prev_leaf(&mut self) -> Option<&L> {
<Self as CursorNav>::prev_leaf(self)
}
/// Tries to return the left sibling if exists, or ascends the tree until an ancestor with a
/// left sibling is found and returns that sibling.
pub fn left_maybe_ascend(&mut self) -> Option<&Node<L, CONF::Ptr>> {
<Self as CursorNav>::left_maybe_ascend(self)
}
/// Tries to return the right sibling if exists, or ascends the tree until an ancestor with a
/// right sibling is found and returns that sibling.
pub fn right_maybe_ascend(&mut self) -> Option<&Node<L, CONF::Ptr>> {
<Self as CursorNav>::right_maybe_ascend(self)
}
/// Moves the cursor to the first leaf node which satisfy the following condition:
///
/// `info_sub <= node.info()`
///
/// And returns a reference to it. Returns `None` if no leaf satisfied the condition.
///
/// Conditions for correctness:
/// - The leaves of the tree must be sorted by the value represented by `info_sub` inside
/// `node.info()` in ascending order.
/// - `Leaf::Info::gather` must apply the "min" function on this field.
///
/// See `find_max` for examples.
///
/// A more descriptive name of this might be `find_sorted_suffix_min`.
pub fn find_min<IS>(&mut self, info_sub: IS) -> Option<&L>
where IS: SubOrd<L::Info>,
{
<Self as CursorNav>::find_min(self, info_sub)
}
/// Moves the cursor to the last leaf node which satisfy the following condition:
///
/// `info_sub >= node.info()`
///
/// And returns a reference to it. Returns `None` if no leaf satisfied the condition.
///
/// Conditions for correctness is the same as `find_min`, except that `Leaf::Info::gather` must
/// apply the "max" function on this field, instead of "min".
///
/// Note: If exactly one leaf satisfies equality with `info_sub`, then both `find_max` and
/// `find_min` will return the same element. Here are some examples:
///
/// ```text
/// leaf: ('c', 2) ('j', 1) ('j', 4) ('v', 2)
/// find_min('j') == Some(('j', 1))
/// find_max('j') == find_max('k') == Some(('j', 4))
/// find_min('k') == find_max('z') == Some(('v', 2))
/// find_min('z') == find_max('a') == None
/// ```
///
/// A more descriptive name of this might be `find_sorted_prefix_max`.
pub fn find_max<IS>(&mut self, info_sub: IS) -> Option<&L>
where IS: SubOrd<L::Info>,
{
<Self as CursorNav>::find_max(self, info_sub)
}
/// Moves the cursor to the first leaf node which satisfy the following condition:
///
/// `path_info_sub <= path_info`
///
/// And returns a reference to it. Returns `None` if no leaf satisfied the condition.
///
/// Conditions for correctness:
/// - `Leaf::Info` should not contain "negative" values so that path-info is non-decreasing when
/// `extend`-ed with `Leaf::Info` values.
///
/// See `goto_max` for examples.
///
/// A more descriptive name of this might be `goto_path_suffix_min`.
pub fn goto_min<PS: SubOrd<PI>>(&mut self, path_info_sub: PS) -> Option<&L> {
<Self as CursorNav>::goto_min(self, path_info_sub)
}
/// Moves the cursor to the last leaf node which satisfy the following condition:
///
/// `path_info_sub >= path_info.extend(node.info())`
///
/// And returns a reference to it. Returns `None` if no leaf satisfied the condition.
///
/// Conditions for correctness is the same as `goto_min`.
///
/// These methods can be visualized as follows:
///
/// ```text
/// leaf : 'a' 'b' 'c' 'd' 'e'
/// leaf::info() : 1 1 1 1 1
/// path_info : 0 1 2 3 4 5
/// goto_min(3) ^--~ ^--~ = first of ('d', 'e') = Some('d')
/// goto_max(3) ~--^ ~--^ ~--^ = last of ('a', 'b', 'c') = Some('c')
/// goto_max(0) = None
/// goto_min(5) = goto_min(6) = None
/// goto_max(5) = goto_max(6) = Some('e')
///
/// =====
///
/// leaf : 't' 'u' 'v' 'w' 'x'
/// leaf::info() : 1 1 0 0 1
/// path_info : 0 1 2 2 2 3
/// goto_min(2) ^--~ ^--~ ^--~ = first of ('v', 'w', 'x') = Some('v')
/// goto_max(2) ~--^ ~--^ ~--^ ~--^ = last of ('t', 'u', 'v', 'w') = Some('w')
/// ```
///
/// A more descriptive name of this might be `goto_path_prefix_max`.
pub fn goto_max<PS: SubOrd<PI>>(&mut self, path_info_sub: PS) -> Option<&L> {
<Self as CursorNav>::goto_max(self, path_info_sub)
}
}
impl<L, PI, CONF> CursorNav for CursorMut<L, PI, CONF>
where L: Leaf,
PI: PathInfo<L::Info>,
CONF: CMutConf<L, PI>,
{
type Leaf = L;
type NodesPtr = CONF::Ptr;
type PathInfo = PI;
fn _is_root(&self) -> bool {
self.is_root()
}
fn _path_info(&self) -> PI {
self.path_info()
}
fn _leaf(&self) -> Option<&Self::Leaf> {
self.leaf()
}
fn _height(&self) -> Option<usize> {
self.height()
}
fn _current(&self) -> Option<&Node<L, CONF::Ptr>> {
self.current()
}
fn _current_must(&self) -> &Node<L, CONF::Ptr> {
&self.cur_node
}
fn _reset(&mut self) {
self.reset();
}
fn _ascend(&mut self) -> Option<&Node<L, CONF::Ptr>> {
self.ascend()
}
fn _descend_first(&mut self) -> Option<&Node<L, CONF::Ptr>> {
self.descend_first()
}
fn _descend_last(&mut self) -> Option<&Node<L, CONF::Ptr>> {
self.descend_last()
}
fn _left_sibling(&mut self) -> Option<&Node<L, CONF::Ptr>> {
self.left_sibling()
}
fn _right_sibling(&mut self) -> Option<&Node<L, CONF::Ptr>> {
self.right_sibling()
}
}
// structural modifications
impl<L, PI, CONF> CursorMut<L, PI, CONF>
where L: Leaf,
PI: PathInfo<L::Info>,
CONF: CMutConf<L, PI>,
{
/// Insert `leaf` before or after the current node. If currently not at a leaf node, the cursor
/// first descends to a leaf node (to the first leaf node if `!after`, or the last leaf node),
/// and inserts it per `after`.
///
/// It is unspecified where the cursor will be after this operation. But it is guaranteed that
/// `path_info` will not decrease (i.e. get `extend_inv`-ed). The user should ensure that the
/// cursor is at the intended location after this.
pub fn insert_leaf(&mut self, leaf: L, after: bool) {
self.insert(Node::from_leaf(leaf), after);
}
/// Insert `newnode` before or after the current node and rebalance. `newnode` can be of any
/// height.
pub fn insert(&mut self, newnode: Node<L, CONF::Ptr>, after: bool) {
let newnode_ht = newnode.height();
match self.height() {
Some(cur_ht) if cur_ht >= newnode_ht => {
while self.cur_node.height() > newnode_ht {
let _res = if after { self.descend_last() } else { self.descend_first() };
debug_assert!(_res.is_some());
}
return self.insert_simple(newnode, after);
}
None => {
self.cur_node = newnode;
return;
}
_ => (),
}
let mut current = self.cur_node.never_take();
current = if after {
Node::concat(current, newnode)
} else {
Node::concat(newnode, current)
};
// TODO investigate possible performance tweaks
while let Some(CMutStep { mut nodes, idx, path_info, .. }) = self.pop_step() {
if nodes[(idx + 1) % nodes.len()].height() == current.height() {
self.push_step(CMutStep::new(nodes, idx, path_info));
break;
}
let nodes = <CONF::Ptr as NodesPtr<L>>::make_mut(&mut nodes);
let len = nodes.len();
if idx + 1 < len {
let right = Node::from_children(
<CONF::Ptr as NodesPtr<L>>::new(nodes.drain(idx+1..).collect()));
current = Node::concat(current, right);
}
if idx > 0 {
let left = Node::from_children(
<CONF::Ptr as NodesPtr<L>>::new(nodes.drain(0..idx).collect()));
current = Node::concat(left, current);
}
}
self.cur_node = current;
}
/// Remove the first leaf under the current node.
pub fn remove_leaf(&mut self) -> Option<L> {
self.first_leaf();
self.remove_node().and_then(|n| n.into_leaf().ok())
}
/// Remove the current node and return it. If the cursor is empty, return `None`.
///
/// It is unspecified where the cursor will be after this operation. But it is guaranteed that
/// `path_info` will not increase (or `extend`). The user should ensure that the cursor is at
/// the correct location after this.
pub fn remove_node(&mut self) -> Option<Node<L, CONF::Ptr>> {
match self.take_current() {
Some(cur_node) => {
if let Some(mut cstep) = self.pop_step() {
let dummy = <CONF::Ptr as NodesPtr<L>>::make_mut(&mut cstep.nodes)
.remove(cstep.idx)
.unwrap();
debug_assert!(dummy.is_never());
if cstep.nodes.len() > 0 {
self.fix_current(cstep);
} else {
debug_assert!(self.steps.len() == 0); // should be root
}
}
Some(cur_node)
},
None => None, // cursor is empty
}
}
/// Split the tree into two, and return the right part of it. The current node, all leaves
/// under it, as well as all leaves to the right of it will be included in the returned tree.
///
/// Returns `None` if the cursor was empty.
///
/// Time: O(log n)
pub fn split_off(&mut self) -> Option<Node<L, CONF::Ptr>> {
if self.is_empty() {
return None;
}
let mut this = Node::never();
let mut ret = self.cur_node.never_take();
// Note on time complexity: Even though time complexity of concat is O(log n), the heights
// of nodes being concated differ only by 1 (amortized).
while let Some(CMutStep { mut nodes, idx, .. }) = self.pop_step() {
{ // mutate nodes
let nodes = <CONF::Ptr as NodesPtr<L>>::make_mut(&mut nodes);
let right_nodes = nodes.drain(idx + 1 ..)
.collect::<ArrayVec<<CONF::Ptr as NodesPtr<L>>::Array>>();
if right_nodes.len() > 0 {
ret = Node::concat(ret, Node::from_children(
<CONF::Ptr as NodesPtr<L>>::new(right_nodes)));
}
nodes.pop(); // pop the never node at idx
}
if nodes.len() > 0 {
let left_node = Node::from_children(nodes);
this = match this {
Node::Never(_) => left_node,
_ => Node::concat(left_node, this),
};
}
}
self.cur_node = this;
Some(ret)
}
}
impl<L, PI, CONF> CursorMut<L, PI, CONF>
where L: Leaf,
PI: PathInfo<L::Info>,
CONF: CMutConf<L, PI>,
{
fn insert_simple(&mut self, mut newnode: Node<L, CONF::Ptr>, after: bool) {
if self.is_empty() {
self.cur_node = newnode;
return;
}
let &mut CursorMut { ref mut cur_node, ref mut steps } = self;
loop {
debug_assert_eq!(cur_node.height(), newnode.height());
match steps.last_mut() {
Some(&mut CMutStep { ref mut nodes, ref mut idx, ref mut path_info, .. }) => {
let maybe_split;
{
let nodes = <CONF::Ptr as NodesPtr<L>>::make_mut(nodes);
if !newnode.has_min_size() {
let merged = {
let (left_int, right_int) =
if after {
(cur_node.internal_mut_must(), newnode.internal_mut_must())
} else {
(newnode.internal_mut_must(), cur_node.internal_mut_must())
};
left_int.try_merge_with(right_int)
};
if merged {
if !after {
*cur_node = newnode;
}
return;
}
}
debug_assert!(!cur_node.is_never());
let cur_info = cur_node.info();
cur_node.never_swap(&mut nodes[*idx]);
if after {
*path_info = path_info.extend(cur_info);
*idx += 1;
}
maybe_split = insert_maybe_split(nodes, *idx, newnode);
}
// now cur_node is never
if let Some(mut split_nodes) = maybe_split {
if !after {
mem::swap(&mut split_nodes, nodes);
}
newnode = Node::from_children(split_nodes);
// the only way out of match without returning
} else {
let nodes = <CONF::Ptr as NodesPtr<L>>::make_mut(nodes);
cur_node.never_swap(&mut nodes[*idx]);
return;
}
}
None => { // cur_node is the root
*cur_node = if after {
Node::concat(cur_node.never_take(), newnode)
} else {
Node::concat(newnode, cur_node.never_take())
};
return;
}
}
// ascend the tree (cur_node is never, nodes[idx] is valid)
let CMutStep { nodes, .. } = steps.pop().unwrap();
let parent = Node::from_children(nodes); // gather info
*cur_node = parent;
}
}
// Find a replacement node for the current node. May ascend the tree multiple times.
fn fix_current(&mut self, cstep: CMutStep<L, PI, CONF>) {
debug_assert!(self.cur_node.is_never());
let CMutStep { mut nodes, mut idx, mut path_info, .. } = cstep;
let nodes_len = nodes.len();
debug_assert!(nodes_len > 0); // nodes should never be empty
debug_assert!(nodes.iter().all(|n| !n.is_never())); // nodes should be all valid
let steps_len = self.steps.len();
if nodes_len >= <CONF::Ptr as NodesPtr<L>>::max_size()/2 || steps_len == 0 {
let at_right_end = idx == nodes_len;
if at_right_end {
idx -= 1;
}
self.cur_node.never_swap(&mut <CONF::Ptr as NodesPtr<L>>::make_mut(&mut nodes)[idx]);
if at_right_end {
path_info = path_info.extend_inv(self.cur_node.info());
}
debug_assert!(self.cur_node.is_leaf() || self.cur_node.has_min_size());
self.push_step(CMutStep::new(nodes, idx, path_info));
} else { // steps_len > 0
debug_assert_eq!(nodes_len, <CONF::Ptr as NodesPtr<L>>::max_size()/2 - 1);
self.cur_node = Node::from_children(nodes);
self.merge_adjacent();
}
}
// Merge the current node with an adjacent sibling to make it balanced.
fn merge_adjacent(&mut self) {
debug_assert!(!self.cur_node.is_never());
debug_assert_eq!(self.cur_node.children().len(), <CONF::Ptr as NodesPtr<L>>::max_size()/2 - 1);
let CMutStep { mut nodes, mut idx, mut path_info, .. } = self.pop_step().unwrap();
if nodes.len() == 1 { // cur_node is the only child
debug_assert!(self.steps.len() == 0); // the parent must be root
return; // cur_node becomes the root
}
let merge_left = idx + 1 == nodes.len(); // merge with the right node by default
debug_assert!(nodes.len() > 1);
let merged;
{
let nodes = <CONF::Ptr as NodesPtr<L>>::make_mut(&mut nodes);
merged = if merge_left {
let left_node_int = nodes.get_mut(idx - 1).unwrap().internal_mut_must();
path_info = path_info.extend_inv(left_node_int.info());
left_node_int.try_merge_with(self.cur_node.internal_mut_must())
} else {
let right_node_int = nodes.get_mut(idx + 1).unwrap().internal_mut_must();
self.cur_node.internal_mut_must().try_merge_with(right_node_int)
};
if merged {
if merge_left {
self.cur_node.never_take(); // make the now empty cur_node never
nodes.remove(idx).unwrap(); // and remove its placeholder
idx -= 1; // make left_node be the current node (path_info already adjusted)
} else {
nodes.remove(idx + 1).unwrap(); // remove the now empty right_node
self.cur_node.never_swap(&mut nodes[idx]);
}
debug_assert!(self.cur_node.is_never());
} else {
if merge_left {
self.cur_node.never_swap(&mut nodes[idx]);
idx -= 1; // make left_node be the current node (for path_info correctness)
self.cur_node.never_swap(&mut nodes[idx]);
}
debug_assert!(!self.cur_node.is_never());
}
};
let cstep = CMutStep::new(nodes, idx, path_info);
if merged {
self.fix_current(cstep);
} else {
self.push_step(cstep);
}
}
fn ascend_raw(&mut self, mut nodes: CONF::Ptr, idx: usize) {
debug_assert!(!self.cur_node.is_never());
self.cur_node.never_swap(&mut <CONF::Ptr as NodesPtr<L>>::make_mut(&mut nodes)[idx]);
let parent = Node::from_children(nodes); // gather info
self.cur_node = parent;
}
fn descend_raw(&mut self, mut nodes: CONF::Ptr, idx: usize, path_info: PI) {
debug_assert!(self.cur_node.is_never());
self.cur_node.never_swap(&mut <CONF::Ptr as NodesPtr<L>>::make_mut(&mut nodes)[idx]);
self.push_step(CMutStep::new(nodes, idx, path_info));
}
fn push_step(&mut self, cstep: CMutStep<L, PI, CONF>) {
//testln!("descended!");
let _res = self.steps.push(cstep);
assert!(_res.is_none(), "Exceeded maximum supported depth.");
}
fn pop_step(&mut self) -> Option<CMutStep<L, PI, CONF>> {
//testln!("ascended! (try)");
self.steps.pop()
}
fn take_current(&mut self) -> Option<Node<L, CONF::Ptr>> {
match self.cur_node {
Node::Never(_) => None,
ref mut cur_node => Some(cur_node.never_take()),
}
}
}
impl<L, PI, CONF> FromIterator<L> for CursorMut<L, PI, CONF>
where L: Leaf,
PI: PathInfo<L::Info>,
CONF: CMutConf<L, PI>,
{
fn from_iter<J: IntoIterator<Item=L>>(iter: J) -> Self {
let mut curs = CursorMut::new();
curs.extend(iter);
curs
}
}
impl<L, PI, CONF> Extend<L> for CursorMut<L, PI, CONF>
where L: Leaf,
PI: PathInfo<L::Info>,
CONF: CMutConf<L, PI>,
{
fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item=L>
{
self.reset();
let mut iter = iter.into_iter().map(Node::from_leaf);
loop {
let nodes = iter.by_ref()
.take(<CONF::Ptr as NodesPtr<L>>::max_size())
.collect::<ArrayVec<<CONF::Ptr as NodesPtr<L>>::Array>>();
if nodes.len() > 0 {
self.insert(Node::from_children(<CONF::Ptr as NodesPtr<L>>::new(nodes)), true);
} else {
break;
}
}
}
}
#[cfg(test)]
mod tests {
use test_help::*;
type CursorMut<L, PI> = super::CursorMut<L, PI>;
#[test]
fn insert() {
let mut cursor_mut = CursorMutT::new();
for i in 0..128 {
cursor_mut.insert_leaf(ListLeaf(i), true);
}
let root = cursor_mut.into_root().unwrap();
let mut leaf_iter = CursorT::new(&root).into_iter();
for i in 0..128 {
assert_eq!(leaf_iter.next(), Some(&ListLeaf(i)));
}
assert_eq!(leaf_iter.next(), None);
}
#[test]
fn delete() {
let mut cursor_mut = CursorMutT::new();
for i in 0..128 {
cursor_mut.insert_leaf(ListLeaf(i), true);
}
cursor_mut.reset();
for i in 0..128 {
assert_eq!(cursor_mut.remove_leaf(), Some(ListLeaf(i)));
}
assert_eq!(cursor_mut.is_empty(), true);
}
#[test]
fn from_iter() {
let cursor_mut: CursorMutT<_> = (0..128).map(|i| ListLeaf(i)).collect();
let root = cursor_mut.into_root().unwrap();
let mut leaf_iter = CursorT::new(&root).into_iter();
for i in 0..128 {
assert_eq!(leaf_iter.next(), Some(&ListLeaf(i)));
}
assert_eq!(leaf_iter.next(), None);
}
#[test]
fn root_balance() {
let mut cursor_mut: CursorMutT<_> = (0..2).map(|i| ListLeaf(i)).collect();
cursor_mut.remove_leaf();
cursor_mut.reset();
assert_eq!(cursor_mut.height(), Some(1)); // allow root with single leaf child
let mut cursor_mut: CursorMutT<_> = (0..17).map(|i| ListLeaf(i)).collect();
cursor_mut.reset();
assert_eq!(cursor_mut.height(), Some(2));
cursor_mut.descend_first();
cursor_mut.remove_node(); // now root has only one child
cursor_mut.reset();
assert_eq!(cursor_mut.height(), Some(2));
cursor_mut.remove_leaf();
cursor_mut.remove_leaf();
cursor_mut.reset();
assert_eq!(cursor_mut.height(), Some(1));
}
#[test]
fn node_iter() {
let mut cursor_mut: CursorMutT<_> = (0..128).map(|i| ListLeaf(i)).collect();
cursor_mut.reset();
assert_eq!(cursor_mut.first_leaf(), Some(&ListLeaf(0)));
for i in 1..128 {
assert_eq!(cursor_mut.next_node().and_then(|n| n.leaf()), Some(&ListLeaf(i)));
}
assert_eq!(cursor_mut.next_node().and_then(|n| n.leaf()), None);
}
#[test]
fn find_min_max() {
let rand = || rand_usize(256) + 4;
let (l1, l2, l3) = (rand(), rand(), rand());
println!("lengths: {:?}", (l1, l2, l3));
let mut cursor_mut: CursorMutT<_> = (0..l1).map(|i| SetLeaf('b', i))
.chain((0..l2).map(|i| SetLeaf('c', i)))
.chain((0..l3).map(|i| SetLeaf('d', i)))
.collect();
assert_eq!(cursor_mut.find_min(MinChar('a')), Some(&SetLeaf('b', 0)));
assert_eq!(cursor_mut.find_min(MinChar('b')), Some(&SetLeaf('b', 0)));
assert_eq!(cursor_mut.find_min(MinChar('c')), Some(&SetLeaf('c', 0)));
assert_eq!(cursor_mut.find_min(MinChar('d')), Some(&SetLeaf('d', 0)));
assert_eq!(cursor_mut.find_min(MinChar('e')), None);
assert_eq!(cursor_mut.find_max(MaxChar('a')), None);
assert_eq!(cursor_mut.find_max(MaxChar('b')), Some(&SetLeaf('b', l1-1)));
assert_eq!(cursor_mut.find_max(MaxChar('c')), Some(&SetLeaf('c', l2-1)));
assert_eq!(cursor_mut.find_max(MaxChar('d')), Some(&SetLeaf('d', l3-1)));
assert_eq!(cursor_mut.find_max(MaxChar('e')), Some(&SetLeaf('d', l3-1)));
let leaf = SetLeaf('b', rand_usize(8));
assert_eq!(cursor_mut.find_min(MinLeaf(leaf)), Some(&leaf));
assert_eq!(cursor_mut.find_max(MaxLeaf(leaf)), Some(&leaf));
}
#[test]
fn goto_min_max() {
let mut cursor_mut: CursorMut<_, ListPath> = (0..128).map(|i| ListLeaf(i)).collect();
assert_eq!(cursor_mut.goto_min(ListIndex(50)), Some(&ListLeaf(50)));
assert_eq!(cursor_mut.goto_min(ListRun(79*80/2)), Some(&ListLeaf(80)));
cursor_mut.reset();
assert_eq!(cursor_mut.goto_max(ListIndex(50)), Some(&ListLeaf(49)));
assert_eq!(cursor_mut.goto_max(ListRun(79*80/2)), Some(&ListLeaf(79)));
let mut cursor_mut: CursorMut<_, ListPath> = vec![2, 1, 0, 0, 0, 3, 4].into_iter()
.map(|i| ListLeaf(i)).collect();
assert_eq!(cursor_mut.goto_min(ListRun(3)), Some(&ListLeaf(0)));
assert_eq!(cursor_mut.prev_leaf(), Some(&ListLeaf(1)));
assert_eq!(cursor_mut.goto_max(ListRun(3)), Some(&ListLeaf(0)));
assert_eq!(cursor_mut.next_leaf(), Some(&ListLeaf(3)));
}
#[test]
fn split_off() {
let total = rand_usize(2048) + 1;
let split_at = rand_usize(total);
println!("total: {}, split_at: {}", total, split_at);
let mut cursor_mut: CursorMutT<_> = (0..total).map(|i| SetLeaf('a', i)).collect();
cursor_mut.reset();
let orig_ht = cursor_mut.height().unwrap();
cursor_mut.find_min(MinLeaf(SetLeaf('a', split_at))).unwrap();
let right = cursor_mut.split_off().unwrap();
let mut leaf_iter = CursorT::new(&right).into_iter();
for i in split_at..total {
assert_eq!(leaf_iter.next(), Some(&SetLeaf('a', i)));
}
assert!(orig_ht >= right.height());
let maybe_left = cursor_mut.into_root();
if split_at > 0 {
let left = maybe_left.unwrap();
let mut leaf_iter = CursorT::new(&left).into_iter();
for i in 0..split_at {
assert_eq!(leaf_iter.next(), Some(&SetLeaf('a', i)));
}
assert!(orig_ht >= left.height());
} else {
assert!(maybe_left.is_none());
}
}
#[test]
fn general_insert() {
let rand = || rand_usize(256) + 4;
let (l1, l2, l3) = (rand(), rand(), rand());
println!("lengths: {:?}", (l1, l2, l3));
let mut cursor_mut: CursorMutT<_> = (0..l1).map(|i| SetLeaf('a', i))
.chain((0..l3).map(|i| SetLeaf('a', l1 + l2 + i)))
.collect();
cursor_mut.reset();
cursor_mut.find_min(MinLeaf(SetLeaf('a', l1))).unwrap();
let node: NodeRc<_> = (0..l2).map(|i| SetLeaf('a', l1 + i)).collect();
cursor_mut.insert(node, false);
cursor_mut.reset();
let mut leaf_iter = CursorT::new(cursor_mut.current().unwrap()).into_iter();
for i in 0..l1+l2+l3 {
assert_eq!(leaf_iter.next(), Some(&SetLeaf('a', i)));
}
}
// FIXME need more tests (create verify_balanced function?)
}
|
use clap::ArgMatches;
pub const DEFAULT_BULK_SIZE: usize = 100;
pub const DEFAULT_CHANNEL_SIZE: usize = 100;
pub const DEFAULT_DELIMITER: u8 = b',';
use super::channel::Channel;
use super::csv::OptionsCsv;
#[derive(Debug, Clone)]
pub struct Options {
pub channel: Channel,
pub csv: OptionsCsv,
pub manifest: Option<String>,
pub cache: bool,
pub sync_io: bool,
pub bulk_size: usize
}
impl<'a> From<&'a ArgMatches<'a>> for Options {
fn from(matches: &ArgMatches) -> Options {
debug!("Parsing options");
Options {
channel: Channel {
size: matches.value_of("channel-size")
.unwrap()
.to_string()
.parse::<usize>()
.unwrap_or(DEFAULT_CHANNEL_SIZE),
},
csv: OptionsCsv {
delimiter: match matches.value_of("delimiter") {
Some(val) => val.to_string().bytes().nth(0).unwrap_or(DEFAULT_DELIMITER),
_ => DEFAULT_DELIMITER
},
has_header: matches.is_present("has-header"),
flexible: matches.is_present("flexible"),
},
manifest: match matches.value_of("manifest") {
Some(val) => Some(val.to_string()),
_ => None
},
cache: matches.is_present("cache"),
sync_io: matches.is_present("sync-io"),
bulk_size: matches.value_of("bulk-size")
.unwrap()
.to_string()
.parse::<usize>()
.unwrap_or(DEFAULT_BULK_SIZE),
}
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 core::u64;
use super::super::kernel::futex::*;
use super::super::memmgr::mm::*;
use super::super::memmgr::vma::*;
use super::super::task::*;
use super::super::qlib::common::*;
use super::super::qlib::linux_def::*;
use super::super::qlib::addr::*;
use super::super::qlib::range::*;
use super::super::qlib::linux::limits::*;
use super::*;
#[derive(Debug)]
pub struct MSyncOpts {
// Sync has the semantics of MS_SYNC.
pub Sync: bool,
// Invalidate has the semantics of MS_INVALIDATE.
pub Invalidate: bool,
}
impl MemoryManager {
// MMap establishes a memory mapping.
pub fn MMap(&self, task: &Task, opts: &mut MMapOpts) -> Result<u64> {
let ml = self.MappingLock();
let _ml = ml.write();
if opts.Length == 0 {
return Err(Error::SysError(SysErr::EINVAL));
}
let length = match Addr(opts.Length).RoundUp() {
Err(_) => return Err(Error::SysError(SysErr::ENOMEM)),
Ok(l) => l.0,
};
opts.Length = length;
if opts.Mappable.is_some() {
// Offset must be aligned.
if Addr(opts.Offset).RoundDown()?.0 != opts.Offset {
return Err(Error::SysError(SysErr::EINVAL));
}
// Offset + length must not overflow.
if u64::MAX - opts.Length < opts.Offset {
return Err(Error::SysError(SysErr::ENOMEM));
}
} else if !opts.VDSO { //not vdso
opts.Offset = 0;
}
if Addr(opts.Addr).RoundDown()?.0 != opts.Addr {
// MAP_FIXED requires addr to be page-aligned; non-fixed mappings
// don't.
if opts.Fixed {
return Err(Error::SysError(SysErr::EINVAL));
}
opts.Addr = Addr(opts.Addr).RoundDown()?.0;
}
if !opts.MaxPerms.SupersetOf(&opts.Perms) {
return Err(Error::SysError(SysErr::EACCES));
}
if opts.Unmap && !opts.Fixed {
return Err(Error::SysError(SysErr::EINVAL));
}
if opts.GrowsDown && opts.Mappable.is_some() {
return Err(Error::SysError(SysErr::EINVAL));
}
let (vseg, ar) = self.CreateVMAlocked(task, opts)?;
self.PopulateVMALocked(task, &vseg, &ar, opts.Precommit, opts.VDSO)?;
return Ok(ar.Start());
}
// MapStack allocates the initial process stack.
pub fn MapStack(&self, task: &Task) -> Result<Range> {
let ml = self.MappingLock();
let _ml = ml.write();
// maxStackSize is the maximum supported process stack size in bytes.
//
// This limit exists because stack growing isn't implemented, so the entire
// process stack must be mapped up-front.
const MAX_STACK_SIZE: u64 = 128 << 20; //128 MB
let sz = DEFAULT_STACK_SOFT_LIMIT;
//todo: add random
// stackEnd := mm.layout.MaxAddr - usermem.Addr(mrand.Int63n(int64(mm.layout.MaxStackRand))).RoundDown()
let stackEnd = self.layout.lock().MaxAddr;
if stackEnd < sz {
return Err(Error::SysError(SysErr::ENOMEM));
}
let stackStart = stackEnd - sz;
let (vseg, ar) = self.CreateVMAlocked(task, &MMapOpts {
Length: sz,
Addr: stackStart,
Offset: 0,
Fixed: true,
Unmap: false,
Map32Bit: false,
Perms: AccessType::ReadWrite(),
MaxPerms: AccessType::AnyAccess(),
Private: true,
VDSO: false,
GrowsDown: true,
Precommit: false,
MLockMode: MLockMode::default(),
Kernel: false,
Mapping: None,
Mappable: None,
Hint: "[stack]".to_string(),
})?;
self.PopulateVMALocked(task, &vseg, &ar, false, false)?;
return Ok(ar)
}
// MUnmap implements the semantics of Linux's munmap(2).
pub fn MUnmap(&self, _task: &Task, addr: u64, length: u64) -> Result<()> {
let ml = self.MappingLock();
let _ml = ml.write();
if addr != Addr(addr).RoundDown()?.0 {
return Err(Error::SysError(SysErr::EINVAL));
}
if length == 0 {
//|| length != Addr(length).RoundDown()?.0 {
return Err(Error::SysError(SysErr::EINVAL));
}
let length = Addr(length).RoundUp()?.0;
let ar = Addr(addr).ToRange(length)?;
return self.RemoveVMAsLocked(&ar);
}
// MRemap implements the semantics of Linux's mremap(2).
pub fn MRemap(&self, task: &Task, oldAddr: u64, oldSize: u64, newSize: u64, opts: &MRemapOpts) -> Result<u64> {
let ml = self.MappingLock();
let _ml = ml.write();
// "Note that old_address has to be page aligned." - mremap(2)
if oldAddr != Addr(oldAddr).RoundDown()?.0 {
return Err(Error::SysError(SysErr::EINVAL));
}
// Linux treats an old_size that rounds up to 0 as 0, which is otherwise a
// valid size. However, new_size can't be 0 after rounding.
let oldSize = Addr(oldSize).RoundUp()?.0;
let newSize = Addr(newSize).RoundUp()?.0;
if newSize == 0 {
return Err(Error::SysError(SysErr::EINVAL));
}
let mut oldEnd = Addr(oldAddr).AddLen(oldSize)?.0;
// All cases require that a vma exists at oldAddr.
let mut vseg = self.mapping.lock().vmas.FindSeg(oldAddr);
if !vseg.Ok() {
return Err(Error::SysError(SysErr::EFAULT));
}
// Behavior matrix:
//
// Move | oldSize = 0 | oldSize < newSize | oldSize = newSize | oldSize > newSize
// ---------+-------------+-------------------+-------------------+------------------
// NoMove | ENOMEM [1] | Grow in-place | No-op | Shrink in-place
// MayMove | Copy [1] | Grow in-place or | No-op | Shrink in-place
// | | move | |
// MustMove | Copy | Move and grow | Move | Shrink and move
//
// [1] In-place growth is impossible because the vma at oldAddr already
// occupies at least part of the destination. Thus the NoMove case always
// fails and the MayMove case always falls back to copying.
if opts.Move != MREMAP_MUST_MOVE {
// Handle no-ops and in-place shrinking. These cases don't care if
// [oldAddr, oldEnd) maps to a single vma, or is even mapped at all
// (aside from oldAddr).
if newSize <= oldSize {
if newSize < oldSize {
// If oldAddr+oldSize didn't overflow, oldAddr+newSize can't
// either.
let newEnd = oldAddr + newSize;
self.RemoveVMAsLocked(&Range::New(newEnd, oldSize - newSize))?;
}
return Ok(oldAddr)
}
// Handle in-place growing.
// Check that oldEnd maps to the same vma as oldAddr.
if vseg.Range().End() < oldEnd {
return Err(Error::SysError(SysErr::EFAULT));
}
// "Grow" the existing vma by creating a new mergeable one.
let vma = vseg.Value();
let mut newOffset = 0;
if vma.mappable.is_some() {
newOffset = vseg.MappableRange().End();
}
match self.CreateVMAlocked(task, &MMapOpts {
Length: newSize - oldSize,
Addr: oldEnd,
Offset: newOffset,
Fixed: true,
Unmap: false,
Map32Bit: false,
Perms: vma.realPerms,
MaxPerms: vma.maxPerms,
Private: vma.private,
VDSO: false,
GrowsDown: vma.growsDown,
Precommit: false,
MLockMode: MLockMode::default(),
Kernel: false,
Mapping: vma.id.clone(),
Mappable: vma.mappable.clone(),
Hint: vma.hint.to_string(),
}) {
Ok((vseg, ar)) => {
self.PopulateVMALocked(task, &vseg, &ar, false, false)?;//to true?
return Ok(oldAddr);
}
Err(e) => {
// In-place growth failed. In the MRemapMayMove case, fall through to
// copying/moving below.
if opts.Move == MREMAP_NO_MOVE {
return Err(e)
}
}
}
}
// Find a location for the new mapping.
let newAR;
match opts.Move {
MREMAP_MAY_MOVE => {
let newAddr = self.FindAvailableLocked(newSize, &mut FindAvailableOpts::default())?;
newAR = Range::New(newAddr, newSize);
}
MREMAP_MUST_MOVE => {
let newAddr = opts.NewAddr;
if Addr(newAddr).RoundDown()?.0 != newAddr {
return Err(Error::SysError(SysErr::EINVAL));
}
match Addr(newAddr).ToRange(newSize) {
Err(_) => return Err(Error::SysError(SysErr::EINVAL)),
Ok(r) => newAR = r,
}
if Range::New(oldAddr, oldEnd - oldAddr).Overlaps(&newAR) {
return Err(Error::SysError(SysErr::EINVAL));
}
// Unmap any mappings at the destination.
self.RemoveVMAsLocked(&newAR)?;
// If the sizes specify shrinking, unmap everything between the new and
// old sizes at the source. Unmapping before the following checks is
// correct: compare Linux's mm/mremap.c:mremap_to() => do_munmap(),
// vma_to_resize().
if newSize < oldSize {
let oldNewEnd = oldAddr + newSize;
self.RemoveVMAsLocked(&Range::New(oldNewEnd, oldEnd - oldNewEnd))?;
oldEnd = oldNewEnd;
}
// unmapLocked may have invalidated vseg; look it up again.
vseg = self.mapping.lock().vmas.FindSeg(oldAddr);
}
_ => {
//unreachable
panic!("impossible to reach...");
}
}
let oldAR = Range::New(oldAddr, oldEnd - oldAddr);
// Check that oldEnd maps to the same vma as oldAddr.
if vseg.Range().End() < oldEnd {
return Err(Error::SysError(SysErr::EFAULT));
}
let vma = vseg.Value();
if vma.mappable.is_some() {
if core::u64::MAX - vma.offset < newAR.Len() {
return Err(Error::SysError(SysErr::EINVAL));
}
// Inform the Mappable, if any, of the new mapping.
let mappable = vma.mappable.clone().unwrap();
let offsetat = vseg.MappableOffsetAt(oldAR.Start());
mappable.CopyMapping(self, &oldAR, &newAR, offsetat, vma.CanWriteMappableLocked())?;
}
if oldSize == 0 {
// Handle copying.
//
// We can't use createVMALocked because it calls Mappable.AddMapping,
// whereas we've already called Mappable.CopyMapping (which is
// consistent with Linux). Call vseg.Value() (rather than
// vseg.ValuePtr()) to make a copy of the vma.
let mut vma = vseg.Value();
if vma.mappable.is_some() {
vma.offset = vseg.MappableOffsetAt(oldAR.Start());
}
let gap = self.mapping.lock().vmas.FindGap(newAR.Start());
let vseg = self.mapping.lock().vmas.Insert(&gap, &newAR, vma);
self.mapping.lock().usageAS += newAR.Len();
self.PopulateVMALocked(task, &vseg, &newAR, false, false)?;
return Ok(newAR.Start())
}
// Handle moving.
//
// Remove the existing vma before inserting the new one to minimize
// iterator invalidation. We do this directly (instead of calling
// removeVMAsLocked) because:
//
// 1. We can't drop the reference on vma.id, which will be transferred to
// the new vma.
//
// 2. We can't call vma.mappable.RemoveMapping, because pmas are still at
// oldAR, so calling RemoveMapping could cause us to miss an invalidation
// overlapping oldAR.
//
// Call vseg.Value() (rather than vseg.ValuePtr()) to make a copy of the
// vma.
let vseg = self.mapping.lock().vmas.Isolate(&vseg, &oldAR);
let vma = vseg.Value();
self.mapping.lock().vmas.Remove(&vseg);
let gap = self.mapping.lock().vmas.FindGap(newAR.Start());
let vseg = self.mapping.lock().vmas.Insert(&gap, &newAR, vma.clone());
let usageAS = self.mapping.lock().usageAS;
self.mapping.lock().usageAS = usageAS - oldAR.Len() + newAR.Len();
// Now that pmas have been moved to newAR, we can notify vma.mappable that
// oldAR is no longer mapped.
if vma.mappable.is_some() {
let mappable = vma.mappable.clone().unwrap();
mappable.RemoveMapping(self, &oldAR, vma.offset, vma.CanWriteMappableLocked())?;
}
self.PopulateVMARemapLocked(task, &vseg, &newAR, &Range::New(oldAddr, oldSize), true)?;
return Ok(newAR.Start())
}
pub fn MProtect(&self, addr: u64, len: u64, realPerms: &AccessType, growsDown: bool) -> Result<()> {
let ml = self.MappingLock();
let _ml = ml.write();
if Addr(addr).RoundDown()?.0 != addr {
return Err(Error::SysError(SysErr::EINVAL));
}
if len == 0 {
return Ok(())
}
let rlen = match Addr(len).RoundUp() {
Err(_) => return Err(Error::SysError(SysErr::ENOMEM)),
Ok(l) => l.0,
};
let mut ar = Addr(addr).ToRange(rlen)?;
let effectivePerms = realPerms.Effective();
// Non-growsDown mprotect requires that all of ar is mapped, and stops at
// the first non-empty gap. growsDown mprotect requires that the first vma
// be growsDown, but does not require it to extend all the way to ar.Start;
// vmas after the first must be contiguous but need not be growsDown, like
// the non-growsDown case.
let mut mapping = self.mapping.lock();
let vseg = mapping.vmas.LowerBoundSeg(ar.Start());
if !vseg.Ok() {
return Err(Error::SysError(SysErr::ENOMEM));
}
if growsDown {
if !vseg.Value().growsDown {
return Err(Error::SysError(SysErr::EINVAL));
}
if ar.End() <= vseg.Range().Start() {
return Err(Error::SysError(SysErr::ENOMEM));
}
ar.start = vseg.Range().Start();
} else {
if ar.Start() < vseg.Range().Start() {
return Err(Error::SysError(SysErr::ENOMEM));
}
}
let mut vseg = vseg;
loop {
let vma = vseg.Value();
// Check for permission validity before splitting vmas, for consistency
// with Linux.
if !vma.maxPerms.SupersetOf(&effectivePerms) {
return Err(Error::SysError(SysErr::EACCES));
}
//error!("MProtect: vseg range is {:x?}, vma.mappable.is_some() is {}", vseg.Range(), vma.mappable.is_some());
vseg = mapping.vmas.Isolate(&vseg, &ar);
// Update vma permissions.
let mut vma = vseg.Value();
vma.realPerms = *realPerms;
vma.effectivePerms = effectivePerms;
vseg.SetValue(vma);
let range = vseg.Range();
let pageopts = if effectivePerms.Write() {
PageOpts::UserReadWrite().Val()
} else if effectivePerms.Read() || effectivePerms.Exec() {
PageOpts::UserReadOnly().Val()
} else {
PageOpts::UserNonAccessable().Val()
};
//change pagetable permission
let mut end = range.End();
if ar.End() < end {
end = ar.End();
}
self.pagetable.write().pt.MProtect(Addr(range.Start()), Addr(end), pageopts, false)?;
if ar.End() <= range.End() {
break;
}
let (segtmp, _) = vseg.NextNonEmpty();
vseg = segtmp;
if !vseg.Ok() {
return Err(Error::SysError(SysErr::ENOMEM));
}
}
mapping.vmas.MergeRange(&ar);
mapping.vmas.MergeAdjacent(&ar);
return Ok(())
}
pub fn NumaPolicy(&self, addr: u64) -> Result<(i32, u64)> {
let ml = self.MappingLock();
let _ml = ml.write();
return self.NumaPolicyLocked(addr);
}
pub fn NumaPolicyLocked(&self, addr: u64) -> Result<(i32, u64)> {
let vseg = self.mapping.lock().vmas.FindSeg(addr);
if !vseg.Ok() {
return Err(Error::SysError(SysErr::EFAULT));
}
let vma = vseg.Value();
return Ok((vma.numaPolicy, vma.numaNodemask))
}
pub fn SetNumaPolicy(&self, addr: u64, len: u64, policy: i32, nodemask: u64) -> Result<()> {
let ml = self.MappingLock();
let _ml = ml.write();
if !Addr(addr).IsPageAligned() {
return Err(Error::SysError(SysErr::EINVAL))
}
// Linux allows this to overflow.
let la = Addr(len).RoundUp()?.0;
let ar = Range::New(addr, la);
if ar.Len() == 0 {
return Ok(())
}
let mut mapping = self.mapping.lock();
let mut vseg = mapping.vmas.LowerBoundSeg(ar.Start());
let mut lastEnd = ar.Start();
loop {
if !vseg.Ok() || lastEnd < vseg.Range().Start() {
// "EFAULT: ... there was an unmapped hole in the specified memory
// range specified [sic] by addr and len." - mbind(2)
return Err(Error::SysError(SysErr::EFAULT))
}
vseg = mapping.vmas.Isolate(&vseg, &ar);
let mut vma = vseg.Value();
vma.numaPolicy = policy;
vma.numaNodemask = nodemask;
vseg.SetValue(vma);
lastEnd = vseg.Range().End();
if ar.End() <= lastEnd {
mapping.vmas.MergeRange(&ar);
mapping.vmas.MergeAdjacent(&ar);
return Ok(())
}
let (tmpVseg, _) = vseg.NextNonEmpty();
vseg = tmpVseg;
}
}
// BrkSetup sets mm's brk address to addr and its brk size to 0.
pub fn BrkSetupLocked(&self, addr: u64) {
let mut mapping = self.mapping.lock();
if mapping.brkInfo.brkStart != mapping.brkInfo.brkEnd {
panic!("BrkSetup get nonempty brk");
}
mapping.brkInfo.brkStart = addr;
mapping.brkInfo.brkEnd = addr;
mapping.brkInfo.brkMemEnd = addr;
}
// Brk implements the semantics of Linux's brk(2), except that it returns an
// error on failure.
pub fn Brk(&self, task: &Task, addr: u64) -> Result<u64> {
let ml = self.MappingLock();
let _ml = ml.write();
if addr == 0 || addr == -1 as i64 as u64 {
return Ok(self.mapping.lock().brkInfo.brkEnd);
}
if addr < self.mapping.lock().brkInfo.brkStart {
return Err(Error::SysError(SysErr::EINVAL));
}
let oldbrkpg = Addr(self.mapping.lock().brkInfo.brkEnd).RoundUp()?.0;
let newbrkpg = match Addr(addr).RoundUp() {
Err(_e) => return Err(Error::SysError(SysErr::EFAULT)),
Ok(v) => v.0,
};
if oldbrkpg < newbrkpg {
let (vseg, ar) = self.CreateVMAlocked(task, &MMapOpts {
Length: newbrkpg - oldbrkpg,
Addr: oldbrkpg,
Offset: 0,
Fixed: true,
Unmap: false,
Map32Bit: false,
Perms: AccessType::ReadWrite(),
MaxPerms: AccessType::AnyAccess(),
Private: true,
VDSO: false,
GrowsDown: false,
Precommit: false,
MLockMode: MLockMode::default(),
Kernel: false,
Mapping: None,
Mappable: None,
Hint: "[Heap]".to_string(),
})?;
self.PopulateVMALocked(task, &vseg, &ar, false, false)?;
self.mapping.lock().brkInfo.brkEnd = addr;
} else {
if newbrkpg < oldbrkpg {
self.RemoveVMAsLocked(&Range::New(newbrkpg, oldbrkpg - newbrkpg))?;
}
self.mapping.lock().brkInfo.brkEnd = addr;
}
return Ok(addr);
}
pub fn GetSharedFutexKey(&self, _task: &Task, addr: u64) -> Result<Key> {
let ml = self.MappingLock();
let _ml = ml.read();
let ar = match Addr(addr).ToRange(4) {
Ok(r) => r,
Err(_) => return Err(Error::SysError(SysErr::EFAULT)),
};
let (vseg, _, err) = self.GetVMAsLocked(&ar, &AccessType::ReadOnly(), false);
match err {
Ok(()) => (),
Err(e) => return Err(e),
}
let vma = vseg.Value();
if vma.private {
return Ok(Key {
Kind: KeyKind::KindSharedPrivate,
Addr: addr,
})
}
let (phyAddr, _) = self.VirtualToPhyLocked(addr)?;
return Ok(Key {
Kind: KeyKind::KindSharedMappable,
Addr: phyAddr,
})
}
pub fn MAdvise(&self, _task: &Task, addr: u64, length: u64, advise: i32) -> Result<()> {
let ar = match Addr(addr).ToRange(length) {
Err(_) => return Err(Error::SysError(SysErr::EINVAL)),
Ok(r) => r
};
let ml = self.MappingLock();
let _ml = ml.read();
let mapping = self.mapping.lock();
let mut vseg = mapping.vmas.LowerBoundSeg(ar.Start());
while vseg.Ok() && vseg.Range().Start() < ar.End() {
let vma = vseg.Value();
if vma.mlockMode != MLockMode::MlockNone && advise == MAdviseOp::MADV_DONTNEED {
return Err(Error::SysError(SysErr::EINVAL))
}
let mr = ar.Intersect(&vseg.Range());
self.pagetable.write().pt.MUnmap(mr.Start(), mr.Len())?;
if let Some(iops) = vma.mappable.clone() {
let fstart = mr.Start() - vseg.Range().Start() + vma.offset;
// todo: fix the Madvise/MADV_DONTNEED, when there are multiple process MAdviseOp::MADV_DONTNEED
// with current implementation, the first Madvise/MADV_DONTNEED will work.
iops.MAdvise(fstart, mr.Len(), advise)?;
}
vseg = vseg.NextSeg();
}
return Ok(())
}
pub fn SetDontFork(&self, _task: &Task, addr: u64, length: u64, dontfork: bool) -> Result<()> {
let ar = match Addr(addr).ToRange(length) {
Err(_) => return Err(Error::SysError(SysErr::EINVAL)),
Ok(r) => r
};
let ml = self.MappingLock();
let _ml = ml.write();
let mut mapping = self.mapping.lock();
let mut vseg = mapping.vmas.LowerBoundSeg(ar.Start());
while vseg.Ok() && vseg.Range().Start() < ar.End() {
vseg = mapping.vmas.Isolate(&vseg, &ar);
let mut vma = vseg.Value();
vma.dontfork = dontfork;
vseg.SetValue(vma);
vseg = vseg.NextSeg();
}
mapping.vmas.MergeRange(&ar);
mapping.vmas.MergeAdjacent(&ar);
if mapping.vmas.SpanRange(&ar) != ar.Len() {
return Err(Error::SysError(SysErr::ENOMEM))
}
return Ok(())
}
pub fn VirtualMemorySizeRangeLocked(&self, ar: &Range) -> u64 {
return self.mapping.lock().vmas.SpanRange(&ar);
}
pub fn VirtualMemorySizeRange(&self, ar: &Range) -> u64 {
let ml = self.MappingLock();
let _ml = ml.read();
return self.VirtualMemorySizeRangeLocked(ar);
}
pub fn VirtualMemorySizeLocked(&self) -> u64 {
return self.mapping.lock().usageAS;
}
pub fn VirtualMemorySize(&self) -> u64 {
let ml = self.MappingLock();
let _ml = ml.read();
return self.VirtualMemorySizeLocked();
}
pub fn ResidentSetSizeLocked(&self) -> u64 {
return self.pagetable.read().curRSS;
}
pub fn ResidentSetSize(&self) -> u64 {
let ml = self.MappingLock();
let _ml = ml.read();
return self.ResidentSetSize();
}
pub fn MaxResidentSetSizeLocked(&self) -> u64 {
return self.pagetable.read().maxRSS;
}
pub fn MaxResidentSetSize(&self) -> u64 {
let ml = self.MappingLock();
let _ml = ml.read();
return self.MaxResidentSetSizeLocked();
}
}
// MRemapOpts specifies options to MRemap.
#[derive(Debug)]
pub struct MRemapOpts {
// Move controls whether MRemap moves the remapped mapping to a new address.
pub Move: MRemapMoveMode,
// NewAddr is the new address for the remapping. NewAddr is ignored unless
// Move is MMRemapMustMove.
pub NewAddr: u64,
}
pub type MRemapMoveMode = i32;
// MRemapNoMove prevents MRemap from moving the remapped mapping.
pub const MREMAP_NO_MOVE: MRemapMoveMode = 0;
// MRemapMayMove allows MRemap to move the remapped mapping.
pub const MREMAP_MAY_MOVE: MRemapMoveMode = 1;
// MRemapMustMove requires MRemap to move the remapped mapping to
// MRemapOpts.NewAddr, replacing any existing mappings in the remapped
// range.
pub const MREMAP_MUST_MOVE: MRemapMoveMode = 2; |
use gl::types::*;
use anyhow::Result;
use super::{ShaderExt, Shader};
pub type VertexShader = Shader<Vertex>;
pub struct Vertex {}
impl ShaderExt for Vertex {
fn new() -> Vertex {
Vertex{}
}
fn ty() -> GLenum {
gl::VERTEX_SHADER
}
fn name() -> &'static str {
"vertex"
}
}
impl VertexShader {
pub fn from_source(source: &str) -> Result<VertexShader> {
let mut shader = VertexShader::new();
shader.set_source(source);
shader.compile()?;
Ok(shader)
}
} |
use anyhow::{anyhow, Error};
use inkwell::values::PointerValue;
use serde_json::Value;
use std::{collections::HashMap, rc::Rc};
pub struct Env<'ctx> {
pub names: HashMap<String, u64>,
pub parent: Option<Rc<Env<'ctx>>>,
pub ptr: Option<Rc<PointerValue<'ctx>>>,
counter: u64,
}
impl<'ctx> Env<'ctx> {
pub fn new(parent: Option<Rc<Env<'ctx>>>) -> Self {
Env {
names: HashMap::new(),
parent,
ptr: None,
counter: 0,
}
}
pub fn add_name(&mut self, name: String) {
self.counter += 1;
self.names.insert(name, self.counter);
}
pub fn lookup(&self, name: &str) -> Result<(usize, u64), Error> {
if let Some(&offset) = self.names.get(name) {
return Ok((0, offset));
}
let mut jumps = 1;
let mut frame = self.parent.clone().unwrap();
loop {
if let Some(&offset) = frame.names.get(name) {
break Ok((jumps, offset));
} else if let Some(parent) = frame.parent.clone() {
frame = parent;
jumps += 1;
} else {
break Err(anyhow!(format!("Cannot find name {}", name)));
}
}
}
pub fn add_and_count_decls(&mut self, body: &[Value]) -> Result<u64, Error> {
let mut count = 0;
body.iter().for_each(
|es_node| match es_node.get("type").unwrap().as_str().unwrap() {
"VariableDeclaration" => {
count += 1;
let name = es_node
.get("declarations")
.unwrap()
.as_array()
.unwrap()
.get(0)
.unwrap()
.get("id")
.unwrap()
.get("name")
.unwrap()
.as_str()
.unwrap();
self.add_name(name.into());
}
"FunctionDeclaration" => {
count += 1;
let name = es_node
.get("id")
.unwrap()
.get("name")
.unwrap()
.as_str()
.unwrap();
self.add_name(name.into());
}
_ => {}
},
);
Ok(count)
}
}
|
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
use js_sys::*;
#[wasm_bindgen_test]
fn test() {
let bytes = Int8Array::new(&JsValue::from(10));
// TODO: figure out how to do `bytes[2] = 2`
bytes.subarray(2, 3).fill(2, 0, 1);
let v = DataView::new(&bytes.buffer(), 2, 8);
assert_eq!(v.byte_offset(), 2);
assert_eq!(v.byte_length(), 8);
assert_eq!(v.get_int8(0), 2);
assert_eq!(v.get_uint8(0), 2);
v.set_int8(0, 42);
assert_eq!(v.get_int8(0), 42);
v.set_uint8(0, 255);
assert_eq!(v.get_uint8(0), 255);
v.set_int16(0, 32767);
assert_eq!(v.get_int16(0), 32767);
v.set_uint16(0, 65535);
assert_eq!(v.get_uint16(0), 65535);
v.set_int32(0, 123456789);
assert_eq!(v.get_int32(0), 123456789);
v.set_uint32(0, 3_123_456_789);
assert_eq!(v.get_uint32(0), 3_123_456_789);
v.set_float32(0, 100.123);
assert_eq!(v.get_float32(0), 100.123);
v.set_float64(0, 123456789.123456);
assert_eq!(v.get_float64(0), 123456789.123456);
v.set_int8(0, 42);
// TODO: figure out how to do `bytes[2]`
bytes.subarray(2, 3).for_each(&mut |x, _, _| assert_eq!(x, 42));
}
|
use crate::{
error::CompilerError,
hir::{self},
id::CountableId,
lir::{self, Lir},
mir::{self},
mir_optimize::OptimizeMir,
module::Module,
string_to_rcst::ModuleError,
TracingConfig,
};
use itertools::Itertools;
use rustc_hash::{FxHashMap, FxHashSet};
use std::sync::Arc;
#[salsa::query_group(MirToLirStorage)]
pub trait MirToLir: OptimizeMir {
fn lir(&self, module: Module, tracing: TracingConfig) -> LirResult;
}
pub type LirResult = Result<(Arc<Lir>, Arc<FxHashSet<CompilerError>>), ModuleError>;
fn lir(db: &dyn MirToLir, module: Module, tracing: TracingConfig) -> LirResult {
let (mir, _, errors) = db.optimized_mir(module.clone(), tracing)?;
let mut context = LoweringContext::default();
context.compile_function(
FxHashSet::from_iter([hir::Id::new(module, vec![])]),
&[],
&[],
mir::Id::from_usize(0),
&mir.body,
);
let lir = Lir::new(context.constants, context.bodies);
Ok((Arc::new(lir), errors))
}
#[derive(Clone, Debug, Default)]
struct LoweringContext {
constants: lir::Constants,
constant_mapping: FxHashMap<mir::Id, lir::ConstantId>,
bodies: lir::Bodies,
}
impl LoweringContext {
fn compile_function(
&mut self,
original_hirs: FxHashSet<hir::Id>,
captured: &[mir::Id],
parameters: &[mir::Id],
responsible_parameter: mir::Id,
body: &mir::Body,
) -> lir::BodyId {
let body = CurrentBody::compile_function(
self,
original_hirs,
captured,
parameters,
responsible_parameter,
body,
);
self.bodies.push(body)
}
}
#[derive(Clone, Debug, Default)]
struct CurrentBody {
id_mapping: FxHashMap<mir::Id, lir::Id>,
captured_count: usize,
parameter_count: usize,
expressions: Vec<lir::Expression>,
last_constant: Option<mir::Id>,
ids_to_drop: FxHashSet<lir::Id>,
}
impl CurrentBody {
fn compile_function(
context: &mut LoweringContext,
original_hirs: FxHashSet<hir::Id>,
captured: &[mir::Id],
parameters: &[mir::Id],
responsible_parameter: mir::Id,
body: &mir::Body,
) -> lir::Body {
let mut lir_body = CurrentBody::new(captured, parameters, responsible_parameter);
for (id, expression) in body.iter() {
lir_body.compile_expression(context, id, expression);
}
lir_body.finish(&context.constant_mapping, original_hirs)
}
fn new(captured: &[mir::Id], parameters: &[mir::Id], responsible_parameter: mir::Id) -> Self {
let captured_count = captured.len();
let parameter_count = parameters.len();
let id_mapping: FxHashMap<_, _> = captured
.iter()
.chain(parameters.iter())
.copied()
.chain([responsible_parameter])
.enumerate()
.map(|(index, id)| (id, lir::Id::from_usize(index)))
.collect();
// The responsible parameter is a HIR ID, which is always constant.
// Hence, it never has to be dropped.
let ids_to_drop = id_mapping
.iter()
.filter(|(&k, _)| k != responsible_parameter)
.map(|(_, v)| v)
.copied()
.collect();
Self {
id_mapping,
captured_count,
parameter_count,
expressions: Vec::new(),
last_constant: None,
ids_to_drop,
}
}
fn compile_expression(
&mut self,
context: &mut LoweringContext,
id: mir::Id,
expression: &mir::Expression,
) {
match expression {
mir::Expression::Int(int) => self.push_constant(context, id, int.clone()),
mir::Expression::Text(text) => self.push_constant(context, id, text.clone()),
mir::Expression::Tag { symbol, value } => {
if let Some(value) = value {
if let Some(constant_id) = self.constant_for(context, *value) {
self.push_constant(
context,
id,
lir::Constant::Tag {
symbol: symbol.clone(),
value: Some(constant_id),
},
);
} else {
self.push(
id,
lir::Expression::CreateTag {
symbol: symbol.clone(),
value: self.id_mapping[value],
},
);
}
} else {
self.push_constant(
context,
id,
lir::Constant::Tag {
symbol: symbol.clone(),
value: None,
},
);
}
}
mir::Expression::Builtin(builtin) => self.push_constant(context, id, *builtin),
mir::Expression::List(items) => {
if let Some(items) = items
.iter()
.map(|item| self.constant_for(context, *item))
.collect::<Option<Vec<_>>>()
{
self.push_constant(context, id, items);
} else {
let items = self.ids_for(context, items);
self.push(id, items);
}
}
mir::Expression::Struct(fields) => {
if let Some(fields) = fields
.iter()
.map(|(key, value)| try {
(
self.constant_for(context, *key)?,
self.constant_for(context, *value)?,
)
})
.collect::<Option<FxHashMap<_, _>>>()
{
self.push_constant(context, id, fields);
} else {
let fields = fields
.iter()
.map(|(key, value)| {
(self.id_for(context, *key), self.id_for(context, *value))
})
.collect_vec();
self.push(id, fields);
}
}
mir::Expression::Reference(referenced_id) => {
// References only remain in the MIR to return a constant from a
// function.
if let Some(&referenced_id) = self.id_mapping.get(referenced_id) {
self.maybe_dup(referenced_id);
// TODO: The reference following MIR optimization isn't
// always working correctly. Add the following code once it
// does work.
// assert!(
// !self.ids_to_drop.contains(&referenced_id),
// "References in the optimized MIR should only point to constants.",
// );
self.push(id, referenced_id);
return;
}
self.push(id, self.constant_for(context, *referenced_id).unwrap());
}
mir::Expression::HirId(hir_id) => self.push_constant(context, id, hir_id.clone()),
mir::Expression::Function {
original_hirs,
parameters,
responsible_parameter,
body,
} => {
let captured = expression
.captured_ids()
.into_iter()
.filter(|captured| !context.constant_mapping.contains_key(captured))
.sorted()
.collect_vec();
let body_id = context.compile_function(
original_hirs.clone(),
&captured,
parameters,
*responsible_parameter,
body,
);
if captured.is_empty() {
self.push_constant(context, id, body_id);
} else {
let captured = captured.iter().map(|it| self.id_mapping[it]).collect();
self.push(id, lir::Expression::CreateFunction { captured, body_id });
}
}
mir::Expression::Parameter => {
panic!("The MIR should not contain any parameter expressions.")
}
mir::Expression::Call {
function,
arguments,
responsible,
} => {
let function = self.id_for(context, *function);
let arguments = self.ids_for(context, arguments);
let responsible = self.id_for(context, *responsible);
self.push(
id,
lir::Expression::Call {
function,
arguments,
responsible,
},
);
}
mir::Expression::UseModule { .. } => {
// Calls of the use function are completely inlined and, if
// they're not statically known, are replaced by panics.
// The only way a use can still be in the MIR is if the tracing
// of evaluated expressions is enabled. We can emit any nonsense
// here, since the instructions will never be executed anyway.
// We just push an empty struct, as if the imported module
// hadn't exported anything.
self.push(id, lir::Expression::CreateStruct(vec![]));
}
mir::Expression::Panic {
reason,
responsible,
} => {
let reason = self.id_for(context, *reason);
let responsible = self.id_for(context, *responsible);
self.push(
id,
lir::Expression::Panic {
reason,
responsible,
},
);
}
mir::Expression::TraceCallStarts {
hir_call,
function,
arguments,
responsible,
} => {
let hir_call = self.id_for(context, *hir_call);
let function = self.id_for(context, *function);
let arguments = self.ids_for(context, arguments);
let responsible = self.id_for(context, *responsible);
self.push(
id,
lir::Expression::TraceCallStarts {
hir_call,
function,
arguments,
responsible,
},
);
}
mir::Expression::TraceCallEnds { return_value } => {
let return_value = self.id_for(context, *return_value);
self.push(id, lir::Expression::TraceCallEnds { return_value });
}
mir::Expression::TraceExpressionEvaluated {
hir_expression,
value,
} => {
let hir_expression = self.id_for(context, *hir_expression);
let value = self.id_for(context, *value);
self.push(
id,
lir::Expression::TraceExpressionEvaluated {
hir_expression,
value,
},
);
}
mir::Expression::TraceFoundFuzzableFunction {
hir_definition,
function,
} => {
let hir_definition = self.id_for(context, *hir_definition);
let function = self.id_for(context, *function);
self.push(
id,
lir::Expression::TraceFoundFuzzableFunction {
hir_definition,
function,
},
);
}
}
}
fn ids_for(&mut self, context: &LoweringContext, ids: &[mir::Id]) -> Vec<lir::Id> {
ids.iter().map(|it| self.id_for(context, *it)).collect()
}
fn id_for(&mut self, context: &LoweringContext, id: mir::Id) -> lir::Id {
if let Some(&id) = self.id_mapping.get(&id) {
self.maybe_dup(id);
return id;
}
self.push(id, self.constant_for(context, id).unwrap())
}
fn push_constant(
&mut self,
context: &mut LoweringContext,
id: mir::Id,
constant: impl Into<lir::Constant>,
) {
let constant_id = context.constants.push(constant);
context.constant_mapping.insert(id, constant_id);
self.last_constant = Some(id);
}
fn constant_for(&self, context: &LoweringContext, id: mir::Id) -> Option<lir::ConstantId> {
context.constant_mapping.get(&id).copied()
}
fn push(&mut self, mir_id: mir::Id, expression: impl Into<lir::Expression>) -> lir::Id {
let expression = expression.into();
let is_constant = matches!(expression, lir::Expression::Constant(_));
self.expressions.push(expression);
let id = self.last_expression_id();
assert!(self.id_mapping.insert(mir_id, id).is_none());
if !is_constant {
assert!(self.ids_to_drop.insert(id));
}
id
}
fn last_expression_id(&self) -> lir::Id {
lir::Id::from_usize(self.captured_count + self.parameter_count + self.expressions.len())
}
fn maybe_dup(&mut self, id: lir::Id) {
if !self.ids_to_drop.contains(&id) {
return;
}
self.expressions.push(lir::Expression::Dup(id));
}
fn finish(
mut self,
constant_mapping: &FxHashMap<mir::Id, lir::ConstantId>,
original_hirs: FxHashSet<hir::Id>,
) -> lir::Body {
if self.expressions.is_empty() {
// If the top-level MIR contains only constants, its LIR body will
// still be empty. Hence, we push a reference to the last constant
// we encountered.
let last_constant_id = self.last_constant.unwrap();
self.push(last_constant_id, constant_mapping[&last_constant_id]);
}
self.ids_to_drop.remove(&self.last_expression_id());
if !self.ids_to_drop.is_empty() {
let return_value_id = self.last_expression_id();
for id in self.ids_to_drop.iter().sorted().rev() {
self.expressions.push(lir::Expression::Drop(*id));
}
self.expressions
.push(lir::Expression::Reference(return_value_id));
}
lir::Body::new(
original_hirs,
self.captured_count,
self.parameter_count,
self.expressions,
)
}
}
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
// This used to cause an ICE because the retslot for the "return" had the wrong type
fn testcase<'a>() -> Box<Iterator<Item=usize> + 'a> {
return Box::new((0..3).map(|i| { return i; }));
}
fn main() {
}
|
use num_traits::Zero;
/// Algorithm: [`Wikipedia`]<https://en.wikipedia.org/wiki/Integer_square_root#Example_implementation_in_C>.
/// Calculates the integer square root of an integer.
pub trait Sqrt {
fn sqrt(&self) -> Self;
}
impl Sqrt for u64 {
fn sqrt(&self) -> Self {
let val = *self;
if val == 1 {
return *self;
}
let mut x0 = val >> 1;
let mut x1 = (x0 + val / x0) >> 1;
while x1 < x0 {
x0 = x1;
x1 = (x0 + val / x0) >> 1;
}
x0
}
}
/// Returns a vector of all primes under a given limit. Uses the Sieve of
/// Eratosthenes algorithm.
#[allow(clippy::cast_possible_truncation)]
pub fn sieve(n: u64) -> Vec<u64> {
let mut is_prime = vec![true; (n + 1) as usize];
is_prime[0] = false;
is_prime[1] = false;
for i in 2..=n.sqrt() as usize {
if is_prime[i] {
for j in (i * i..=n as usize).step_by(i) {
is_prime[j] = false;
}
}
}
is_prime
.into_iter()
.enumerate()
.filter_map(|(i, v)| if v { Some(i as u64) } else { None })
.collect()
}
/// Converts an integer to a vector representation of its digits
pub trait ToDigits: num_integer::Integer + Clone {
fn to_digits(&self, radix: Self) -> Vec<Self> {
let mut val = self.clone();
let mut digits = vec![];
while !val.is_zero() {
digits.push(val.clone() % radix.clone());
val = val.clone() / radix.clone();
}
digits
}
}
impl ToDigits for u64 {}
/// Converts a vector representation of an integer's digits to an integer
pub trait FromDigits: num_integer::Integer + Clone {
fn from_digits(digits: &mut Vec<Self>, radix: Self) -> Self {
let mut val: Self = Zero::zero();
while let Some(digit) = digits.pop() {
val = val.clone() * radix.clone();
val = val.clone() + digit.clone();
}
val
}
}
impl FromDigits for u64 {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sieve_works() {
assert_eq!(sieve(10), vec![2, 3, 5, 7]);
}
#[test]
fn sqrt_works() {
assert_eq!(100_u64.sqrt(), 10);
assert_eq!(17_u64.sqrt(), 4);
}
#[test]
fn to_digits_works() {
assert_eq!(100.to_digits(10), vec![0, 0, 1]);
assert_eq!(21_536.to_digits(10), vec![6, 3, 5, 1, 2]);
}
#[test]
fn from_digits_works() {
assert_eq!(u64::from_digits(&mut vec![0, 0, 1], 10), 100);
assert_eq!(u64::from_digits(&mut vec![6, 3, 5, 1, 2], 10), 21_536);
}
}
|
mod board;
mod bot;
use std::f64;
use std::rc::Rc;
use gio::prelude::*;
use gtk::prelude::*;
use gtk::Application;
use crate::board::{Board, PlayerMark};
use crate::bot::Bot;
const APP_ID: &str = "com.github.dmitmel.tic-tac-toe-evolution";
const BOARD_CELL_SIZE: i32 = 32;
const BOARD_MARK_MARGIN: f64 = 0.1;
const BOARD_MARK_LINE_WIDTH: f64 = 0.25;
fn main() {
let application =
Application::new(Some(APP_ID), gio::ApplicationFlags::default())
.expect("failed to initialize GTK application");
application.connect_activate(|app| {
let builder = gtk::Builder::new_from_string(include_str!("main.glade"));
let mut board = Board::new(100, 100);
randomly_fill_board(&mut board);
let players = Rc::new([
Bot::new(generate_random_program(), PlayerMark::X, &board),
Bot::new(generate_random_program(), PlayerMark::O, &board),
]);
let ui_board: gtk::DrawingArea = builder.get_object("board").unwrap();
ui_board.set_size_request(
board.width() as i32 * BOARD_CELL_SIZE,
board.height() as i32 * BOARD_CELL_SIZE,
);
ui_board.connect_draw(move |ui_board, ctx: &cairo::Context| -> Inhibit {
let style_ctx = ui_board.get_style_context();
gtk::render_background(
&style_ctx,
ctx,
0.0,
0.0,
f64::from(ui_board.get_allocated_width()),
f64::from(ui_board.get_allocated_height()),
);
render_board(&board, ctx);
Inhibit(false)
});
let ui_player: gtk::ComboBoxText = builder.get_object("player").unwrap();
for index in 0..players.len() {
ui_player.append_text(&format!("Player {}", index));
}
ui_player.set_active(Some(0));
{
let players = Rc::clone(&players);
let ui_player_info: gtk::Label =
builder.get_object("player_info").unwrap();
let ui_player_program: gtk::TreeView =
builder.get_object("player_program").unwrap();
let mut ui_player_programs_instructions: Vec<gtk::ListStore> = vec![];
for player in players.iter() {
let ui_instructions = gtk::ListStore::new(&[
String::static_type(),
String::static_type(),
String::static_type(),
]);
for (address, instruction) in player.program().iter().enumerate() {
let icon = if address == player.instruction_pointer() {
Some("gtk-go-forward")
} else {
None
};
ui_instructions.insert_with_values(
None,
&[0, 1, 2],
&[
&icon,
&format!("{:04x}", address),
&format!("{:?}", instruction),
],
);
}
ui_player_programs_instructions.push(ui_instructions);
}
let update_player_sidebar = move |ui_player: >k::ComboBoxText| {
if let Some(selected) = ui_player.get_active() {
let selected_player = &players[selected as usize];
ui_player_info.set_text(&format!(
"\
Mark: {:?}
Instruction count: {}
Current address: {:04x}
Program:",
selected_player.mark(),
selected_player.program().len(),
selected_player.instruction_pointer(),
));
ui_player_program.set_model(Some(
&ui_player_programs_instructions[selected as usize],
));
}
};
update_player_sidebar(&ui_player);
ui_player.connect_changed(update_player_sidebar);
}
{
let players = Rc::clone(&players);
let ui_player_program: gtk::TreeView =
builder.get_object("player_program").unwrap();
let ui_show_current_instruction: gtk::Button =
builder.get_object("show_current_instruction").unwrap();
ui_show_current_instruction.connect_clicked(move |_| {
if let Some(selected) = ui_player.get_active() {
let selected_player = &players[selected as usize];
let instruction_pointer: usize =
selected_player.instruction_pointer();
ui_player_program.set_cursor(
>k::TreePath::new_from_indicesv(&[instruction_pointer as i32]),
None::<>k::TreeViewColumn>,
false,
);
}
});
}
let window: gtk::ApplicationWindow = builder.get_object("window2").unwrap();
window.set_application(Some(app));
window.maximize();
window.show_all();
});
let args: Vec<String> = std::env::args().collect();
application.run(&args);
}
fn randomly_fill_board(board: &mut Board) {
use rand::distributions::Bernoulli;
use rand::Rng;
let mut rng = rand::thread_rng();
let dstr = Bernoulli::new(0.5).unwrap();
for y in 0..board.width() {
for x in 0..board.height() {
board.set(
x,
y,
if rng.sample(dstr) {
Some(if rng.sample(dstr) { PlayerMark::X } else { PlayerMark::O })
} else {
None
},
)
}
}
}
fn generate_random_program() -> bot::Program {
use rand::distributions::{Standard, Uniform};
use rand::Rng;
let mut rng = rand::thread_rng();
rng
.sample_iter(Uniform::new(0, 10))
.take(0x100)
.map(|n: u8| {
use crate::bot::Instruction::*;
use crate::bot::MoveDirection::*;
match n {
0..=7 => Move(match n {
0 => Up,
1 => UpRight,
2 => Right,
3 => DownRight,
4 => Down,
5 => DownLeft,
6 => Left,
7 => UpLeft,
_ => unreachable!(),
}),
8 => CheckMark,
9 => PlaceMark,
10 => Jump(rng.sample(Standard)),
_ => unreachable!(),
}
})
.collect()
}
fn render_board(board: &Board, ctx: &cairo::Context) {
ctx.set_line_width(BOARD_MARK_LINE_WIDTH);
for y in 0..board.width() {
for x in 0..board.height() {
if let Some(mark) = board.get(x, y) {
ctx.save();
ctx.scale(f64::from(BOARD_CELL_SIZE), f64::from(BOARD_CELL_SIZE));
ctx.translate(
x as f64 + BOARD_MARK_MARGIN,
y as f64 + BOARD_MARK_MARGIN,
);
ctx.scale(1.0 - BOARD_MARK_MARGIN * 2.0, 1.0 - BOARD_MARK_MARGIN * 2.0);
match mark {
PlayerMark::X => render_player_mark_x(ctx),
PlayerMark::O => render_player_mark_o(ctx),
}
ctx.stroke();
ctx.restore();
}
}
}
}
fn render_player_mark_x(ctx: &cairo::Context) {
let a = BOARD_MARK_LINE_WIDTH / f64::consts::SQRT_2 / 2.0;
ctx.set_source_rgb(239.0 / 255.0, 41.0 / 255.0, 41.0 / 255.0);
ctx.move_to(a, a);
ctx.line_to(1.0 - a, 1.0 - a);
ctx.move_to(a, 1.0 - a);
ctx.line_to(1.0 - a, a);
}
fn render_player_mark_o(ctx: &cairo::Context) {
ctx.set_source_rgb(52.0 / 255.0, 101.0 / 255.0, 164.0 / 255.0);
ctx.arc(
0.5,
0.5,
0.5 - BOARD_MARK_LINE_WIDTH / 2.0,
0.0,
2.0 * f64::consts::PI,
);
}
|
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
use std::cmp::Ordering;
fn main() {
run();
}
fn run() {
let start = std::time::Instant::now();
// code goes here
let res = TriangleNum::default()
.find(|n| num_divisors(*n) > 500)
.unwrap();
let span = start.elapsed().as_nanos();
println!("{} {}", res, span);
}
// calculates the number of positive divisors of a positive integer
fn num_divisors(n: u64) -> u64 {
let mut count = 0;
let lim = sqrt(n);
for i in 1..=lim {
if n % i == 0 {
count += 1;
if i * i != n {
count += 1;
}
}
}
count
}
// returns the approximate square root of an integer
#[allow(clippy::similar_names)]
fn sqrt(n: u64) -> u64 {
let mut min = 0;
let mut max = n;
while min < max {
let mid = (min + max + 1) / 2;
let square = mid * mid;
match square.cmp(&n) {
| Ordering::Equal => return mid,
| Ordering::Greater => max = mid - 1,
| Ordering::Less => min = mid,
}
}
min
}
// Simple struct to allow us to iterate over triangle numbers.
#[derive(Default)]
struct TriangleNum {
idx: u64,
}
impl Iterator for TriangleNum {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
let res = self.idx * (self.idx + 1) / 2;
self.idx += 1;
Some(res)
}
}
|
extern crate libsamplerate_sys;
#[cfg(test)]
mod tests {
use libsamplerate_sys::*;
#[test]
fn linking_works() {
unsafe {
let mut error = 0;
let _state = src_new(SRC_SINC_BEST_QUALITY, 2, &mut error);
}
}
}
|
use std::{
ops,
intrinsics::{fadd_fast, fsub_fast, fmul_fast, fdiv_fast}
};
#[derive(Debug, Clone, Copy)]
pub struct Vector3 {
x: f32,
y: f32,
z: f32
}
impl ops::Add for Vector3 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
unsafe {
Vector3 {
x: fadd_fast(self.x, rhs.x),
y: fadd_fast(self.y, rhs.y),
z: fadd_fast(self.z, rhs.z)
}
}
}
}
impl ops::Sub for Vector3 {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
unsafe {
Vector3 {
x: fsub_fast(self.x, rhs.x),
y: fsub_fast(self.y, rhs.y),
z: fsub_fast(self.z, rhs.z)
}
}
}
}
impl ops::Mul for Vector3 {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
unsafe {
Vector3 {
x: fmul_fast(self.x, rhs.x),
y: fmul_fast(self.y, rhs.y),
z: fmul_fast(self.z, rhs.z)
}
}
}
}
impl ops::Mul<f32> for Vector3 {
type Output = Self;
fn mul(self, rhs: f32) -> Self::Output {
unsafe {
Vector3 {
x: fmul_fast(self.x, rhs),
y: fmul_fast(self.y, rhs),
z: fmul_fast(self.z, rhs)
}
}
}
}
impl ops::Div for Vector3 {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
unsafe {
Vector3 {
x: fdiv_fast(self.x, rhs.x),
y: fdiv_fast(self.y, rhs.y),
z: fdiv_fast(self.z, rhs.z)
}
}
}
}
impl ops::AddAssign for Vector3 {
fn add_assign(&mut self, rhs: Self) {
unsafe {
self.x = fadd_fast(self.x, rhs.x);
self.y = fadd_fast(self.y, rhs.y);
self.z = fadd_fast(self.z, rhs.z);
}
}
}
impl ops::SubAssign for Vector3 {
fn sub_assign(&mut self, rhs: Self) {
unsafe {
self.x = fsub_fast(self.x, rhs.x);
self.y = fsub_fast(self.y, rhs.y);
self.z = fsub_fast(self.z, rhs.z);
}
}
}
impl ops::MulAssign for Vector3 {
fn mul_assign(&mut self, rhs: Self) {
unsafe {
self.x = fmul_fast(self.x, rhs.x);
self.y = fmul_fast(self.y, rhs.y);
self.z = fmul_fast(self.z, rhs.z);
}
}
}
impl ops::MulAssign<f32> for Vector3 {
fn mul_assign(&mut self, rhs: f32) {
unsafe {
self.x = fmul_fast(self.x, rhs);
self.y = fmul_fast(self.y, rhs);
self.z = fmul_fast(self.z, rhs);
}
}
}
impl ops::DivAssign for Vector3 {
fn div_assign(&mut self, rhs: Self) {
unsafe {
self.x = fdiv_fast(self.x, rhs.x);
self.y = fdiv_fast(self.y, rhs.y);
self.z = fdiv_fast(self.z, rhs.z);
}
}
}
impl Vector3 {
pub fn new(x: f32, y: f32, z: f32) -> Self {
Vector3 { x, y, z }
}
pub fn dotp(a: &Vector3, b: &Vector3) -> f32 {
unsafe {
fadd_fast(
fadd_fast(
fmul_fast(a.x, b.x),
fmul_fast(a.y, b.y)
),
fmul_fast(a.z, b.z)
)
}
}
#[allow(dead_code)]
pub fn distance_squared(a: &Vector3, b: &Vector3) -> f32 {
unsafe {
fadd_fast(
fadd_fast(
{ let x = fsub_fast(a.x, b.x); fmul_fast(x, x) },
{ let x = fsub_fast(a.y, b.y); fmul_fast(x, x) }
),
{ let x = fsub_fast(a.z, b.z); fmul_fast(x, x) }
)
}
}
#[allow(dead_code)]
pub fn distance(a: &Vector3, b: &Vector3) -> f32 {
f32::sqrt(Vector3::distance_squared(a, b))
}
#[allow(dead_code)]
pub fn normalized(self) -> Self {
let d = f32::sqrt(
f32::powi(self.x, 2) + f32::powi(self.y, 2) + f32::powi(self.z, 2)
);
self * (1. / d)
}
#[allow(dead_code)]
pub fn normalize(&mut self) {
let d = f32::sqrt(
f32::powi(self.x, 2) + f32::powi(self.y, 2) + f32::powi(self.z, 2)
);
*self *= 1. / d;
}
#[allow(dead_code)]
pub fn direction(a: Self, b: Self) -> Self {
(a - b).normalized()
}
}
|
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
extern crate js_sys;
use js_sys::Date;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
// Binding for the `setInverval` method in JS. This function takes a "long
// lived" closure as the first argument so we use `Closure` instead of
// a bare `&Fn()` which only surives for that one stack frame.
//
// The second argument is then the interval and the return value is how we
// clear this interval. We're not going to clear our interval in this
// example though so the return value is ignored.
#[wasm_bindgen(js_name = setInterval)]
fn set_interval(cb: &Closure<FnMut()>, delay: u32) -> f64;
// Bindings for `document` and various methods of updating HTML elements.
// Like with the `dom` example these'll ideally be upstream in a generated
// crate one day but for now we manually define them.
type HTMLDocument;
static document: HTMLDocument;
#[wasm_bindgen(method, js_name = getElementById)]
fn get_element_by_id(this: &HTMLDocument, id: &str) -> Element;
#[wasm_bindgen(method, js_name = getElementById)]
fn get_html_element_by_id(this: &HTMLDocument, id: &str) -> HTMLElement;
type Element;
#[wasm_bindgen(method, setter = innerHTML)]
fn set_inner_html(this: &Element, html: &str);
type HTMLElement;
#[wasm_bindgen(method, setter)]
fn set_onclick(this: &HTMLElement, cb: &Closure<FnMut()>);
#[wasm_bindgen(method, getter)]
fn style(this: &HTMLElement) -> CSS2Properties;
type CSS2Properties;
#[wasm_bindgen(method, setter)]
fn set_display(this: &CSS2Properties, display: &str);
}
#[wasm_bindgen]
pub fn run() {
// Set up a clock on our page and update it each second to ensure it's got
// an accurate date.
let a = Closure::new(update_time);
set_interval(&a, 1000);
update_time();
fn update_time() {
document
.get_element_by_id("current-time")
.set_inner_html(&String::from(
Date::new(&JsValue::undefined())
.to_locale_string("en-GB", &JsValue::undefined()),
));
}
// We also want to count the number of times that our green square has been
// clicked. Our callback will update the `#num-clicks` div
let square = document.get_html_element_by_id("green-square");
let mut clicks = 0;
let b = Closure::new(move || {
clicks += 1;
document
.get_element_by_id("num-clicks")
.set_inner_html(&clicks.to_string());
});
square.set_onclick(&b);
// The instances of `Closure` that we created will invalidate their
// corresponding JS callback whenever they're dropped, so if we were to
// normally return from `run` then both of our registered closures will
// raise exceptions when invoked.
//
// Normally we'd store these handles to later get dropped at an appropriate
// time but for now we want these to be global handlers so we use the
// `forget` method to drop them without invalidating the closure. Note that
// this is leaking memory in Rust, so this should be done judiciously!
a.forget();
b.forget();
// And finally now that our demo is ready to go let's switch things up so
// everything is displayed and our loading prompt is hidden.
document
.get_html_element_by_id("loading")
.style()
.set_display("none");
document
.get_html_element_by_id("script")
.style()
.set_display("block");
}
|
use bevy_app::prelude::*;
use bevy_ecs::IntoQuerySystem;
pub use common::*;
pub use event::*;
pub use listeners::*;
pub use sockets::*;
use system::*;
mod common;
mod event;
mod listener;
mod listeners;
mod socket;
mod sockets;
mod system;
pub mod prelude {
pub use crate::{
common::{IpAddress, ListenerId, Port, SocketAddress, SocketId},
listener::Listener,
listeners::Listeners,
socket::Socket,
sockets::Sockets,
};
}
/// Adds sockets and listeners to an app
#[derive(Default)]
pub struct NetPlugin;
impl Plugin for NetPlugin {
fn build(&self, app: &mut AppBuilder) {
app.add_event::<OpenSocket>()
.add_event::<SocketOpened>()
.add_event::<SocketError>()
.add_event::<SendSocket>()
.add_event::<SocketSent>()
.add_event::<SocketReceive>()
.add_event::<CloseSocket>()
.add_event::<SocketClosed>()
.init_resource::<Sockets>()
.add_systems_to_stage(
bevy_app::stage::EVENT_UPDATE,
vec![
open_socket_events_system.system(),
socket_receive_system.system(),
send_socket_events_system.system(),
close_socket_events_system.system(),
],
)
.add_event::<CreateListener>()
.add_event::<ListenerCreated>()
.add_event::<ListenerError>()
.add_event::<ListenerConnected>()
.add_event::<CloseListener>()
.add_event::<ListenerClosed>()
.init_resource::<Listeners>()
.add_systems_to_stage(
bevy_app::stage::EVENT_UPDATE,
vec![
create_listener_events_system.system(),
listener_connection_system.system(),
close_listener_events_system.system(),
],
);
}
}
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use anyhow::*;
use liblumen_alloc::erts::exception::{self, *};
use liblumen_alloc::erts::process::trace::Trace;
use liblumen_alloc::erts::term::prelude::*;
#[native_implemented::function(erlang:+/1)]
pub fn result(number: Term) -> exception::Result<Term> {
if number.is_number() {
Ok(number)
} else {
Err(badarith(
Trace::capture(),
Some(anyhow!("number ({}) is not an integer or a float", number).into()),
)
.into())
}
}
|
use std::collections::VecDeque;
use std::fs::File;
use std::io::Read;
use std::cmp;
#[repr(u8)]
#[derive(PartialEq)]
enum ParamType {
PositionMode = 0,
ImmediateMode = 1,
RelativeMode = 2,
}
fn get_param_type(mode: i64) -> ParamType {
match mode {
0 => ParamType::PositionMode,
1 => ParamType::ImmediateMode,
2 => ParamType::RelativeMode,
u => panic!("Unexpected parameter type: {}", u),
}
}
struct Param {
mode: ParamType,
value: i64,
relative_base: i64,
}
impl Param {
fn new(vec: &Vec<i64>, index: usize, param_index: usize, relative_base: i64) -> Param {
let mode = get_param_type((vec[index] / 10i64.pow((param_index + 1) as u32)) % 10);
let value = vec[index + param_index];
Param { mode, value, relative_base }
}
fn get_value(&self, vec: &Vec<i64>) -> i64 {
match self.mode {
ParamType::PositionMode => vec[self.value as usize],
ParamType::ImmediateMode => self.value,
ParamType::RelativeMode => vec[(self.value + self.relative_base) as usize],
}
}
fn set_value(&self, vec: &mut Vec<i64>, value: i64) {
match self.mode {
ParamType::PositionMode => vec[self.value as usize] = value,
ParamType::ImmediateMode => panic!("set_value called with a parameter in ImmediateMode!"),
ParamType::RelativeMode => vec[(self.value + self.relative_base) as usize] = value,
}
}
}
struct Program {
state: Vec<i64>,
current_op: usize,
finished: bool,
input: VecDeque<i64>,
output: VecDeque<i64>,
relative_base: i64,
}
impl Program {
fn new(program: &Vec<i64>, input: VecDeque<i64>) -> Program {
let mut state = vec![0; 10000];
state.as_mut_slice()[0..program.len()].copy_from_slice(program.as_slice());
Program {
state,
current_op: 0,
finished: false,
input,
output: VecDeque::new(),
relative_base: 0,
}
}
fn _is_finished(&self) -> bool {
self.finished
}
fn get_params(&self, num_params: usize) -> Vec<Param> {
let mut params = Vec::new();
for i in 1..num_params + 1 {
params.push(Param::new(&self.state, self.current_op, i, self.relative_base));
}
params
}
fn op_add(&mut self) {
let params = self.get_params(3);
let sum = params[0].get_value(&self.state) + params[1].get_value(&self.state);
params[2].set_value(&mut self.state, sum);
self.current_op += 4;
}
fn op_mul(&mut self) {
let params = self.get_params(3);
let product = params[0].get_value(&self.state) * params[1].get_value(&self.state);
params[2].set_value(&mut self.state, product);
self.current_op += 4;
}
fn op_input(&mut self) -> bool {
let params = self.get_params(1);
let input = self.input.pop_back();
if input.is_none() {
return false;
}
params[0].set_value(&mut self.state, input.unwrap());
self.current_op += 2;
return true;
}
fn op_output(&mut self) {
let params = self.get_params(1);
let value = params[0].get_value(&self.state);
self.output.push_back(value);
self.current_op += 2;
// println!("Output: {}", value);
}
fn op_jump_if_true(&mut self) {
let params = self.get_params(2);
if params[0].get_value(&self.state) != 0 {
self.current_op = params[1].get_value(&self.state) as usize;
} else {
self.current_op += 3;
}
}
fn op_jump_if_false(&mut self) {
let params = self.get_params(2);
if params[0].get_value(&self.state) == 0 {
self.current_op = params[1].get_value(&self.state) as usize;
} else {
self.current_op += 3;
}
}
fn op_lessthan(&mut self) {
let params = self.get_params(3);
let to_store;
if params[0].get_value(&self.state) < params[1].get_value(&self.state) {
to_store = 1;
} else {
to_store = 0;
}
params[2].set_value(&mut self.state, to_store);
self.current_op += 4;
}
fn op_equal(&mut self) {
let params = self.get_params(3);
let to_store;
if params[0].get_value(&self.state) == params[1].get_value(&self.state) {
to_store = 1;
} else {
to_store = 0;
}
params[2].set_value(&mut self.state, to_store);
self.current_op += 4;
}
fn op_adjust_relative_base(&mut self) {
let params = self.get_params(1);
self.relative_base += params[0].get_value(&self.state);
self.current_op += 2;
}
fn run_program(&mut self, input: i64) -> &VecDeque<i64> {
self.output.clear();
self.input.push_front(input);
while self.current_op < self.state.len() {
match self.state[self.current_op] % 100 {
1 => self.op_add(),
2 => self.op_mul(),
3 => {
if !self.op_input() {
break;
}
}
4 => self.op_output(),
5 => self.op_jump_if_true(),
6 => self.op_jump_if_false(),
7 => self.op_lessthan(),
8 => self.op_equal(),
9 => self.op_adjust_relative_base(),
99 => {
self.finished = true;
break;
}
_ => panic!("Invalid opcode!"),
}
}
&self.output
}
}
#[repr(u8)]
#[derive(Clone, Copy, PartialEq)]
enum TileType {
Unexplored = 0,
Empty = 1,
InitialPos = 2,
OxygenSys = 3,
Wall = 4,
}
fn get_dir_command(dir_x: i64, dir_y: i64) -> i64 {
if dir_x != 0 {
if dir_x < 0 {
3
} else {
4
}
} else {
if dir_y < 0 {
1
} else {
2
}
}
}
fn print_map(map: &[[(TileType, u64); 500]; 500]) {
let (mut min_x, mut min_y) = (std::usize::MAX, std::usize::MAX);
let (mut max_x, mut max_y) = (0, 0);
println!("Map:");
for y in 0..500 {
for x in 0..500 {
if map[y][x].0 != TileType::Unexplored {
min_x = cmp::min(x, min_x);
min_y = cmp::min(y, min_y);
max_x = cmp::max(x, max_x);
max_y = cmp::max(y, max_y);
}
}
}
let width = (max_x - min_x) + 1;
for y in min_y..max_y + 1 {
let mut line = vec![' '; width];
for x in min_x..max_x + 1 {
let dachar;
match map[y][x].0 {
TileType::Unexplored => dachar = ' ',
TileType::Empty => dachar = '.',
TileType::InitialPos => dachar = 'R',
TileType::OxygenSys => dachar = 'O',
TileType::Wall => dachar = '#',
}
line[x - min_x] = dachar;
}
let string: String = line.iter().collect();
println!("{}", string);
}
}
fn flood_fill(program: &mut Program, map: &mut [[(TileType, u64); 500]; 500], x: i64, y: i64, dir_x: i64, dir_y: i64) {
if map[(y + dir_y) as usize][(x + dir_x) as usize].0 == TileType::Unexplored {
let command = get_dir_command(dir_x, dir_y);
let res = program.run_program(command);
let res = res[res.len()-1];
let ret_tile;
match res {
0 => ret_tile = TileType::Wall,
1 => ret_tile = TileType::Empty,
2 => ret_tile = TileType::OxygenSys,
_ => unreachable!(),
}
map[(y + dir_y) as usize][(x + dir_x) as usize].0 = ret_tile;
// print_map(map);
if ret_tile != TileType::Wall {
flood_fill(program, map, x + dir_x, y + dir_y, -1, 0);
flood_fill(program, map, x + dir_x, y + dir_y, 1, 0);
flood_fill(program, map, x + dir_x, y + dir_y, 0, -1);
flood_fill(program, map, x + dir_x, y + dir_y, 0, 1);
let command = get_dir_command(-dir_x, -dir_y);
program.run_program(command);
}
}
}
pub fn run_puzzle() {
let mut file = File::open("input_day15.txt").expect("Failed to open input_day15.txt");
let mut ops_string = String::new();
file.read_to_string(&mut ops_string).unwrap();
let vec: Vec<i64> = ops_string.split(',').map(|text| text.trim().parse().unwrap()).collect();
let mut program = Program::new(&vec, VecDeque::new());
let mut map = [[(TileType::Unexplored, std::u64::MAX - 1); 500]; 500];
let (x, y) = (250, 250);
map[y as usize][x as usize] = (TileType::InitialPos, std::u64::MAX - 1);
flood_fill(&mut program, &mut map, x, y, -1, 0);
flood_fill(&mut program, &mut map, x, y, 1, 0);
flood_fill(&mut program, &mut map, x, y, 0, -1);
flood_fill(&mut program, &mut map, x, y, 0, 1);
'search: for y in 0..500 {
for x in 0..500 {
if map[y][x].0 == TileType::OxygenSys {
map[y][x].1 = 0;
break 'search;
}
}
}
let mut changed = true;
while changed {
changed = false;
for y in 0..500 {
for x in 0..500 {
if map[y][x].0 == TileType::Empty || map[y][x].0 == TileType::InitialPos {
let mut min_steps = std::u64::MAX - 1;
if map[y][x-1].1 < min_steps { min_steps = map[y][x-1].1; }
if map[y][x+1].1 < min_steps { min_steps = map[y][x+1].1; }
if map[y-1][x].1 < min_steps { min_steps = map[y-1][x].1; }
if map[y+1][x].1 < min_steps { min_steps = map[y+1][x].1; }
min_steps += 1;
if min_steps < map[y][x].1 {
map[y][x].1 = min_steps;
changed = true;
}
}
}
}
}
let mut max = 0;
for y in 0..500 {
for x in 0..500 {
if map[y][x].0 == TileType::Empty || map[y][x].0 == TileType::InitialPos {
if map[y][x].1 > max {
max = map[y][x].1;
}
}
}
}
println!("Last tile gets oxygen after {} minutes", max);
}
|
/*
* @lc app=leetcode.cn id=67 lang=rust
*
* [67] 二进制求和
*
* https://leetcode-cn.com/problems/add-binary/description/
*
* algorithms
* Easy (46.61%)
* Total Accepted: 18.5K
* Total Submissions: 39.3K
* Testcase Example: '"11"\n"1"'
*
* 给定两个二进制字符串,返回他们的和(用二进制表示)。
*
* 输入为非空字符串且只包含数字 1 和 0。
*
* 示例 1:
*
* 输入: a = "11", b = "1"
* 输出: "100"
*
* 示例 2:
*
* 输入: a = "1010", b = "1011"
* 输出: "10101"
*
*/
use std::collections::vec_deque::VecDeque;
impl Solution {
pub fn add_binary(a: String, b: String) -> String {
let num1: Vec<char> = a.chars().collect();
let num2: Vec<char> = b.chars().collect();
add(&num1, &num2).iter().collect()
}
}
fn add(num1: &Vec<char>, num2: &Vec<char>) -> VecDeque<char> {
if num1.len() < num2.len() {
return add(num2, num1);
}
let (l1, l2) = (num1.len() - 1, num2.len() - 1);
let mut res = VecDeque::new(); // 保存结果
let mut flag = '0'; // 进位标识
for i in 0..num1.len() {
let n2 = if i > l2 { '0' } else { num2[l2 - i] };
let t = [num1[l1 - i], n2, flag]
.iter()
.filter(|c| **c == '1')
.count();
if t == 1 || t == 3 {
res.push_front('1');
} else {
res.push_front('0')
}
if t == 2 || t == 3 {
flag = '1'
} else {
flag = '0';
}
}
if flag != '0' {
res.push_front(flag);
}
res
}
fn main() {
let num1: u64 = 101101;
let num2: u64 = 110101;
let s = Solution::add_binary(num1.to_string(), num2.to_string());
println!("{},{}", s, num1 + num2);
}
struct Solution {}
|
use crate::capabilities::attempt_server_capability;
use crate::capabilities::CAPABILITY_SIGNATURE_HELP;
use crate::context::*;
use crate::position::*;
use crate::types::*;
use crate::util::*;
use lsp_types::request::*;
use lsp_types::*;
use serde::Deserialize;
use url::Url;
pub fn text_document_signature_help(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {
if meta.fifo.is_none() && !attempt_server_capability(ctx, CAPABILITY_SIGNATURE_HELP) {
return;
}
let params = PositionParams::deserialize(params).unwrap();
let req_params = SignatureHelpParams {
context: None,
text_document_position_params: TextDocumentPositionParams {
text_document: TextDocumentIdentifier {
uri: Url::from_file_path(&meta.buffile).unwrap(),
},
position: get_lsp_position(&meta.buffile, ¶ms.position, ctx).unwrap(),
},
work_done_progress_params: Default::default(),
};
ctx.call::<SignatureHelpRequest, _>(
meta,
req_params,
move |ctx: &mut Context, meta, result| editor_signature_help(meta, params, result, ctx),
);
}
pub fn editor_signature_help(
meta: EditorMeta,
params: PositionParams,
result: Option<SignatureHelp>,
ctx: &mut Context,
) {
if let Some(result) = result {
let active_signature = result.active_signature.unwrap_or(0);
if let Some(active_signature) = result.signatures.get(active_signature as usize) {
// TODO decide how to use it
// let active_parameter = result.active_parameter.unwrap_or(0);
let contents = &active_signature.label;
let command = format!(
"lsp-show-signature-help {} {}",
params.position,
editor_quote(contents)
);
ctx.exec(meta, command);
}
}
}
|
pub mod generic_func_strat;
pub mod functional_validation;
use generic_func_strat::run as gfs_run;
use functional_validation::fv_run;
//cargo rustc -- -Z unstable-options --pretty=expanded
fn main(){
gfs_run();
fv_run();
} |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 clap::{App, AppSettings, SubCommand, ArgMatches};
use alloc::string::String;
use super::super::super::qlib::common::*;
use super::super::cmd::config::*;
use super::super::container::container::*;
use super::command::*;
#[derive(Debug)]
pub struct ResumeCmd {
pub id: String,
}
impl ResumeCmd {
pub fn Init(cmd_matches: &ArgMatches) -> Result<Self> {
return Ok(Self {
id: cmd_matches.value_of("id").unwrap().to_string(),
})
}
pub fn SubCommand<'a, 'b>(common: &CommonArgs<'a, 'b>) -> App<'a, 'b> {
return SubCommand::with_name("resume")
.setting(AppSettings::ColoredHelp)
.arg(&common.id_arg)
.about("Resume unpauses a paused container");
}
pub fn Run(&self, gCfg: &GlobalConfig) -> Result<()> {
info!("Container:: resume ....");
let id = &self.id;
let mut container = Container::Load(&gCfg.RootDir, id)?;
container.Resume()?;
return Ok(())
}
} |
use {
crate::{
math::Scalar,
noise::{
fns::{ArcNoiseFn, HeightmapNoise, PerlinConsts, PerlinNoise, PlaneNoise, ScaledNoise},
NoiseArgs,
},
random::Seed,
},
std::sync::Arc,
};
pub trait HeightmapScalar: Scalar + PerlinConsts {}
impl HeightmapScalar for f32 {}
impl HeightmapScalar for f64 {}
/// Heightmap generation based on procedural noise.
#[derive(Clone)]
pub struct Heightmap {
noise: ArcNoiseFn<f32, [f32; 3]>,
}
impl Heightmap {
/// Creates a new heightmap from a given seed.
pub fn new(world_seed: Seed) -> Self {
let noise = Arc::new(
ScaledNoise::new(Arc::new(HeightmapNoise::new(Arc::new(PerlinNoise::new(
NoiseArgs::new(world_seed),
)))))
.scale_x(0.01)
.scale_y(0.1)
.scale_z(0.01),
);
Self { noise }
}
pub fn plane(y_level: f32) -> Self {
let noise = Arc::new(PlaneNoise::new(y_level));
Self { noise }
}
/// Gets a value associated to a point within the world.
///
/// This value may be used to determine what voxel should be placed at the
/// given point.
pub fn value(&self, point: [f32; 3]) -> f32 {
self.noise.value(point)
}
}
|
//! Scheduling of processing and solving steps.
//!
//! The current implementation is temporary and will be replaced with something more flexible.
use log::info;
use partial_ref::{partial, PartialRef};
use crate::{
cdcl::conflict_step,
clause::{
collect_garbage,
reduce::{reduce_locals, reduce_mids},
Tier,
},
context::{parts::*, Context},
prop::restart,
state::SatState,
};
mod luby;
use luby::LubySequence;
/// Scheduling of processing and solving steps.
#[derive(Default)]
pub struct Schedule {
conflicts: u64,
next_restart: u64,
restarts: u64,
luby: LubySequence,
}
/// Perform one step of the schedule.
pub fn schedule_step<'a>(
mut ctx: partial!(
Context<'a>,
mut AnalyzeConflictP,
mut AssignmentP,
mut AssumptionsP,
mut BinaryClausesP,
mut ClauseActivityP,
mut ClauseAllocP,
mut ClauseDbP,
mut ImplGraphP,
mut ModelP,
mut ProofP<'a>,
mut ScheduleP,
mut SolverStateP,
mut TmpDataP,
mut TmpFlagsP,
mut TrailP,
mut VariablesP,
mut VsidsP,
mut WatchlistsP,
SolverConfigP,
),
) -> bool {
let (schedule, mut ctx) = ctx.split_part_mut(ScheduleP);
let (config, mut ctx) = ctx.split_part(SolverConfigP);
if ctx.part(SolverStateP).sat_state != SatState::Unknown
|| ctx.part(SolverStateP).solver_error.is_some()
{
false
} else {
if schedule.conflicts > 0 && schedule.conflicts % 5000 == 0 {
let db = ctx.part(ClauseDbP);
let units = ctx.part(TrailP).top_level_assignment_count();
info!(
"confl: {}k rest: {} vars: {} bin: {} irred: {} core: {} mid: {} local: {}",
schedule.conflicts / 1000,
schedule.restarts,
ctx.part(AssignmentP).assignment().len() - units,
ctx.part(BinaryClausesP).count(),
db.count_by_tier(Tier::Irred),
db.count_by_tier(Tier::Core),
db.count_by_tier(Tier::Mid),
db.count_by_tier(Tier::Local)
);
}
if schedule.next_restart == schedule.conflicts {
restart(ctx.borrow());
schedule.restarts += 1;
schedule.next_restart += config.luby_restart_interval_scale * schedule.luby.advance();
}
if schedule.conflicts % config.reduce_locals_interval == 0 {
reduce_locals(ctx.borrow());
}
if schedule.conflicts % config.reduce_mids_interval == 0 {
reduce_mids(ctx.borrow());
}
collect_garbage(ctx.borrow());
conflict_step(ctx.borrow());
schedule.conflicts += 1;
true
}
}
|
use std::fs::{create_dir_all, File};
use std::io::prelude::*;
use std::io::Result;
use std::path::Path;
pub fn define_ast(output_dir: &str, base_name: &str, types: Vec<&str>) -> Result<()> {
let directory = Path::new(".").join(output_dir);
create_dir_all(directory.clone())?;
let file_path = directory.join(format!("{}{}", base_name, ".java"));
let mut file_buffer = File::create(file_path)?;
file_buffer.write(b"package com.craftinginterpreters.lox;\n\n")?;
file_buffer.write(b"import java.util.List;\n\n")?;
file_buffer.write_fmt(format_args!("abstract class {} {{\n", base_name))?;
define_visitor(&mut file_buffer, base_name, &types)?;
for lox_type in types {
let mut type_split = lox_type.split(":");
let class_name = type_split.next().unwrap().trim();
let field_list = type_split.next().unwrap().trim();
define_type(&mut file_buffer, base_name, class_name, field_list)?;
}
file_buffer.write(b"}\n\n")?;
Ok(())
}
fn define_visitor(file_buffer: &mut File, base_name: &str, types: &Vec<&str>) -> Result<()> {
file_buffer.write(b" interface Visitor<R> {\n")?;
for lox_type in types {
let type_name = lox_type.split(":").next().unwrap().trim();
file_buffer.write_fmt(format_args!(
" R visit{}{}({} {});\n",
type_name,
base_name,
type_name,
base_name.to_lowercase()
))?;
}
file_buffer.write(b" }\n\n")?;
Ok(())
}
fn define_type(
file_buffer: &mut File,
base_name: &str,
class_name: &str,
field_list: &str,
) -> Result<()> {
file_buffer.write_fmt(format_args!(
" static class {} extends {} {{\n",
class_name, base_name
))?;
// constructor
file_buffer.write_fmt(format_args!(" {}({}) {{\n", class_name, field_list))?;
// store params in fields
let fields = field_list.split(", ");
for field in fields.clone() {
let name = field.split(" ").nth(1).unwrap();
file_buffer.write_fmt(format_args!(" this.{} = {};\n", name, name))?;
}
file_buffer.write(b" }\n\n")?;
// visitor pattern
file_buffer.write(b" @Override\n")?;
file_buffer.write(b" <R> R accept(Visitor<R> visitor) {\n")?;
file_buffer.write_fmt(format_args!(
" return visitor.visit{}{}(this);\n",
class_name, base_name
))?;
file_buffer.write(b" }\n\n")?;
// fields
for field in fields {
file_buffer.write_fmt(format_args!(" final {};\n", field))?;
}
file_buffer.write(b" }\n\n")?;
Ok(())
}
|
use actix::prelude::*;
#[derive(MessageResponse)]
struct Added(usize);
#[derive(Message)]
#[rtype(result = Added)]
struct Sum(usize, usize);
fn main() {}
|
use std::cell::RefCell;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::fs;
use std::rc::Rc;
use crate::error::LispyError;
use crate::parser;
use crate::Result;
// Unfortunately I didn't find a better way to share the environment
// between `Lval`s and also have a reference to a parent environment.
// TODO. Revisit this later.
type SharedEnv = Rc<RefCell<LEnv>>;
type BuiltinFn = fn(Lval, &mut SharedEnv) -> Result<Lval>;
/// Represents Lispy's environment.
#[derive(Default, Clone, PartialEq)]
pub struct LEnv {
map: HashMap<String, Lval>,
parent: Option<SharedEnv>,
}
impl LEnv {
/// Performs a symbol lookup in the environemnt and its parents and returns a matching `Lval`.
///
/// # Arguments
///
/// * `symbol` - A string slice that holds the name of the lookup symbol
///
/// As a side-effect it will perform deep copy of `Lval`
fn get(&self, symbol: &str) -> Result<Lval> {
if let Some(val) = self.map.get(symbol) {
// NOTE
// We have to manually handle Fun::Lambda value, because it contains a reference counted pointer
// to LEnv. When clone() is called on it - it will simply increase the counter but won't create
// an actual copy. In this particular case it's not what we want. We want a new copy of 'val'.
// Not doing this results in stack overflow as we may be able to substitute .parent for the
// original LEnv.
// FIXME
// There must be a better way to do this.
let mut val = (*val).clone();
if let Lval::Fun(LvalFun::Lambda(ref mut lambda)) = &mut val {
let env = lambda.env.borrow().clone().into_shared();
lambda.env = env;
}
Ok(val)
} else if let Some(ref parent) = self.parent {
parent.borrow().get(symbol)
} else {
Err(LispyError::UnboundSymbol(symbol.to_owned()))
}
}
/// Bounds provided symbol to `Lval` in the current environment.
///
/// # Arguments
///
/// * `symbol` - A string slice that holds the name of the lookup symbol
///
/// If the symbol was already bounded - updates its value.
fn put(&mut self, symbol: &str, lval: Lval) {
self.map.insert(symbol.to_owned(), lval);
}
/// Bounds provided symbol to `Lval` in the parent environment (recursively) if any.
///
/// * `symbol` - A string slice that holds the name of the lookup symbol
///
/// Otherwise bounds the symbol in the current environment.
fn def(&mut self, key: &str, val: Lval) {
if let Some(ref mut parent) = self.parent {
return parent.borrow_mut().def(key, val);
}
self.put(key, val);
}
/// Registers provided `BuiltinFn` under name in the current environment.
///
/// # Arguments
///
/// * `name` - A string slice that holds the name of the builtin
/// * `func` - A function of `BuiltinFn` type
fn add_builtin(&mut self, name: &'static str, func: BuiltinFn) {
self.put(name, Lval::builtin(name, func))
}
/// Creates a new environment that can be shared between multiple owners
pub fn new_shared() -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(LEnv::default()))
}
/// Converts this environment into a shared one
pub fn into_shared(self) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(self))
}
}
/// This trait provides an interface for Lispy functions.
trait Fun {
/// Calls this function with provided arguments and environment. Returns `Lval` as a result of evaluation.
///
/// # Arguments
///
/// * `sexpr` - An S-Expression that represents a function to be called
/// * `env` - Callee's environment
fn call(self, env: &mut SharedEnv, sexpr: Lval) -> Result<Lval>;
}
/// Respresents a built-in function.
#[derive(Clone)]
pub struct Builtin {
name: &'static str,
func: BuiltinFn,
}
impl PartialEq for Builtin {
fn eq(&self, other: &Self) -> bool {
// FIXME
// For builtin functions we have to also compare function pointer. It's a bit tricky to do in
// Rust for many reasons and I'm not even sure this trick works properly.
self.name == other.name
&& self.func as *const BuiltinFn as usize == other.func as *const BuiltinFn as usize
}
}
impl Fun for Builtin {
fn call(self, env: &mut SharedEnv, expr: Lval) -> Result<Lval> {
debug!("Calling {}", self.name);
(self.func)(expr, env)
}
}
/// Respresents a user-defined lambda function.
#[derive(Clone, PartialEq)]
pub struct Lambda {
env: SharedEnv,
formals: Box<Lval>,
body: Box<Lval>,
}
impl Fun for Lambda {
fn call(mut self, env: &mut SharedEnv, mut expr: Lval) -> Result<Lval> {
debug!("Calling a lambda");
let total = self.formals.len();
let given = expr.len();
while !expr.is_empty() {
// If there are still arguments, but we exhausted all the formals
// - return an error
if self.formals.is_empty() {
return Err(LispyError::InvalidArgNum("Fun", total, given));
}
let sym = self.formals.pop(0);
// To handle variable arguments we have to convert all leftover arguments
// into a list and store it in local environment under the name that follows
// '&'. Then we can exit the loop.
if sym.as_symbol() == "&" {
if self.formals.len() != 1 {
return Err(LispyError::InvalidFormat(
"Fun format is invalid. Symbol '&' not followed by single symbol.",
));
}
let next_sym = self.formals.pop(0);
self.env
.borrow_mut()
.put(&next_sym.as_symbol(), expr.into_qexpr());
break;
}
// Bind the argument into function's environment
self.env.borrow_mut().put(sym.as_symbol(), expr.pop(0));
}
// In case function accepts variable arguments but they were not yet
// specified we should bind an empty list instead.
if !self.formals.is_empty() && self.formals.peek(0).as_symbol() == "&" {
if self.formals.len() != 2 {
return Err(LispyError::InvalidFormat(
"Fun format is invalid. Symbol '&' not followed by a single symbol.",
));
}
self.formals.pop(0);
env.borrow_mut()
.put(self.formals.pop(0).as_symbol(), Lval::qexpr());
}
// If we managed to bind all the arguments we can now evaluate this function.
// If not we just return an updated function.
if self.formals.is_empty() {
self.env.borrow_mut().parent = Some(Rc::clone(env));
self.body.into_sexpr().eval(&mut self.env)
} else {
Ok(Lval::Fun(LvalFun::Lambda(self)))
}
}
}
/// Assert-like macros similar to those defined in BuildYourOwnLisp book.
/// They would return `LispyError` in case assertion fails. This is C-ish
/// way if doing things, but I wanted to follow the book closely, to
/// begin with.
/// Checks if lval contains an expression with correct number of arguments
macro_rules! lassert_num {
($name:expr, $lval:ident, $num:expr) => {
match &$lval {
Lval::SExpr(cells) | Lval::QExpr(cells) => {
if cells.len() != $num {
return Err(LispyError::InvalidArgNum($name, $num, cells.len()));
}
}
_ => unreachable!(),
}
};
}
/// Checks if lval contains an non-empty expression
macro_rules! lassert_not_empty {
($name:expr, $lval:ident) => {
match &$lval {
Lval::SExpr(cells) | Lval::QExpr(cells) => {
if cells.is_empty() {
return Err(LispyError::EmptyList($name));
}
}
_ => unreachable!(),
}
};
}
/// Checks if lval is of expected type
macro_rules! lassert_type {
($name:expr, $lval:ident, $($type:pat)|+ ) => {
match &$lval {
$($type)|+ => {}
_ => {
return Err(LispyError::InvalidType(
$name,
stringify!($($type)|+),
$lval.to_string(),
))
}
}
};
}
/// A wrapper type for Lispy function
#[derive(Clone, PartialEq)]
pub enum LvalFun {
Builtin(Builtin),
Lambda(Lambda),
}
/// Represents Lispy value. The main data structure our Lispy is built on.
#[derive(Clone, PartialEq)]
pub enum Lval {
Boolean(bool),
Integer(i64),
Float(f64),
Symbol(String),
String(String),
Fun(LvalFun),
SExpr(Vec<Lval>),
QExpr(Vec<Lval>),
Exit,
}
impl fmt::Display for Lval {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self {
Lval::Boolean(x) => write!(f, "{}", x),
Lval::Integer(x) => write!(f, "{}", x),
Lval::Float(x) => write!(f, "{}", x),
Lval::Symbol(sym) => write!(f, "{}", sym),
Lval::String(string) => write!(f, "\"{}\"", string),
Lval::Fun(LvalFun::Builtin(builtin)) => write!(f, "<builtin>: {}", builtin.name),
Lval::Fun(LvalFun::Lambda(lambda)) => write!(f, "(lambda \nbody: {})", lambda.body),
Lval::SExpr(v) => {
write!(f, "(")?;
for (index, lval) in v.iter().enumerate() {
write!(f, "{}", lval)?;
if index != v.len() - 1 {
write!(f, " ")?;
}
}
write!(f, ")")
}
Lval::QExpr(v) => {
write!(f, "{{")?;
for (index, lval) in v.iter().enumerate() {
write!(f, "{}", lval)?;
if index != v.len() - 1 {
write!(f, " ")?;
}
}
write!(f, "}}")
}
Lval::Exit => write!(f, "exit"),
}
}
}
impl fmt::Debug for Lval {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self)
}
}
impl Lval {
/// Returns the underlying number representation if the type is
/// `Lval::Integer`. Will panic otherwise.
fn as_integer(&self) -> i64 {
match self {
Lval::Integer(num) => *num,
_ => unreachable!(),
}
}
/// Returns a reference to the underlying symbol representation if the type is
/// `Lval::Symbol`. Will panic otherwise.
fn as_symbol(&self) -> &str {
match self {
Lval::Symbol(ref sym) => sym,
_ => unreachable!(),
}
}
/// Converts this `Lval` into an S-Expression, preserving internal structure. In case `self` is not an expression
/// - returns an empty S-Expression.
fn into_sexpr(self) -> Lval {
match self {
Lval::QExpr(cells) => Lval::SExpr(cells),
Lval::SExpr(_) => self,
_ => Lval::SExpr(vec![]),
}
}
/// Converts this `Lval` into a Q-Expression, preserving internal structure. In case `self` is not an expression
/// - returns an empty Q-Expression.
fn into_qexpr(self) -> Lval {
match self {
Lval::SExpr(cells) => Lval::QExpr(cells),
Lval::QExpr(_) => self,
_ => Lval::QExpr(vec![]),
}
}
/// Returns a reference to a cell located at `index`. Panics in case `self` is not an expression or index is out
/// of bounds.
fn peek(&self, index: usize) -> &Lval {
match self {
Lval::SExpr(cells) | Lval::QExpr(cells) => &cells[index],
_ => unreachable!(),
}
}
/// Removes and returns a cell located at `index`. Panics in case `self` is not an expression or index is out
/// of bounds.
fn pop(&mut self, index: usize) -> Lval {
match self {
Lval::SExpr(cells) | Lval::QExpr(cells) => cells.remove(index),
_ => unreachable!(),
}
}
/// Inserts a cell at `index` and shift other cells to right. Panics in case `self` is not an expression.
fn insert(&mut self, lval: Lval, index: usize) {
match self {
Lval::SExpr(cells) | Lval::QExpr(cells) => cells.insert(index, lval),
_ => unreachable!(),
}
}
/// Removes and returns a cell located at `index`. Consumes `self`.
/// Panics in case `self` is not an expression or index is out of bounds.
fn take(mut self, i: usize) -> Lval {
self.pop(i)
}
/// Returns number of cells in `self`. Panics in case `self` is not an expression.
fn len(&self) -> usize {
match self {
Lval::SExpr(cells) | Lval::QExpr(cells) => cells.len(),
_ => unreachable!(),
}
}
/// Returns `true` if `self` contains no cells. Panics in case `self` is not an expression.
fn is_empty(&self) -> bool {
self.len() == 0
}
/// Joins `self` and `other` expression together. Consumes `self`, `other` and returns new `Lval`.
/// Panics is either argument is not an expression.
fn join(self, mut other: Self) -> Lval {
let mut lval = self;
while !other.is_empty() {
lval = lval.add(other.pop(0));
}
lval
}
/// Adds `val` to `self` expression. Consumes `self`, `val` and returns new `Lval`.
/// Panics is either argument is not an expression.
pub fn add(self, val: Self) -> Lval {
let mut lval = self;
match &mut lval {
Lval::QExpr(ref mut cells) | Lval::SExpr(ref mut cells) => cells.push(val),
_ => unreachable!(),
}
lval
}
/// Calls `self` as a function. Consumes `self` and returns result of the execution.
///
/// # Arguments
///
/// * `env` - Callee's environment
/// * `args` - An S-Expression containing arguments, this function should be called with
fn call(self, env: &mut SharedEnv, args: Lval) -> Result<Lval> {
match self {
Lval::Fun(LvalFun::Builtin(builtin)) => builtin.call(env, args),
Lval::Fun(LvalFun::Lambda(lambda)) => lambda.call(env, args),
_ => unreachable!(),
}
}
/// Evaluates `self` and returns new `Lval` as a result. Consumes `self`.
pub fn eval(self, env: &mut SharedEnv) -> Result<Lval> {
debug!("eval: {}", self);
match self {
Lval::Symbol(sym) => env.borrow().get(&sym),
Lval::SExpr(ref cells) if cells.is_empty() => Ok(self),
Lval::SExpr(cells) => {
let mut aux = vec![];
for cell in cells {
aux.push(cell.eval(env)?);
}
let mut cells = aux;
// If there's only one argument - evaluate it and return
// the result of evaluation
if cells.len() == 1 {
return cells.remove(0).eval(env);
}
// Otherwise it's an either builtin or a user-defined function
let func = cells.remove(0);
lassert_type!("S-Expression", func, Lval::Fun(_));
func.call(env, Lval::SExpr(cells))
}
_ => Ok(self),
}
}
/// Constructs a new `Lval` holding an S-Expression
pub fn sexpr() -> Lval {
Lval::SExpr(vec![])
}
/// Constructs a new `Lval` holding an Q-Expression
pub fn qexpr() -> Lval {
Lval::QExpr(vec![])
}
/// Constructs a new `Lval` holding a symbol
pub fn symbol(sym: &str) -> Lval {
Lval::Symbol(sym.to_owned())
}
/// Constructs a new `Lval` holding a number
pub fn integer(num: i64) -> Lval {
Lval::Integer(num)
}
/// Constructs a new `Lval` holding a built-in function
pub fn builtin(name: &'static str, func: BuiltinFn) -> Lval {
Lval::Fun(LvalFun::Builtin(Builtin { name, func }))
}
/// Constructs a new `Lval` holding a user-defined function
pub fn lambda(formals: Lval, body: Lval) -> Lval {
Lval::Fun(LvalFun::Lambda(Lambda {
env: LEnv::new_shared(),
formals: Box::new(formals),
body: Box::new(body),
}))
}
/// Constructs a new `Lval` holding a `bool` value
pub fn boolean(val: bool) -> Lval {
Lval::Boolean(val)
}
/// Returns a reference to the underlying `bool` representation if the type is
/// `Lval::Boolean`. Will panic otherwise.
fn as_boolean(&self) -> &bool {
match self {
Lval::Boolean(val) => val,
_ => unreachable!(),
}
}
/// Converts this `Lval` into a boolean, In case `self` is a boolean or a number
/// - panics.
fn into_boolean(self) -> Lval {
match self {
Lval::Boolean(_) => self,
Lval::Integer(num) => Lval::boolean(num != 0),
_ => unreachable!(),
}
}
/// Constructs a new `Lval` holding a string
pub fn string(string: &str) -> Lval {
Lval::String(string.to_owned())
}
/// Returns a reference to the underlying `String` representation if the type
/// is `Lval::String`. Will panic otherwise.
fn as_string(&self) -> &String {
match self {
Lval::String(string) => string,
_ => unreachable!(),
}
}
/// Constructs a new `Lval` holding a `f64`
pub fn float(val: f64) -> Lval {
Lval::Float(val)
}
/// Returns the underlying number representation if the type is
/// `Lval::Float`. Returns the underlying integer casted as float
/// if the type is `Lval::Integer`. Will panic otherwise.
fn as_float(&self) -> f64 {
match self {
Lval::Float(num) => *num,
Lval::Integer(num) => *num as f64,
_ => unreachable!(),
}
}
/// Returns `true` if the underlying type is `Lval::Float`
fn is_float(&self) -> bool {
match self {
Lval::Float(_) => true,
_ => false,
}
}
}
/// Built-in functions.
/// All of those functions accept two arguments:
/// - lval. It should always be an S-Expression containing other expressions or operands,
/// the builtin function should work with;
/// - env. A mutable reference to the environment, in some cases may be used to look up
/// a symbol or to define a symbol.
/// Evaluates `lval` and returns `Lval` that holds the evaluation result
pub fn builtin_eval(lval: Lval, env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("eval", lval, 1);
let expr = lval.take(0);
lassert_type!("eval", expr, Lval::QExpr(_));
expr.into_sexpr().eval(env)
}
/// Converts `lval` into a list (Q-Expression)
pub fn builtin_list(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
Ok(lval.into_qexpr())
}
/// Returns a Q-Expression that holds the head of the list, provided in `lval`
pub fn builtin_head(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("head", lval, 1);
let list = lval.take(0);
lassert_type!("head", list, Lval::QExpr(_));
lassert_not_empty!("head", list);
Ok(Lval::qexpr().add(list.take(0)))
}
/// Returns a Q-Expression that holds the tail of the list, provided in `lval`
pub fn builtin_tail(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("tail", lval, 1);
let mut list = lval.take(0);
lassert_type!("tail", list, Lval::QExpr(_));
lassert_not_empty!("tail", list);
list.pop(0);
Ok(list)
}
/// Joins two Q-Expressions together and returns the new `Lval`
pub fn builtin_join(mut lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
for index in 0..lval.len() {
let expr = lval.peek(index);
lassert_type!("join", expr, Lval::QExpr(_));
}
let mut result = lval.pop(0);
while !lval.is_empty() {
let other = lval.pop(0);
result = result.join(other);
}
Ok(result)
}
/// Creates a new `Lval` that holds two Q-Expressions provided in `lval`
pub fn builtin_cons(mut lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("cons", lval, 2);
let val = lval.pop(0);
let mut list = lval.pop(0);
list.insert(val, 0);
Ok(list)
}
/// Returns `lval` without the last element
pub fn builtin_init(mut lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("init", lval, 1);
let mut list = lval.pop(0);
list.pop(list.len() - 1);
Ok(list)
}
/// Performs checked integer operations where applicable and returns
/// the result in `Lval`
fn integer_op(x: i64, y: i64, op: &'static str) -> Result<Lval> {
let result;
match op {
"+" => {
result = x.checked_add(y).ok_or_else(|| LispyError::Overflow)?;
}
"-" => {
result = x.checked_sub(y).ok_or_else(|| LispyError::Overflow)?;
}
"*" => {
result = x.checked_mul(y).ok_or_else(|| LispyError::Overflow)?;
}
"^" => {
let y = u32::try_from(y)?;
result = i64::checked_pow(x, y).ok_or_else(|| LispyError::Overflow)?;
}
"min" => {
result = x.min(y);
}
"max" => {
result = x.max(y);
}
"%" => {
if y == 0 {
return Err(LispyError::DivisionByZero);
}
result = x.checked_rem(y).ok_or_else(|| LispyError::Overflow)?;
}
_ => unreachable!(),
}
Ok(Lval::integer(result))
}
/// Performs floating point operations where applicable and returns
/// the result in `Lval`
fn float_op(x: f64, y: f64, op: &'static str) -> Result<Lval> {
let result;
match op {
"+" => {
result = x + y;
}
"-" => {
result = x - y;
}
"*" => {
result = x * y;
}
"/" => {
if y == 0.0f64 {
return Err(LispyError::DivisionByZero);
} else {
result = x / y;
}
}
"^" => {
result = f64::powf(x, y.into());
}
"min" => result = x.min(y),
"max" => result = x.max(y),
"%" => {
if y == 0.0f64 {
return Err(LispyError::DivisionByZero);
} else {
result = x % y;
}
}
_ => unreachable!(),
}
Ok(Lval::float(result))
}
fn builtin_op(mut lval: Lval, op: &'static str) -> Result<Lval> {
// We can only perform integer operations if:
// - it's not a division;
// - all operands are integers.
let mut int_op = if op == "/" { false } else { true };
for index in 0..lval.len() {
let number = lval.peek(index);
lassert_type!(op, number, Lval::Integer(_) | Lval::Float(_));
// If it least one argument is float - we should work with float.
if number.is_float() {
int_op = false;
}
}
let mut result = lval.pop(0);
if op == "-" && lval.is_empty() {
if int_op {
result = Lval::integer(-result.as_integer());
} else {
result = Lval::float(-result.as_float());
};
}
while !lval.is_empty() {
let next = lval.pop(0);
result = if int_op {
integer_op(result.as_integer(), next.as_integer(), op)?
} else {
float_op(result.as_float(), next.as_float(), op)?
}
}
Ok(result)
}
/// Returns a new `Lval` that holds a sum of two numbers provided in `lval`
pub fn builtin_add(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_op(lval, "+")
}
/// Returns a new `Lval` that holds a difference of two numbers provided in `lval`
pub fn builtin_sub(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_op(lval, "-")
}
/// Returns a new `Lval` that holds a product of two numbers provided in `lval`
pub fn builtin_mul(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_op(lval, "*")
}
/// Returns a new `Lval` that holds a quotient of two numbers provided in `lval`
pub fn builtin_div(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_op(lval, "/")
}
/// Returns a new `Lval` that holds a pow(first,second) provided in `lval`
pub fn builtin_pow(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_op(lval, "^")
}
/// Returns a new `Lval` that holds a remainder of two numbers provided in `lval`
pub fn builtin_rem(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_op(lval, "%")
}
/// Returns a new `Lval` that holds a minimum of two numbers provided in `lval`
pub fn builtin_min(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_op(lval, "min")
}
/// Returns a new `Lval` that holds a maximum of two numbers provided in `lval`
pub fn builtin_max(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_op(lval, "max")
}
fn builtin_var(mut lval: Lval, env: &mut SharedEnv, func: &'static str) -> Result<Lval> {
let mut symbols = lval.pop(0);
lassert_type!(func, symbols, Lval::QExpr(_));
for index in 0..symbols.len() {
let sym = symbols.peek(index);
lassert_type!(func, sym, Lval::Symbol(_));
}
lassert_num!(func, symbols, lval.len());
while !symbols.is_empty() {
let sym = symbols.pop(0);
let arg = lval.pop(0);
match func {
"def" => env.borrow_mut().def(sym.as_symbol(), arg),
"=" => env.borrow_mut().put(sym.as_symbol(), arg),
_ => unreachable!(),
}
}
Ok(Lval::sexpr())
}
/// Bounds a symbol, described in `lval`, into the global `env` environment. Returns and empty S-Expression.
pub fn builtin_def(lval: Lval, env: &mut SharedEnv) -> Result<Lval> {
builtin_var(lval, env, "def")
}
/// Bounds a symbol, described in `lval`, into the local `env` environment. Returns and empty S-Expression.
pub fn builtin_put(lval: Lval, env: &mut SharedEnv) -> Result<Lval> {
builtin_var(lval, env, "=")
}
/// Returns `Lval` that contains a lambda, described in `lval`.
pub fn builtin_lambda(mut lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("\\", lval, 2);
let formals = lval.pop(0);
let body = lval.pop(0);
lassert_type!("\\", formals, Lval::QExpr(_));
lassert_type!("\\", body, Lval::QExpr(_));
for index in 0..formals.len() {
let sym = formals.peek(index);
lassert_type!("\\", sym, Lval::Symbol(_));
}
Ok(Lval::lambda(formals, body))
}
/// Returns `Lval::Integer(1.0)` if the first number, provided in `lval` is bigger than the second.
pub fn builtin_gt(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_ord(lval, ">")
}
/// Returns `Lval::Integer(1.0)` if the first number, provided in `lval` is smaller than the second.
pub fn builtin_lt(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_ord(lval, "<")
}
/// Returns `Lval::Integer(1.0)` if the first number, provided in `lval` is bigger or equal than/to the second.
pub fn builtin_ge(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_ord(lval, ">=")
}
/// Returns `Lval::Integer(1.0)` if the first number, provided in `lval` is less or equal than/to the second.
pub fn builtin_le(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_ord(lval, "<=")
}
fn builtin_ord(mut lval: Lval, ord: &'static str) -> Result<Lval> {
lassert_num!(ord, lval, 2);
let first = lval.pop(0);
lassert_type!(ord, first, Lval::Integer(_) | Lval::Float(_));
let second = lval.pop(0);
lassert_type!(ord, second, Lval::Integer(_) | Lval::Float(_));
// It's "okay" to cast integer to float in this case as f64 implements
// PartialOrd.
// TODO Revisit this strategy after I read:
// https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
let first = first.as_float();
let second = second.as_float();
match ord {
">" => Ok(Lval::boolean(first > second)),
"<" => Ok(Lval::boolean(first < second)),
">=" => Ok(Lval::boolean(first >= second)),
"<=" => Ok(Lval::boolean(first <= second)),
_ => unreachable!(),
}
}
/// Returns `Lval::Integer(1.0)` if the first `Lval`, provided in `lval` is equal to the second.
pub fn builtin_eq(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_cmp(lval, "==")
}
/// Returns `Lval::Integer(1.0)` if the first `Lval`, provided in `lval` is not equal to the second.
pub fn builtin_ne(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
builtin_cmp(lval, "!=")
}
fn builtin_cmp(mut lval: Lval, op: &'static str) -> Result<Lval> {
lassert_num!(op, lval, 2);
let first = lval.pop(0);
let second = lval.pop(0);
match op {
"==" => Ok(Lval::boolean(first == second)),
"!=" => Ok(Lval::boolean(first != second)),
_ => unreachable!(),
}
}
/// Evaluates one of the two expressions, provided in `lval`, depending on the condition provided in `lval`.
pub fn builtin_if(mut lval: Lval, env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("if", lval, 3);
let cond = lval.pop(0);
let on_true = lval.pop(0);
let on_false = lval.pop(0);
lassert_type!("if", cond, Lval::Integer(_) | Lval::Boolean(_));
lassert_type!("if", on_true, Lval::QExpr(_));
lassert_type!("if", on_false, Lval::QExpr(_));
let cond = cond.into_boolean();
if *cond.as_boolean() {
on_true.into_sexpr().eval(env)
} else {
on_false.into_sexpr().eval(env)
}
}
/// Returns Lval::Integer(1.0) if at least one of the two operands, provided in `lval`, evaluates
/// to true
pub fn builtin_or(mut lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("||", lval, 2);
while !lval.is_empty() {
let cond = lval.pop(0);
lassert_type!("or", cond, Lval::Integer(_) | Lval::Boolean(_));
let cond = cond.into_boolean();
if *cond.as_boolean() {
return Ok(cond);
}
}
Ok(Lval::boolean(false))
}
/// Returns Lval::Integer(1.0) if both of the two operands, provided in `lval`, evaluate
/// to true
pub fn builtin_and(mut lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("&&", lval, 2);
while !lval.is_empty() {
let cond = lval.pop(0);
lassert_type!("and", cond, Lval::Integer(_) | Lval::Boolean(_));
let cond = cond.into_boolean();
if !*cond.as_boolean() {
return Ok(cond);
}
}
Ok(Lval::boolean(true))
}
/// Returns a new `Lval` that reverses the logical state of the operand, provided in `lval`
pub fn builtin_not(mut lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("!", lval, 1);
let cond = lval.pop(0);
lassert_type!("!", cond, Lval::Integer(_) | Lval::Boolean(_));
let cond = !cond.into_boolean().as_boolean();
Ok(Lval::boolean(cond))
}
/// Loads and evaluates a file from the path, passed via `Lval`. Returns an empty S-Expression.
pub fn builtin_load(mut lval: Lval, env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("load", lval, 1);
let path = lval.pop(0);
lassert_type!("load", path, Lval::String(_));
let input = fs::read_to_string(path.as_string())?;
let mut lval = parser::parse(&input)?;
for _ in 0..lval.len() {
lval.pop(0).eval(env)?;
}
Ok(Lval::sexpr())
}
/// Outputs its arguments, passed via `lval` to the stdout, using `print!()`
pub fn builtin_print(lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
for index in 0..lval.len() {
print!("{}", lval.peek(index));
print!(" ");
}
println!("");
Ok(Lval::sexpr())
}
/// Constructs an error from the first argument and returns it.
pub fn builtin_error(mut lval: Lval, _env: &mut SharedEnv) -> Result<Lval> {
lassert_num!("error", lval, 1);
let string = lval.pop(0);
lassert_type!("error", string, Lval::String(_));
Err(LispyError::BuiltinError(string.as_string().to_string()))
}
/// Registers all supported built-in functions and types into the provided environment.
pub fn add_builtins(lenv: &mut LEnv) {
lenv.add_builtin("list", builtin_list);
lenv.add_builtin("join", builtin_join);
lenv.add_builtin("tail", builtin_tail);
lenv.add_builtin("head", builtin_head);
lenv.add_builtin("init", builtin_init);
lenv.add_builtin("cons", builtin_cons);
lenv.add_builtin("eval", builtin_eval);
lenv.add_builtin("+", builtin_add);
lenv.add_builtin("-", builtin_sub);
lenv.add_builtin("/", builtin_div);
lenv.add_builtin("*", builtin_mul);
lenv.add_builtin("%", builtin_rem);
lenv.add_builtin("^", builtin_pow);
lenv.add_builtin("min", builtin_min);
lenv.add_builtin("max", builtin_max);
lenv.add_builtin("=", builtin_put);
lenv.add_builtin("def", builtin_def);
lenv.add_builtin("\\", builtin_lambda);
lenv.add_builtin("==", builtin_eq);
lenv.add_builtin("!=", builtin_ne);
lenv.add_builtin(">", builtin_gt);
lenv.add_builtin("<", builtin_lt);
lenv.add_builtin(">=", builtin_ge);
lenv.add_builtin("<=", builtin_le);
lenv.add_builtin("if", builtin_if);
lenv.add_builtin("||", builtin_or);
lenv.add_builtin("&&", builtin_and);
lenv.add_builtin("!", builtin_not);
lenv.add_builtin("load", builtin_load);
lenv.add_builtin("print", builtin_print);
lenv.add_builtin("error", builtin_error);
lenv.put("exit", Lval::Exit);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_builtin_eval() {
let mut env = LEnv::new_shared();
let sexpr = Lval::sexpr().add(Lval::qexpr().add(Lval::integer(1)).add(Lval::integer(2)));
assert!(builtin_eval(sexpr, &mut env).is_err());
env.borrow_mut().add_builtin("+", builtin_add);
let sexpr = Lval::sexpr().add(
Lval::qexpr()
.add(Lval::symbol("+"))
.add(Lval::integer(1))
.add(Lval::integer(2)),
);
assert_eq!(builtin_eval(sexpr, &mut env), Ok(Lval::integer(3)));
}
#[test]
fn test_builtin_list() {
let mut env = LEnv::new_shared();
let sexpr = Lval::sexpr().add(Lval::integer(1)).add(Lval::integer(2));
// Test that an S-Expression gets converted into a QExpr and becomes a list
assert_eq!(
builtin_list(sexpr.clone(), &mut env),
Ok(sexpr.into_qexpr())
);
// Test that only Lval other than S-Expression of Q-Expression becomes an
// empty Q-Expression (list)
assert_eq!(builtin_list(Lval::integer(42), &mut env), Ok(Lval::qexpr()));
}
#[test]
fn test_builtin_head() {
let mut env = LEnv::new_shared();
// Test that 'head' return a list that contains the
// first element
let list = Lval::qexpr().add(Lval::integer(1)).add(Lval::integer(2));
let sexpr = Lval::sexpr().add(list.clone());
assert_eq!(
builtin_head(sexpr, &mut env),
Ok(Lval::qexpr().add(Lval::integer(1)))
);
// Test that 'head' return an error if the S-Expression
// doesn't contain exactly one Q-Expression
let sexpr = Lval::sexpr();
assert!(matches!(
builtin_head(sexpr, &mut env),
Err(LispyError::InvalidArgNum("head", 1, _))
));
let sexpr = Lval::sexpr().add(Lval::qexpr()).add(Lval::qexpr());
assert!(matches!(
builtin_head(sexpr, &mut env),
Err(LispyError::InvalidArgNum("head", 1, _))
));
// Test that 'head' returns an error if an empty list
// was provided
let sexpr = Lval::sexpr().add(Lval::qexpr());
assert!(matches!(
builtin_head(sexpr, &mut env),
Err(LispyError::EmptyList("head"))
));
}
#[test]
fn test_builtin_tail() {
let mut env = LEnv::new_shared();
let mut list = Lval::qexpr()
.add(Lval::integer(1))
.add(Lval::integer(2))
.add(Lval::integer(3));
let sexpr = Lval::sexpr().add(list.clone());
list.pop(0);
assert_eq!(builtin_tail(sexpr, &mut env), Ok(list));
// Test that 'tail' return an error if the S-Expression
// doesn't contain exactly one Q-Expression
let sexpr = Lval::sexpr();
assert!(matches!(
builtin_tail(sexpr, &mut env),
Err(LispyError::InvalidArgNum("tail", 1, _))
));
let sexpr = Lval::sexpr().add(Lval::qexpr()).add(Lval::qexpr());
assert!(matches!(
builtin_tail(sexpr, &mut env),
Err(LispyError::InvalidArgNum("tail", 1, _))
));
// Test that 'tail' returns an error if an empty list
// was provided
let sexpr = Lval::sexpr().add(Lval::qexpr());
assert!(matches!(
builtin_tail(sexpr, &mut env),
Err(LispyError::EmptyList("tail"))
));
}
#[test]
fn test_builtin_join() {
let mut env = LEnv::new_shared();
let list1 = Lval::qexpr()
.add(Lval::integer(1))
.add(Lval::integer(2))
.add(Lval::integer(3));
let list2 = Lval::qexpr()
.add(Lval::integer(4))
.add(Lval::integer(5))
.add(Lval::integer(6));
let sexpr = Lval::sexpr().add(list1.clone()).add(list2.clone());
let list = list1.join(list2);
assert_eq!(builtin_join(sexpr, &mut env), Ok(list));
let sexpr = Lval::sexpr().add(Lval::integer(42));
assert!(matches!(
builtin_join(sexpr, &mut env),
Err(LispyError::InvalidType("join", _, _))
));
}
#[test]
fn test_builtin_cons() {
let mut env = LEnv::new_shared();
let list = Lval::qexpr()
.add(Lval::integer(1))
.add(Lval::integer(2))
.add(Lval::integer(3));
let sexpr = Lval::sexpr().add(Lval::integer(1)).add(list.clone());
let list = Lval::qexpr().add(Lval::integer(1)).join(list);
assert_eq!(builtin_cons(sexpr, &mut env), Ok(list));
let sexpr = Lval::sexpr().add(Lval::integer(1));
assert!(matches!(
builtin_cons(sexpr, &mut env),
Err(LispyError::InvalidArgNum("cons", 2, _))
));
}
#[test]
fn test_builtin_init() {
let mut env = LEnv::new_shared();
let mut list = Lval::qexpr()
.add(Lval::integer(1))
.add(Lval::integer(2))
.add(Lval::integer(3));
let sexpr = Lval::sexpr().add(list.clone());
list.pop(list.len() - 1);
assert_eq!(builtin_init(sexpr, &mut env), Ok(list));
let sexpr = Lval::sexpr();
assert!(matches!(
builtin_init(sexpr, &mut env),
Err(LispyError::InvalidArgNum("init", 1, _))
));
}
#[test]
fn test_builtin_ops() {
let mut env = LEnv::new_shared();
let args = Lval::sexpr().add(Lval::integer(2)).add(Lval::integer(4));
// integers
assert_eq!(builtin_add(args.clone(), &mut env), Ok(Lval::integer(6)));
assert_eq!(builtin_sub(args.clone(), &mut env), Ok(Lval::integer(-2)));
assert_eq!(builtin_mul(args.clone(), &mut env), Ok(Lval::integer(8)));
assert_eq!(builtin_div(args.clone(), &mut env), Ok(Lval::float(0.5)));
assert_eq!(builtin_rem(args.clone(), &mut env), Ok(Lval::integer(2)));
assert_eq!(builtin_pow(args.clone(), &mut env), Ok(Lval::integer(16)));
assert_eq!(builtin_min(args.clone(), &mut env), Ok(Lval::integer(2)));
assert_eq!(builtin_max(args.clone(), &mut env), Ok(Lval::integer(4)));
assert_eq!(
builtin_sub(Lval::sexpr().add(Lval::integer(-2)), &mut env),
Ok(Lval::integer(2))
);
// float
let args = Lval::sexpr().add(Lval::integer(2)).add(Lval::float(4.0));
assert_eq!(builtin_add(args.clone(), &mut env), Ok(Lval::float(6.0)));
assert_eq!(builtin_sub(args.clone(), &mut env), Ok(Lval::float(-2.0)));
assert_eq!(builtin_mul(args.clone(), &mut env), Ok(Lval::float(8.0)));
assert_eq!(builtin_div(args.clone(), &mut env), Ok(Lval::float(0.5)));
assert_eq!(builtin_rem(args.clone(), &mut env), Ok(Lval::float(2.0)));
assert_eq!(builtin_pow(args.clone(), &mut env), Ok(Lval::float(16.0)));
assert_eq!(builtin_min(args.clone(), &mut env), Ok(Lval::float(2.0)));
assert_eq!(builtin_max(args.clone(), &mut env), Ok(Lval::float(4.0)));
assert_eq!(
builtin_sub(Lval::sexpr().add(Lval::float(-2.0)), &mut env),
Ok(Lval::float(2.0))
);
assert!(matches!(
builtin_div(
Lval::sexpr().add(Lval::integer(1)).add(Lval::integer(0)),
&mut env
),
Err(LispyError::DivisionByZero)
));
assert!(matches!(
builtin_rem(
Lval::sexpr().add(Lval::integer(1)).add(Lval::integer(0)),
&mut env
),
Err(LispyError::DivisionByZero)
));
assert!(matches!(
builtin_pow(
Lval::sexpr()
.add(Lval::integer(1))
.add(Lval::integer(std::i64::MAX)),
&mut env
),
Err(LispyError::ConversionError(_))
));
assert!(matches!(
builtin_pow(
Lval::sexpr()
.add(Lval::integer(std::i64::MAX))
.add(Lval::integer(std::i32::MAX as i64)),
&mut env
),
Err(LispyError::Overflow)
));
}
#[test]
fn test_builtin_def() {
let mut env = LEnv::new_shared();
let sexpr = Lval::sexpr()
.add(Lval::qexpr().add(Lval::symbol("x")))
.add(Lval::integer(42));
assert_eq!(builtin_def(sexpr, &mut env), Ok(Lval::sexpr()));
let sexpr = Lval::sexpr()
.add(Lval::qexpr().add(Lval::integer(1)))
.add(Lval::integer(42));
assert!(matches!(
builtin_def(sexpr, &mut env),
Err(LispyError::InvalidType("def", _, _))
));
}
#[test]
fn test_builtin_lambda() {
let mut env = LEnv::new_shared();
let formals = Lval::qexpr().add(Lval::symbol("x"));
let body = Lval::qexpr().add(Lval::qexpr());
assert!(matches!(
builtin_lambda(Lval::sexpr(), &mut env),
Err(LispyError::InvalidArgNum("\\", 2, _))
));
// Formals should be a Q-Expression
assert!(matches!(
builtin_lambda(
Lval::sexpr().add(Lval::integer(1)).add(body.clone()),
&mut env
),
Err(LispyError::InvalidType("\\", _, _))
));
// Body should be a Q-Expression
assert!(matches!(
builtin_lambda(
Lval::sexpr().add(formals.clone()).add(Lval::integer(1)),
&mut env
),
Err(LispyError::InvalidType("\\", _, _))
));
let lambda = builtin_lambda(
Lval::sexpr().add(formals.clone()).add(body.clone()),
&mut env,
);
if let Ok(Lval::Fun(LvalFun::Lambda(lambda))) = lambda {
assert_eq!(formals, *lambda.formals);
assert_eq!(body, *lambda.body);
}
}
#[test]
fn test_builtin_ord() {
let mut env = LEnv::new_shared();
let args = Lval::qexpr().add(Lval::integer(2)).add(Lval::integer(1));
assert_eq!(builtin_gt(args.clone(), &mut env), Ok(Lval::boolean(true)));
assert_eq!(builtin_lt(args.clone(), &mut env), Ok(Lval::boolean(false)));
assert_eq!(builtin_ge(args.clone(), &mut env), Ok(Lval::boolean(true)));
assert_eq!(builtin_le(args.clone(), &mut env), Ok(Lval::boolean(false)));
assert!(matches!(
builtin_ge(
Lval::qexpr()
.add(Lval::symbol("x"))
.add(Lval::boolean(true)),
&mut env
),
Err(LispyError::InvalidType(">=", _, _))
));
}
#[test]
fn test_builtin_cmp() {
let mut env = LEnv::new_shared();
assert_eq!(
builtin_eq(
Lval::qexpr().add(Lval::qexpr()).add(Lval::qexpr()),
&mut env
),
Ok(Lval::boolean(true))
);
assert_eq!(
builtin_eq(
Lval::qexpr().add(Lval::symbol("x")).add(Lval::symbol("x")),
&mut env
),
Ok(Lval::boolean(true))
);
assert_eq!(
builtin_eq(
Lval::qexpr().add(Lval::integer(5)).add(Lval::integer(5)),
&mut env
),
Ok(Lval::boolean(true))
);
assert_eq!(
builtin_ne(
Lval::qexpr().add(Lval::integer(1)).add(Lval::integer(2)),
&mut env
),
Ok(Lval::boolean(true))
);
assert_eq!(
builtin_ne(
Lval::qexpr().add(Lval::symbol("x")).add(Lval::integer(2)),
&mut env
),
Ok(Lval::boolean(true))
);
assert!(matches!(
builtin_ne(Lval::qexpr().add(Lval::symbol("x")), &mut env),
Err(LispyError::InvalidArgNum("!=", 2, _))
));
}
#[test]
fn test_builtin_if() {
let mut env = LEnv::new_shared();
assert!(matches!(
builtin_if(Lval::qexpr(), &mut env),
Err(LispyError::InvalidArgNum("if", 3, _))
));
assert_eq!(
builtin_if(
Lval::qexpr()
.add(Lval::integer(true as i64))
.add(Lval::qexpr().add(Lval::integer(42)))
.add(Lval::qexpr()),
&mut env
),
Ok(Lval::integer(42))
);
}
#[test]
fn test_builtin_or() {
let mut env = LEnv::new_shared();
assert!(matches!(
builtin_or(Lval::qexpr(), &mut env),
Err(LispyError::InvalidArgNum("||", 2, _))
));
assert_eq!(
builtin_or(
Lval::qexpr()
.add(Lval::integer(false as i64))
.add(Lval::integer(true as i64)),
&mut env
),
Ok(Lval::boolean(true))
);
assert_eq!(
builtin_or(
Lval::qexpr()
.add(Lval::boolean(false))
.add(Lval::boolean(false)),
&mut env
),
Ok(Lval::boolean(false))
);
}
#[test]
fn test_builtin_and() {
let mut env = LEnv::new_shared();
assert!(matches!(
builtin_and(Lval::qexpr(), &mut env),
Err(LispyError::InvalidArgNum("&&", 2, _))
));
assert_eq!(
builtin_and(
Lval::qexpr()
.add(Lval::integer(true as i64))
.add(Lval::integer(true as i64)),
&mut env
),
Ok(Lval::boolean(true))
);
assert_eq!(
builtin_and(
Lval::qexpr()
.add(Lval::boolean(true))
.add(Lval::boolean(false)),
&mut env
),
Ok(Lval::boolean(false))
);
}
#[test]
fn test_builtin_not() {
let mut env = LEnv::new_shared();
assert!(matches!(
builtin_not(Lval::qexpr(), &mut env),
Err(LispyError::InvalidArgNum("!", 1, _))
));
assert!(matches!(
builtin_not(Lval::qexpr().add(Lval::symbol("x")), &mut env),
Err(LispyError::InvalidType("!", _, _))
));
assert_eq!(
builtin_not(Lval::qexpr().add(Lval::boolean(true)), &mut env),
Ok(Lval::boolean(false))
);
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![cfg(test)]
use {
cobalt_sw_delivery_registry as metrics,
failure::Error,
fidl_fuchsia_paver as paver,
fidl_fuchsia_pkg::PackageResolverRequestStream,
fidl_fuchsia_sys::{LauncherProxy, TerminationReason},
fuchsia_async as fasync,
fuchsia_component::{
client::AppBuilder,
server::{NestedEnvironment, ServiceFs},
},
fuchsia_zircon::{Status, Vmo},
futures::prelude::*,
parking_lot::Mutex,
std::{
collections::HashMap,
convert::TryInto,
fs::{create_dir, File},
path::{Path, PathBuf},
sync::Arc,
},
tempfile::TempDir,
};
struct TestEnv {
env: NestedEnvironment,
resolver: Arc<MockResolverService>,
paver_service: Arc<MockPaverService>,
reboot_service: Arc<MockRebootService>,
logger_factory: Arc<MockLoggerFactory>,
_test_dir: TempDir,
packages_path: PathBuf,
blobfs_path: PathBuf,
fake_path: PathBuf,
}
impl TestEnv {
fn launcher(&self) -> &LauncherProxy {
self.env.launcher()
}
fn new() -> Self {
Self::new_with_paver_service_call_hook(MockPaverService::hook_always_ok)
}
fn new_with_paver_service_call_hook(
call_hook: impl Fn(&PaverEvent) -> Status + Send + Sync + 'static,
) -> Self {
let mut fs = ServiceFs::new();
let resolver = Arc::new(MockResolverService::new());
let resolver_clone = resolver.clone();
fs.add_fidl_service(move |stream: PackageResolverRequestStream| {
let resolver_clone = resolver_clone.clone();
fasync::spawn(
resolver_clone
.run_resolver_service(stream)
.unwrap_or_else(|e| panic!("error running resolver service: {:?}", e)),
)
});
let paver_service = Arc::new(MockPaverService::new_with_call_hook(call_hook));
let paver_service_clone = paver_service.clone();
fs.add_fidl_service(move |stream| {
let paver_service_clone = paver_service_clone.clone();
fasync::spawn(
paver_service_clone
.run_paver_service(stream)
.unwrap_or_else(|e| panic!("error running paver service: {:?}", e)),
)
});
let reboot_service = Arc::new(MockRebootService::new());
let reboot_service_clone = reboot_service.clone();
fs.add_fidl_service(move |stream| {
let reboot_service_clone = reboot_service_clone.clone();
fasync::spawn(
reboot_service_clone
.run_reboot_service(stream)
.unwrap_or_else(|e| panic!("error running reboot service: {:?}", e)),
)
});
let logger_factory = Arc::new(MockLoggerFactory::new());
let logger_factory_clone = logger_factory.clone();
fs.add_fidl_service(move |stream| {
let logger_factory_clone = logger_factory_clone.clone();
fasync::spawn(
logger_factory_clone
.run_logger_factory(stream)
.unwrap_or_else(|e| panic!("error running logger factory: {:?}", e)),
)
});
let env = fs
.create_salted_nested_environment("systemupdater_env")
.expect("nested environment to create successfully");
fasync::spawn(fs.collect());
let test_dir = TempDir::new().expect("create test tempdir");
let blobfs_path = test_dir.path().join("blob");
create_dir(&blobfs_path).expect("create blob dir");
let packages_path = test_dir.path().join("packages");
create_dir(&packages_path).expect("create packages dir");
let fake_path = test_dir.path().join("fake");
create_dir(&fake_path).expect("create fake stimulus dir");
Self {
env,
resolver,
paver_service,
reboot_service,
logger_factory,
_test_dir: test_dir,
packages_path,
blobfs_path,
fake_path,
}
}
fn register_package(&mut self, name: impl AsRef<str>, merkle: impl AsRef<str>) -> TestPackage {
let name = name.as_ref();
let merkle = merkle.as_ref();
let root = self.packages_path.join(merkle);
create_dir(&root).expect("package to not yet exist");
self.resolver
.mock_package_result(format!("fuchsia-pkg://fuchsia.com/{}", name), Ok(root.clone()));
TestPackage { root }.add_file("meta", merkle)
}
async fn run_system_updater<'a>(
&'a self,
args: SystemUpdaterArgs<'a>,
) -> Result<(), fuchsia_component::client::OutputError> {
let launcher = self.launcher();
let blobfs_dir = File::open(&self.blobfs_path).expect("open blob dir");
let packages_dir = File::open(&self.packages_path).expect("open packages dir");
let fake_dir = File::open(&self.fake_path).expect("open fake stimulus dir");
let mut system_updater = AppBuilder::new(
"fuchsia-pkg://fuchsia.com/systemupdater-tests#meta/system_updater_isolated.cmx",
)
.add_dir_to_namespace("/blob".to_string(), blobfs_dir)
.expect("/blob to mount")
.add_dir_to_namespace("/pkgfs/versions".to_string(), packages_dir)
.expect("/pkgfs/versions to mount")
.add_dir_to_namespace("/fake".to_string(), fake_dir)
.expect("/fake to mount")
.arg(format!("-initiator={}", args.initiator))
.arg(format!("-target={}", args.target));
if let Some(update) = args.update {
system_updater = system_updater.arg(format!("-update={}", update));
}
if let Some(reboot) = args.reboot {
system_updater = system_updater.arg(format!("-reboot={}", reboot));
}
let output = system_updater
.output(launcher)
.expect("system_updater to launch")
.await
.expect("no errors while waiting for exit");
assert_eq!(output.exit_status.reason(), TerminationReason::Exited);
output.ok()
}
}
struct TestPackage {
root: PathBuf,
}
impl TestPackage {
fn add_file(self, path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Self {
std::fs::write(self.root.join(path), contents).expect("create fake package file");
self
}
}
struct SystemUpdaterArgs<'a> {
initiator: &'a str,
target: &'a str,
update: Option<&'a str>,
reboot: Option<bool>,
}
struct MockResolverService {
resolved_urls: Mutex<Vec<String>>,
expectations: Mutex<HashMap<String, Result<PathBuf, Status>>>,
}
impl MockResolverService {
fn new() -> Self {
Self { resolved_urls: Mutex::new(vec![]), expectations: Mutex::new(HashMap::new()) }
}
async fn run_resolver_service(
self: Arc<Self>,
mut stream: PackageResolverRequestStream,
) -> Result<(), Error> {
while let Some(event) = stream.try_next().await? {
let fidl_fuchsia_pkg::PackageResolverRequest::Resolve {
package_url,
selectors: _,
update_policy: _,
dir,
responder,
} = event;
eprintln!("TEST: Got resolve request for {:?}", package_url);
let response = self
.expectations
.lock()
.get(&package_url)
.map(|entry| entry.clone())
// Successfully resolve unexpected packages without serving a package dir. Log the
// transaction so tests can decide if it was expected.
.unwrap_or(Err(Status::OK));
self.resolved_urls.lock().push(package_url);
let response_status = match response {
Ok(package_dir) => {
// Open the package directory using the directory request given by the client
// asking to resolve the package.
fdio::service_connect(
package_dir.to_str().expect("path to str"),
dir.into_channel(),
)
.unwrap_or_else(|err| panic!("error connecting to tempdir {:?}", err));
Status::OK
}
Err(status) => status,
};
responder.send(response_status.into_raw())?;
}
Ok(())
}
fn mock_package_result(&self, url: impl Into<String>, response: Result<PathBuf, Status>) {
self.expectations.lock().insert(url.into(), response);
}
}
#[derive(Debug, PartialEq, Eq)]
enum PaverEvent {
WriteAsset { configuration: paver::Configuration, asset: paver::Asset, payload: Vec<u8> },
WriteBootloader(Vec<u8>),
}
struct MockPaverService {
events: Mutex<Vec<PaverEvent>>,
call_hook: Box<dyn Fn(&PaverEvent) -> Status + Send + Sync>,
}
impl MockPaverService {
fn new_with_call_hook(
call_hook: impl Fn(&PaverEvent) -> Status + Send + Sync + 'static,
) -> Self {
Self { events: Mutex::new(vec![]), call_hook: Box::new(call_hook) }
}
fn hook_always_ok(_: &PaverEvent) -> Status {
Status::OK
}
fn take_events(&self) -> Vec<PaverEvent> {
std::mem::replace(&mut *self.events.lock(), vec![])
}
async fn run_paver_service(
self: Arc<Self>,
mut stream: paver::PaverRequestStream,
) -> Result<(), Error> {
while let Some(request) = stream.try_next().await? {
match request {
paver::PaverRequest::WriteAsset {
configuration,
asset,
mut payload,
responder,
} => {
let payload = verify_and_read_buffer(&mut payload);
let event = PaverEvent::WriteAsset { configuration, asset, payload };
let status = (*self.call_hook)(&event);
self.events.lock().push(event);
responder.send(status.into_raw()).expect("paver response to send");
}
paver::PaverRequest::WriteBootloader { mut payload, responder } => {
let payload = verify_and_read_buffer(&mut payload);
let event = PaverEvent::WriteBootloader(payload);
let status = (*self.call_hook)(&event);
self.events.lock().push(event);
responder.send(status.into_raw()).expect("paver response to send");
}
request => panic!("Unhandled method Paver::{}", request.method_name()),
}
}
Ok(())
}
}
fn verify_and_read_buffer(buffer: &mut fidl_fuchsia_mem::Buffer) -> Vec<u8> {
// The paver service requires VMOs to be resizable. Assert that the buffer provided by the
// system updater can be resized without error.
resize_vmo(&mut buffer.vmo);
read_mem_buffer(buffer)
}
fn resize_vmo(vmo: &mut Vmo) {
let size = vmo.get_size().expect("vmo size query to succeed");
vmo.set_size(size * 2).expect("vmo must be resizable");
}
fn read_mem_buffer(buffer: &fidl_fuchsia_mem::Buffer) -> Vec<u8> {
let mut res = vec![0; buffer.size.try_into().expect("usize")];
buffer.vmo.read(&mut res[..], 0).expect("vmo read to succeed");
res
}
struct MockRebootService {
called: Mutex<u32>,
}
impl MockRebootService {
fn new() -> Self {
Self { called: Mutex::new(0) }
}
async fn run_reboot_service(
self: Arc<Self>,
mut stream: fidl_fuchsia_device_manager::AdministratorRequestStream,
) -> Result<(), Error> {
while let Some(event) = stream.try_next().await? {
let fidl_fuchsia_device_manager::AdministratorRequest::Suspend { flags, responder } =
event;
eprintln!("TEST: Got reboot request with flags {:?}", flags);
*self.called.lock() += 1;
responder.send(Status::OK.into_raw())?;
}
Ok(())
}
}
#[derive(Clone)]
struct CustomEvent {
metric_id: u32,
values: Vec<fidl_fuchsia_cobalt::CustomEventValue>,
}
struct MockLogger {
cobalt_events: Mutex<Vec<fidl_fuchsia_cobalt::CobaltEvent>>,
}
impl MockLogger {
fn new() -> Self {
Self { cobalt_events: Mutex::new(vec![]) }
}
async fn run_logger(
self: Arc<Self>,
mut stream: fidl_fuchsia_cobalt::LoggerRequestStream,
) -> Result<(), Error> {
while let Some(event) = stream.try_next().await? {
match event {
fidl_fuchsia_cobalt::LoggerRequest::LogCobaltEvent { event, responder } => {
self.cobalt_events.lock().push(event);
responder.send(fidl_fuchsia_cobalt::Status::Ok)?;
}
_ => {
panic!("unhandled Logger method {:?}", event);
}
}
}
Ok(())
}
}
struct MockLoggerFactory {
loggers: Mutex<Vec<Arc<MockLogger>>>,
broken: Mutex<bool>,
}
impl MockLoggerFactory {
fn new() -> Self {
Self { loggers: Mutex::new(vec![]), broken: Mutex::new(false) }
}
async fn run_logger_factory(
self: Arc<Self>,
mut stream: fidl_fuchsia_cobalt::LoggerFactoryRequestStream,
) -> Result<(), Error> {
if *self.broken.lock() {
eprintln!("TEST: This LoggerFactory is broken by order of the test.");
// Drop the stream, closing the channel.
return Ok(());
}
while let Some(event) = stream.try_next().await? {
match event {
fidl_fuchsia_cobalt::LoggerFactoryRequest::CreateLoggerFromProjectName {
project_name,
release_stage: _,
logger,
responder,
} => {
eprintln!(
"TEST: Got CreateLogger request with project_name {:?}",
project_name
);
let mock_logger = Arc::new(MockLogger::new());
self.loggers.lock().push(mock_logger.clone());
fasync::spawn(
mock_logger
.run_logger(logger.into_stream()?)
.unwrap_or_else(|e| eprintln!("error while running Logger: {:?}", e)),
);
responder.send(fidl_fuchsia_cobalt::Status::Ok)?;
}
_ => {
panic!("unhandled LoggerFactory method: {:?}", event);
}
}
}
Ok(())
}
}
#[derive(PartialEq, Eq, Debug)]
struct OtaMetrics {
initiator: u32,
phase: u32,
status_code: u32,
target: String,
// TODO: support free_space_delta assertions
}
impl OtaMetrics {
fn from_events(mut events: Vec<fidl_fuchsia_cobalt::CobaltEvent>) -> Self {
events.sort_by_key(|e| e.metric_id);
// expecting one of each event
assert_eq!(
events.iter().map(|e| e.metric_id).collect::<Vec<_>>(),
vec![
metrics::OTA_START_METRIC_ID,
metrics::OTA_RESULT_ATTEMPTS_METRIC_ID,
metrics::OTA_RESULT_DURATION_METRIC_ID,
metrics::OTA_RESULT_FREE_SPACE_DELTA_METRIC_ID
]
);
// we just asserted that we have the exact 4 things we're expecting, so unwrap them
let mut iter = events.into_iter();
let start = iter.next().unwrap();
let attempt = iter.next().unwrap();
let duration = iter.next().unwrap();
let free_space_delta = iter.next().unwrap();
// Some basic sanity checks follow
assert_eq!(
attempt.payload,
fidl_fuchsia_cobalt::EventPayload::EventCount(fidl_fuchsia_cobalt::CountEvent {
period_duration_micros: 0,
count: 1
})
);
let fidl_fuchsia_cobalt::CobaltEvent { event_codes, component, .. } = attempt;
// metric event_codes and component should line up across all 3 result metrics
assert_eq!(&duration.event_codes, &event_codes);
assert_eq!(&duration.component, &component);
assert_eq!(&free_space_delta.event_codes, &event_codes);
assert_eq!(&free_space_delta.component, &component);
// OtaStart only has initiator and hour_of_day, so just check initiator.
assert_eq!(start.event_codes[0], event_codes[0]);
assert_eq!(&start.component, &component);
let target = component.expect("a target update merkle");
assert_eq!(event_codes.len(), 3);
let initiator = event_codes[0];
let phase = event_codes[1];
let status_code = event_codes[2];
match duration.payload {
fidl_fuchsia_cobalt::EventPayload::ElapsedMicros(_time) => {
// Ignore the value since timing is not predictable.
}
other => {
panic!("unexpected duration payload {:?}", other);
}
}
// Ignore this for now, since it's using a shared tempdir, the values
// are not deterministic.
let _free_space_delta = match free_space_delta.payload {
fidl_fuchsia_cobalt::EventPayload::EventCount(fidl_fuchsia_cobalt::CountEvent {
period_duration_micros: 0,
count,
}) => count,
other => {
panic!("unexpected free space delta payload {:?}", other);
}
};
Self { initiator, phase, status_code, target }
}
}
#[fasync::run_singlethreaded(test)]
async fn test_system_update() {
let mut env = TestEnv::new();
env.register_package("update", "upd4t3").add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
);
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await
.expect("run system_updater");
assert_eq!(*env.resolver.resolved_urls.lock(), vec![
"fuchsia-pkg://fuchsia.com/update",
"fuchsia-pkg://fuchsia.com/system_image/0?hash=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296",
]);
let loggers = env.logger_factory.loggers.lock().clone();
assert_eq!(loggers.len(), 1);
let logger = loggers.into_iter().next().unwrap();
assert_eq!(
OtaMetrics::from_events(logger.cobalt_events.lock().clone()),
OtaMetrics {
initiator: metrics::OtaResultAttemptsMetricDimensionInitiator::UserInitiatedCheck
as u32,
phase: metrics::OtaResultAttemptsMetricDimensionPhase::SuccessPendingReboot as u32,
status_code: metrics::OtaResultAttemptsMetricDimensionStatusCode::Success as u32,
target: "m3rk13".into(),
}
);
assert_eq!(*env.reboot_service.called.lock(), 1);
}
#[fasync::run_singlethreaded(test)]
async fn test_system_update_no_reboot() {
let mut env = TestEnv::new();
env.register_package("update", "upd4t3").add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
);
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: Some(false),
})
.await
.expect("run system_updater");
assert_eq!(*env.resolver.resolved_urls.lock(), vec![
"fuchsia-pkg://fuchsia.com/update",
"fuchsia-pkg://fuchsia.com/system_image/0?hash=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296",
]);
let loggers = env.logger_factory.loggers.lock().clone();
assert_eq!(loggers.len(), 1);
let logger = loggers.into_iter().next().unwrap();
assert_eq!(
OtaMetrics::from_events(logger.cobalt_events.lock().clone()),
OtaMetrics {
initiator: metrics::OtaResultAttemptsMetricDimensionInitiator::UserInitiatedCheck
as u32,
phase: metrics::OtaResultAttemptsMetricDimensionPhase::SuccessPendingReboot as u32,
status_code: metrics::OtaResultAttemptsMetricDimensionStatusCode::Success as u32,
target: "m3rk13".into(),
}
);
assert_eq!(*env.reboot_service.called.lock(), 0);
}
#[fasync::run_singlethreaded(test)]
async fn test_broken_logger() {
let mut env = TestEnv::new();
env.register_package("update", "upd4t3").add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
);
*env.logger_factory.broken.lock() = true;
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await
.expect("run system_updater");
assert_eq!(*env.resolver.resolved_urls.lock(), vec![
"fuchsia-pkg://fuchsia.com/update",
"fuchsia-pkg://fuchsia.com/system_image/0?hash=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296"
]);
let loggers = env.logger_factory.loggers.lock().clone();
assert_eq!(loggers.len(), 0);
assert_eq!(*env.reboot_service.called.lock(), 1);
}
#[fasync::run_singlethreaded(test)]
async fn test_failing_package_fetch() {
let mut env = TestEnv::new();
env.register_package("update", "upd4t3").add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
);
env.resolver.mock_package_result("fuchsia-pkg://fuchsia.com/system_image/0?hash=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296", Err(Status::NOT_FOUND));
let result = env
.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await;
assert!(result.is_err(), "system_updater succeeded when it should fail");
assert_eq!(*env.resolver.resolved_urls.lock(), vec![
"fuchsia-pkg://fuchsia.com/update",
"fuchsia-pkg://fuchsia.com/system_image/0?hash=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296"
]);
let loggers = env.logger_factory.loggers.lock().clone();
assert_eq!(loggers.len(), 1);
let logger = loggers.into_iter().next().unwrap();
assert_eq!(
OtaMetrics::from_events(logger.cobalt_events.lock().clone()),
OtaMetrics {
initiator: metrics::OtaResultAttemptsMetricDimensionInitiator::UserInitiatedCheck
as u32,
phase: metrics::OtaResultAttemptsMetricDimensionPhase::PackageDownload as u32,
status_code: metrics::OtaResultAttemptsMetricDimensionStatusCode::Error as u32,
target: "m3rk13".into(),
}
);
assert_eq!(*env.reboot_service.called.lock(), 0);
}
#[fasync::run_singlethreaded(test)]
async fn test_writes_bootloader() {
let mut env = TestEnv::new();
env.register_package("update", "upd4t3")
.add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
)
.add_file("bootloader", "new bootloader");
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await
.expect("success");
assert_eq!(
env.paver_service.take_events(),
vec![PaverEvent::WriteBootloader(b"new bootloader".to_vec())]
);
assert_eq!(*env.reboot_service.called.lock(), 1);
}
#[fasync::run_singlethreaded(test)]
async fn test_writes_recovery() {
let mut env = TestEnv::new();
env.register_package("update", "upd4t3")
.add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
)
.add_file("zedboot", "new recovery");
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await
.expect("success");
assert_eq!(
env.paver_service.take_events(),
vec![PaverEvent::WriteAsset {
configuration: paver::Configuration::Recovery,
asset: paver::Asset::Kernel,
payload: b"new recovery".to_vec(),
}]
);
assert_eq!(*env.reboot_service.called.lock(), 1);
}
#[fasync::run_singlethreaded(test)]
async fn test_writes_recovery_vbmeta() {
let mut env = TestEnv::new();
env.register_package("update", "upd4t3")
.add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
)
.add_file("zedboot", "new recovery")
.add_file("recovery.vbmeta", "new recovery vbmeta");
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await
.expect("success");
assert_eq!(
env.paver_service.take_events(),
vec![
PaverEvent::WriteAsset {
configuration: paver::Configuration::Recovery,
asset: paver::Asset::Kernel,
payload: b"new recovery".to_vec(),
},
PaverEvent::WriteAsset {
configuration: paver::Configuration::Recovery,
asset: paver::Asset::VerifiedBootMetadata,
payload: b"new recovery vbmeta".to_vec(),
},
]
);
assert_eq!(*env.reboot_service.called.lock(), 1);
}
#[fasync::run_singlethreaded(test)]
async fn test_writes_fuchsia_vbmeta() {
let mut env = TestEnv::new();
env.register_package("update", "upd4t3")
.add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
)
.add_file("zbi", "fake zbi")
.add_file("fuchsia.vbmeta", "fake zbi vbmeta");
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await
.expect("success");
assert_eq!(
env.paver_service.take_events(),
vec![
PaverEvent::WriteAsset {
configuration: paver::Configuration::A,
asset: paver::Asset::Kernel,
payload: b"fake zbi".to_vec(),
},
PaverEvent::WriteAsset {
configuration: paver::Configuration::B,
asset: paver::Asset::Kernel,
payload: b"fake zbi".to_vec(),
},
PaverEvent::WriteAsset {
configuration: paver::Configuration::A,
asset: paver::Asset::VerifiedBootMetadata,
payload: b"fake zbi vbmeta".to_vec(),
},
PaverEvent::WriteAsset {
configuration: paver::Configuration::B,
asset: paver::Asset::VerifiedBootMetadata,
payload: b"fake zbi vbmeta".to_vec(),
},
]
);
assert_eq!(*env.reboot_service.called.lock(), 1);
}
#[fasync::run_singlethreaded(test)]
async fn test_working_image_write() {
let mut env = TestEnv::new();
env.register_package("update", "upd4t3")
.add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
)
.add_file("zbi", "fake_zbi");
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await
.expect("success");
let loggers = env.logger_factory.loggers.lock().clone();
assert_eq!(loggers.len(), 1);
let logger = loggers.into_iter().next().unwrap();
assert_eq!(
OtaMetrics::from_events(logger.cobalt_events.lock().clone()),
OtaMetrics {
initiator: metrics::OtaResultAttemptsMetricDimensionInitiator::UserInitiatedCheck
as u32,
phase: metrics::OtaResultAttemptsMetricDimensionPhase::SuccessPendingReboot as u32,
status_code: metrics::OtaResultAttemptsMetricDimensionStatusCode::Success as u32,
target: "m3rk13".into(),
}
);
assert_eq!(
env.paver_service.take_events(),
vec![
PaverEvent::WriteAsset {
configuration: paver::Configuration::A,
asset: paver::Asset::Kernel,
payload: b"fake_zbi".to_vec(),
},
PaverEvent::WriteAsset {
configuration: paver::Configuration::B,
asset: paver::Asset::Kernel,
payload: b"fake_zbi".to_vec(),
}
]
);
assert_eq!(*env.reboot_service.called.lock(), 1);
}
#[fasync::run_singlethreaded(test)]
async fn test_unsupported_b_image_write() {
let mut env = TestEnv::new_with_paver_service_call_hook(|event| match event {
PaverEvent::WriteAsset { configuration, asset, .. }
if *configuration == paver::Configuration::B
&& *asset == fidl_fuchsia_paver::Asset::Kernel =>
{
Status::NOT_SUPPORTED
}
_ => Status::OK,
});
env.register_package("update", "upd4t3")
.add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
)
.add_file("zbi", "fake_zbi");
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await
.expect("success");
let loggers = env.logger_factory.loggers.lock().clone();
assert_eq!(loggers.len(), 1);
let logger = loggers.into_iter().next().unwrap();
assert_eq!(
OtaMetrics::from_events(logger.cobalt_events.lock().clone()),
OtaMetrics {
initiator: metrics::OtaResultAttemptsMetricDimensionInitiator::UserInitiatedCheck
as u32,
phase: metrics::OtaResultAttemptsMetricDimensionPhase::SuccessPendingReboot as u32,
status_code: metrics::OtaResultAttemptsMetricDimensionStatusCode::Success as u32,
target: "m3rk13".into(),
}
);
assert_eq!(
env.paver_service.take_events(),
vec![
PaverEvent::WriteAsset {
configuration: paver::Configuration::A,
asset: paver::Asset::Kernel,
payload: b"fake_zbi".to_vec(),
},
PaverEvent::WriteAsset {
configuration: paver::Configuration::B,
asset: paver::Asset::Kernel,
payload: b"fake_zbi".to_vec(),
}
]
);
assert_eq!(*env.reboot_service.called.lock(), 1);
}
#[fasync::run_singlethreaded(test)]
async fn test_failing_image_write() {
let mut env = TestEnv::new_with_paver_service_call_hook(|_| Status::INTERNAL);
env.register_package("update", "upd4t3")
.add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
)
.add_file("zbi", "fake_zbi");
let result = env
.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await;
assert!(result.is_err(), "system_updater succeeded when it should fail");
let loggers = env.logger_factory.loggers.lock().clone();
assert_eq!(loggers.len(), 1);
let logger = loggers.into_iter().next().unwrap();
assert_eq!(
OtaMetrics::from_events(logger.cobalt_events.lock().clone()),
OtaMetrics {
initiator: metrics::OtaResultAttemptsMetricDimensionInitiator::UserInitiatedCheck
as u32,
phase: metrics::OtaResultAttemptsMetricDimensionPhase::ImageWrite as u32,
status_code: metrics::OtaResultAttemptsMetricDimensionStatusCode::Error as u32,
target: "m3rk13".into(),
}
);
assert_eq!(*env.reboot_service.called.lock(), 0);
}
#[fasync::run_singlethreaded(test)]
async fn test_uses_custom_update_package() {
let mut env = TestEnv::new();
env.register_package("another-update/4", "upd4t3r").add_file(
"packages",
"system_image/0=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296\n",
);
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: Some("fuchsia-pkg://fuchsia.com/another-update/4"),
reboot: None,
})
.await
.expect("run system_updater");
assert_eq!(*env.resolver.resolved_urls.lock(), vec![
"fuchsia-pkg://fuchsia.com/another-update/4",
"fuchsia-pkg://fuchsia.com/system_image/0?hash=42ade6f4fd51636f70c68811228b4271ed52c4eb9a647305123b4f4d0741f296",
]);
}
#[fasync::run_singlethreaded(test)]
async fn test_requires_update_package() {
let env = TestEnv::new();
env.resolver.mock_package_result("fuchsia-pkg://fuchsia.com/update", Err(Status::NOT_FOUND));
let result = env
.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: None,
reboot: None,
})
.await;
assert!(result.is_err(), "system_updater succeeded when it should fail");
assert_eq!(*env.resolver.resolved_urls.lock(), vec!["fuchsia-pkg://fuchsia.com/update"]);
assert_eq!(*env.reboot_service.called.lock(), 0);
}
#[fasync::run_singlethreaded(test)]
async fn test_rejects_invalid_update_package_url() {
let env = TestEnv::new();
let bogus_url = "not-fuchsia-pkg://fuchsia.com/not-a-update";
env.resolver.mock_package_result(bogus_url, Err(Status::INVALID_ARGS));
let result = env
.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: Some(bogus_url),
reboot: None,
})
.await;
assert!(result.is_err(), "system_updater succeeded when it should fail");
assert_eq!(*env.resolver.resolved_urls.lock(), vec![bogus_url]);
assert_eq!(*env.reboot_service.called.lock(), 0);
}
|
//! A binary for testing the OJN parser
use remani::chart::ojm_dump;
use std::{env, ffi::OsStr};
fn output_help(binary_name: &OsStr) {
println!("Usage: {} path/to/ojmfile", binary_name.to_string_lossy());
}
pub fn main() {
let mut args = env::args_os();
let binary = args.next().unwrap_or(format!("./{}", file!().rsplitn(2, ".rs").nth(1).unwrap()).into());
let path = match args.next() {
Some(s) => s,
None => {
output_help(&binary);
return;
}
};
ojm_dump(path);
}
|
use rocket;
mod token;
use spliff_lib::{self, state::SolanaClient};
#[rocket::catch(404)]
fn not_found(req: &rocket::Request) -> String {
format!("Invalid path: {}", req.uri())
}
#[rocket::get("/ping")]
fn ping() -> &'static str {
"OK"
}
#[rocket::main]
async fn main() {
println!("{:?}", spliff_lib::hello());
let solana_client = match SolanaClient::from_env() {
Ok(client) => client,
Err(e) => panic!("Error while initializing solana client: {:?}", e),
};
println!(
"Running server using keypair with public key: {:?}",
solana_client.pubkey
);
if let Err(e) = rocket::build()
.manage(solana_client)
.mount("/", rocket::routes![ping])
.mount(
"/tokens",
rocket::routes![
token::list_tokens_handler,
token::create_token_handler,
token::transfer_token_handler,
],
)
.register("/", rocket::catchers![not_found])
.launch()
.await
{
println!("Could not launch server:");
drop(e);
}
}
|
use std::io;
fn main(){
let reader = io::stdin();
let mut ip = String::new();
reader.read_line(&mut ip).ok().expect("Read Error");
let ns: Vec<i32> = ip
.split_whitespace()
.map(|s| s.parse().unwrap())
.collect();
let mut res = 0;
for num in &ns {
res = res + num;
}
println!("{}", res);
}
// http://stackoverflow.com/questions/26536871/convert-a-string-of-numbers-to-an-array-vector-of-ints-in-rust
/*
split_whitespace() is in fact just a combination of split() and filter(), just like in my original example.
It uses a function in split() argument though which checks for different kinds of whitespace, not only space characters.
You can find its source is here.
*/ |
use anyhow::{anyhow, Result};
use std::convert::{TryFrom, TryInto};
#[derive(serde::Deserialize)]
pub struct Settings {
pub application: ApplicationSettings,
pub observer: ObserverSettings,
pub ecosystem: EcosystemSettings,
}
#[derive(serde::Deserialize)]
pub struct ApplicationSettings {
pub addr_host: String,
pub addr_base_port: usize,
}
#[derive(serde::Deserialize)]
pub struct ObserverSettings {
pub host: String,
pub port: usize,
}
#[derive(serde::Deserialize)]
pub struct EcosystemSettings {
pub population_size: usize,
}
pub fn get_configuration() -> Result<Settings> {
let mut settings = config::Config::default();
let base_path = std::env::current_dir().expect("Failed to determine the current directory");
let configuration_directory = base_path.join("configuration");
// read the 'default' configuration file
settings.merge(config::File::from(configuration_directory.join("base")).required(true))?;
// detect the running environment
// default to 'local' if unspecified
let environment: Environment = std::env::var("APP_ENVIRONMENT")
.unwrap_or_else(|_| "local".into())
.try_into()
.map_err(|e| anyhow!("Failed to parse APP_ENVIRONMENT: {:?}", e))?;
// layer on the environment specific values
settings.merge(
config::File::from(configuration_directory.join(environment.as_str())).required(true),
)?;
// Add in settings from environment variables (with a prefix of APP and '__' as separator)
// E.g. `APP_APPLICATION__PORT=5001 would set `Settings.application.port`
settings.merge(config::Environment::with_prefix("app").separator("__"))?;
settings
.try_into()
.map_err(|e| anyhow!("settings.try_into(): {:?}", e))
}
pub enum Environment {
Local,
Production,
}
impl Environment {
pub fn as_str(&self) -> &'static str {
match self {
Environment::Local => "local",
Environment::Production => "production",
}
}
}
impl TryFrom<String> for Environment {
type Error = String;
fn try_from(s: String) -> Result<Self, Self::Error> {
match s.to_lowercase().as_str() {
"local" => Ok(Self::Local),
"production" => Ok(Self::Production),
other => Err(format!(
"{} is not a supported environment. Use either `local` or `production`.",
other
)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn configuration_can_be_loaded() -> Result<()> {
let settings = get_configuration()?;
assert_eq!(settings.application.addr_host, "[::1]");
assert_eq!(settings.application.addr_base_port, 10000);
assert_eq!(settings.observer.host, "[::1]");
assert_eq!(settings.observer.port, 20000);
assert_eq!(settings.ecosystem.population_size, 2);
Ok(())
}
}
|
#[doc = "Reader of register DECCTRL"]
pub type R = crate::R<u32, super::DECCTRL>;
#[doc = "Writer for register DECCTRL"]
pub type W = crate::W<u32, super::DECCTRL>;
#[doc = "Register DECCTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::DECCTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DISABLE`"]
pub type DISABLE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DISABLE`"]
pub struct DISABLE_W<'a> {
w: &'a mut W,
}
impl<'a> DISABLE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `ERRCHK`"]
pub type ERRCHK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ERRCHK`"]
pub struct ERRCHK_W<'a> {
w: &'a mut W,
}
impl<'a> ERRCHK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `INTMAP`"]
pub type INTMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `INTMAP`"]
pub struct INTMAP_W<'a> {
w: &'a mut W,
}
impl<'a> INTMAP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `HYSTPRS0`"]
pub type HYSTPRS0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HYSTPRS0`"]
pub struct HYSTPRS0_W<'a> {
w: &'a mut W,
}
impl<'a> HYSTPRS0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `HYSTPRS1`"]
pub type HYSTPRS1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HYSTPRS1`"]
pub struct HYSTPRS1_W<'a> {
w: &'a mut W,
}
impl<'a> HYSTPRS1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `HYSTPRS2`"]
pub type HYSTPRS2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HYSTPRS2`"]
pub struct HYSTPRS2_W<'a> {
w: &'a mut W,
}
impl<'a> HYSTPRS2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `HYSTIRQ`"]
pub type HYSTIRQ_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HYSTIRQ`"]
pub struct HYSTIRQ_W<'a> {
w: &'a mut W,
}
impl<'a> HYSTIRQ_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `PRSCNT`"]
pub type PRSCNT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PRSCNT`"]
pub struct PRSCNT_W<'a> {
w: &'a mut W,
}
impl<'a> PRSCNT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `INPUT`"]
pub type INPUT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `INPUT`"]
pub struct INPUT_W<'a> {
w: &'a mut W,
}
impl<'a> INPUT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "LESENSE Decoder PRS Input 0 Configuration\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum PRSSEL0_A {
#[doc = "0: PRS Channel 0 selected as input"]
PRSCH0 = 0,
#[doc = "1: PRS Channel 1 selected as input"]
PRSCH1 = 1,
#[doc = "2: PRS Channel 2 selected as input"]
PRSCH2 = 2,
#[doc = "3: PRS Channel 3 selected as input"]
PRSCH3 = 3,
#[doc = "4: PRS Channel 4 selected as input"]
PRSCH4 = 4,
#[doc = "5: PRS Channel 5 selected as input"]
PRSCH5 = 5,
#[doc = "6: PRS Channel 6 selected as input"]
PRSCH6 = 6,
#[doc = "7: PRS Channel 7 selected as input"]
PRSCH7 = 7,
#[doc = "8: PRS Channel 8 selected as input"]
PRSCH8 = 8,
#[doc = "9: PRS Channel 9 selected as input"]
PRSCH9 = 9,
#[doc = "10: PRS Channel 10 selected as input"]
PRSCH10 = 10,
#[doc = "11: PRS Channel 11 selected as input"]
PRSCH11 = 11,
}
impl From<PRSSEL0_A> for u8 {
#[inline(always)]
fn from(variant: PRSSEL0_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `PRSSEL0`"]
pub type PRSSEL0_R = crate::R<u8, PRSSEL0_A>;
impl PRSSEL0_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, PRSSEL0_A> {
use crate::Variant::*;
match self.bits {
0 => Val(PRSSEL0_A::PRSCH0),
1 => Val(PRSSEL0_A::PRSCH1),
2 => Val(PRSSEL0_A::PRSCH2),
3 => Val(PRSSEL0_A::PRSCH3),
4 => Val(PRSSEL0_A::PRSCH4),
5 => Val(PRSSEL0_A::PRSCH5),
6 => Val(PRSSEL0_A::PRSCH6),
7 => Val(PRSSEL0_A::PRSCH7),
8 => Val(PRSSEL0_A::PRSCH8),
9 => Val(PRSSEL0_A::PRSCH9),
10 => Val(PRSSEL0_A::PRSCH10),
11 => Val(PRSSEL0_A::PRSCH11),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PRSCH0`"]
#[inline(always)]
pub fn is_prsch0(&self) -> bool {
*self == PRSSEL0_A::PRSCH0
}
#[doc = "Checks if the value of the field is `PRSCH1`"]
#[inline(always)]
pub fn is_prsch1(&self) -> bool {
*self == PRSSEL0_A::PRSCH1
}
#[doc = "Checks if the value of the field is `PRSCH2`"]
#[inline(always)]
pub fn is_prsch2(&self) -> bool {
*self == PRSSEL0_A::PRSCH2
}
#[doc = "Checks if the value of the field is `PRSCH3`"]
#[inline(always)]
pub fn is_prsch3(&self) -> bool {
*self == PRSSEL0_A::PRSCH3
}
#[doc = "Checks if the value of the field is `PRSCH4`"]
#[inline(always)]
pub fn is_prsch4(&self) -> bool {
*self == PRSSEL0_A::PRSCH4
}
#[doc = "Checks if the value of the field is `PRSCH5`"]
#[inline(always)]
pub fn is_prsch5(&self) -> bool {
*self == PRSSEL0_A::PRSCH5
}
#[doc = "Checks if the value of the field is `PRSCH6`"]
#[inline(always)]
pub fn is_prsch6(&self) -> bool {
*self == PRSSEL0_A::PRSCH6
}
#[doc = "Checks if the value of the field is `PRSCH7`"]
#[inline(always)]
pub fn is_prsch7(&self) -> bool {
*self == PRSSEL0_A::PRSCH7
}
#[doc = "Checks if the value of the field is `PRSCH8`"]
#[inline(always)]
pub fn is_prsch8(&self) -> bool {
*self == PRSSEL0_A::PRSCH8
}
#[doc = "Checks if the value of the field is `PRSCH9`"]
#[inline(always)]
pub fn is_prsch9(&self) -> bool {
*self == PRSSEL0_A::PRSCH9
}
#[doc = "Checks if the value of the field is `PRSCH10`"]
#[inline(always)]
pub fn is_prsch10(&self) -> bool {
*self == PRSSEL0_A::PRSCH10
}
#[doc = "Checks if the value of the field is `PRSCH11`"]
#[inline(always)]
pub fn is_prsch11(&self) -> bool {
*self == PRSSEL0_A::PRSCH11
}
}
#[doc = "Write proxy for field `PRSSEL0`"]
pub struct PRSSEL0_W<'a> {
w: &'a mut W,
}
impl<'a> PRSSEL0_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PRSSEL0_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "PRS Channel 0 selected as input"]
#[inline(always)]
pub fn prsch0(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH0)
}
#[doc = "PRS Channel 1 selected as input"]
#[inline(always)]
pub fn prsch1(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH1)
}
#[doc = "PRS Channel 2 selected as input"]
#[inline(always)]
pub fn prsch2(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH2)
}
#[doc = "PRS Channel 3 selected as input"]
#[inline(always)]
pub fn prsch3(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH3)
}
#[doc = "PRS Channel 4 selected as input"]
#[inline(always)]
pub fn prsch4(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH4)
}
#[doc = "PRS Channel 5 selected as input"]
#[inline(always)]
pub fn prsch5(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH5)
}
#[doc = "PRS Channel 6 selected as input"]
#[inline(always)]
pub fn prsch6(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH6)
}
#[doc = "PRS Channel 7 selected as input"]
#[inline(always)]
pub fn prsch7(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH7)
}
#[doc = "PRS Channel 8 selected as input"]
#[inline(always)]
pub fn prsch8(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH8)
}
#[doc = "PRS Channel 9 selected as input"]
#[inline(always)]
pub fn prsch9(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH9)
}
#[doc = "PRS Channel 10 selected as input"]
#[inline(always)]
pub fn prsch10(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH10)
}
#[doc = "PRS Channel 11 selected as input"]
#[inline(always)]
pub fn prsch11(self) -> &'a mut W {
self.variant(PRSSEL0_A::PRSCH11)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 10)) | (((value as u32) & 0x0f) << 10);
self.w
}
}
#[doc = "LESENSE Decoder PRS Input 1 Configuration\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum PRSSEL1_A {
#[doc = "0: PRS Channel 0 selected as input"]
PRSCH0 = 0,
#[doc = "1: PRS Channel 1 selected as input"]
PRSCH1 = 1,
#[doc = "2: PRS Channel 2 selected as input"]
PRSCH2 = 2,
#[doc = "3: PRS Channel 3 selected as input"]
PRSCH3 = 3,
#[doc = "4: PRS Channel 4 selected as input"]
PRSCH4 = 4,
#[doc = "5: PRS Channel 5 selected as input"]
PRSCH5 = 5,
#[doc = "6: PRS Channel 6 selected as input"]
PRSCH6 = 6,
#[doc = "7: PRS Channel 7 selected as input"]
PRSCH7 = 7,
#[doc = "8: PRS Channel 8 selected as input"]
PRSCH8 = 8,
#[doc = "9: PRS Channel 9 selected as input"]
PRSCH9 = 9,
#[doc = "10: PRS Channel 10 selected as input"]
PRSCH10 = 10,
#[doc = "11: PRS Channel 11 selected as input"]
PRSCH11 = 11,
}
impl From<PRSSEL1_A> for u8 {
#[inline(always)]
fn from(variant: PRSSEL1_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `PRSSEL1`"]
pub type PRSSEL1_R = crate::R<u8, PRSSEL1_A>;
impl PRSSEL1_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, PRSSEL1_A> {
use crate::Variant::*;
match self.bits {
0 => Val(PRSSEL1_A::PRSCH0),
1 => Val(PRSSEL1_A::PRSCH1),
2 => Val(PRSSEL1_A::PRSCH2),
3 => Val(PRSSEL1_A::PRSCH3),
4 => Val(PRSSEL1_A::PRSCH4),
5 => Val(PRSSEL1_A::PRSCH5),
6 => Val(PRSSEL1_A::PRSCH6),
7 => Val(PRSSEL1_A::PRSCH7),
8 => Val(PRSSEL1_A::PRSCH8),
9 => Val(PRSSEL1_A::PRSCH9),
10 => Val(PRSSEL1_A::PRSCH10),
11 => Val(PRSSEL1_A::PRSCH11),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PRSCH0`"]
#[inline(always)]
pub fn is_prsch0(&self) -> bool {
*self == PRSSEL1_A::PRSCH0
}
#[doc = "Checks if the value of the field is `PRSCH1`"]
#[inline(always)]
pub fn is_prsch1(&self) -> bool {
*self == PRSSEL1_A::PRSCH1
}
#[doc = "Checks if the value of the field is `PRSCH2`"]
#[inline(always)]
pub fn is_prsch2(&self) -> bool {
*self == PRSSEL1_A::PRSCH2
}
#[doc = "Checks if the value of the field is `PRSCH3`"]
#[inline(always)]
pub fn is_prsch3(&self) -> bool {
*self == PRSSEL1_A::PRSCH3
}
#[doc = "Checks if the value of the field is `PRSCH4`"]
#[inline(always)]
pub fn is_prsch4(&self) -> bool {
*self == PRSSEL1_A::PRSCH4
}
#[doc = "Checks if the value of the field is `PRSCH5`"]
#[inline(always)]
pub fn is_prsch5(&self) -> bool {
*self == PRSSEL1_A::PRSCH5
}
#[doc = "Checks if the value of the field is `PRSCH6`"]
#[inline(always)]
pub fn is_prsch6(&self) -> bool {
*self == PRSSEL1_A::PRSCH6
}
#[doc = "Checks if the value of the field is `PRSCH7`"]
#[inline(always)]
pub fn is_prsch7(&self) -> bool {
*self == PRSSEL1_A::PRSCH7
}
#[doc = "Checks if the value of the field is `PRSCH8`"]
#[inline(always)]
pub fn is_prsch8(&self) -> bool {
*self == PRSSEL1_A::PRSCH8
}
#[doc = "Checks if the value of the field is `PRSCH9`"]
#[inline(always)]
pub fn is_prsch9(&self) -> bool {
*self == PRSSEL1_A::PRSCH9
}
#[doc = "Checks if the value of the field is `PRSCH10`"]
#[inline(always)]
pub fn is_prsch10(&self) -> bool {
*self == PRSSEL1_A::PRSCH10
}
#[doc = "Checks if the value of the field is `PRSCH11`"]
#[inline(always)]
pub fn is_prsch11(&self) -> bool {
*self == PRSSEL1_A::PRSCH11
}
}
#[doc = "Write proxy for field `PRSSEL1`"]
pub struct PRSSEL1_W<'a> {
w: &'a mut W,
}
impl<'a> PRSSEL1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PRSSEL1_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "PRS Channel 0 selected as input"]
#[inline(always)]
pub fn prsch0(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH0)
}
#[doc = "PRS Channel 1 selected as input"]
#[inline(always)]
pub fn prsch1(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH1)
}
#[doc = "PRS Channel 2 selected as input"]
#[inline(always)]
pub fn prsch2(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH2)
}
#[doc = "PRS Channel 3 selected as input"]
#[inline(always)]
pub fn prsch3(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH3)
}
#[doc = "PRS Channel 4 selected as input"]
#[inline(always)]
pub fn prsch4(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH4)
}
#[doc = "PRS Channel 5 selected as input"]
#[inline(always)]
pub fn prsch5(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH5)
}
#[doc = "PRS Channel 6 selected as input"]
#[inline(always)]
pub fn prsch6(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH6)
}
#[doc = "PRS Channel 7 selected as input"]
#[inline(always)]
pub fn prsch7(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH7)
}
#[doc = "PRS Channel 8 selected as input"]
#[inline(always)]
pub fn prsch8(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH8)
}
#[doc = "PRS Channel 9 selected as input"]
#[inline(always)]
pub fn prsch9(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH9)
}
#[doc = "PRS Channel 10 selected as input"]
#[inline(always)]
pub fn prsch10(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH10)
}
#[doc = "PRS Channel 11 selected as input"]
#[inline(always)]
pub fn prsch11(self) -> &'a mut W {
self.variant(PRSSEL1_A::PRSCH11)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 15)) | (((value as u32) & 0x0f) << 15);
self.w
}
}
#[doc = "LESENSE Decoder PRS Input 2 Configuration\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum PRSSEL2_A {
#[doc = "0: PRS Channel 0 selected as input"]
PRSCH0 = 0,
#[doc = "1: PRS Channel 1 selected as input"]
PRSCH1 = 1,
#[doc = "2: PRS Channel 2 selected as input"]
PRSCH2 = 2,
#[doc = "3: PRS Channel 3 selected as input"]
PRSCH3 = 3,
#[doc = "4: PRS Channel 4 selected as input"]
PRSCH4 = 4,
#[doc = "5: PRS Channel 5 selected as input"]
PRSCH5 = 5,
#[doc = "6: PRS Channel 6 selected as input"]
PRSCH6 = 6,
#[doc = "7: PRS Channel 7 selected as input"]
PRSCH7 = 7,
#[doc = "8: PRS Channel 8 selected as input"]
PRSCH8 = 8,
#[doc = "9: PRS Channel 9 selected as input"]
PRSCH9 = 9,
#[doc = "10: PRS Channel 10 selected as input"]
PRSCH10 = 10,
#[doc = "11: PRS Channel 11 selected as input"]
PRSCH11 = 11,
}
impl From<PRSSEL2_A> for u8 {
#[inline(always)]
fn from(variant: PRSSEL2_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `PRSSEL2`"]
pub type PRSSEL2_R = crate::R<u8, PRSSEL2_A>;
impl PRSSEL2_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, PRSSEL2_A> {
use crate::Variant::*;
match self.bits {
0 => Val(PRSSEL2_A::PRSCH0),
1 => Val(PRSSEL2_A::PRSCH1),
2 => Val(PRSSEL2_A::PRSCH2),
3 => Val(PRSSEL2_A::PRSCH3),
4 => Val(PRSSEL2_A::PRSCH4),
5 => Val(PRSSEL2_A::PRSCH5),
6 => Val(PRSSEL2_A::PRSCH6),
7 => Val(PRSSEL2_A::PRSCH7),
8 => Val(PRSSEL2_A::PRSCH8),
9 => Val(PRSSEL2_A::PRSCH9),
10 => Val(PRSSEL2_A::PRSCH10),
11 => Val(PRSSEL2_A::PRSCH11),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PRSCH0`"]
#[inline(always)]
pub fn is_prsch0(&self) -> bool {
*self == PRSSEL2_A::PRSCH0
}
#[doc = "Checks if the value of the field is `PRSCH1`"]
#[inline(always)]
pub fn is_prsch1(&self) -> bool {
*self == PRSSEL2_A::PRSCH1
}
#[doc = "Checks if the value of the field is `PRSCH2`"]
#[inline(always)]
pub fn is_prsch2(&self) -> bool {
*self == PRSSEL2_A::PRSCH2
}
#[doc = "Checks if the value of the field is `PRSCH3`"]
#[inline(always)]
pub fn is_prsch3(&self) -> bool {
*self == PRSSEL2_A::PRSCH3
}
#[doc = "Checks if the value of the field is `PRSCH4`"]
#[inline(always)]
pub fn is_prsch4(&self) -> bool {
*self == PRSSEL2_A::PRSCH4
}
#[doc = "Checks if the value of the field is `PRSCH5`"]
#[inline(always)]
pub fn is_prsch5(&self) -> bool {
*self == PRSSEL2_A::PRSCH5
}
#[doc = "Checks if the value of the field is `PRSCH6`"]
#[inline(always)]
pub fn is_prsch6(&self) -> bool {
*self == PRSSEL2_A::PRSCH6
}
#[doc = "Checks if the value of the field is `PRSCH7`"]
#[inline(always)]
pub fn is_prsch7(&self) -> bool {
*self == PRSSEL2_A::PRSCH7
}
#[doc = "Checks if the value of the field is `PRSCH8`"]
#[inline(always)]
pub fn is_prsch8(&self) -> bool {
*self == PRSSEL2_A::PRSCH8
}
#[doc = "Checks if the value of the field is `PRSCH9`"]
#[inline(always)]
pub fn is_prsch9(&self) -> bool {
*self == PRSSEL2_A::PRSCH9
}
#[doc = "Checks if the value of the field is `PRSCH10`"]
#[inline(always)]
pub fn is_prsch10(&self) -> bool {
*self == PRSSEL2_A::PRSCH10
}
#[doc = "Checks if the value of the field is `PRSCH11`"]
#[inline(always)]
pub fn is_prsch11(&self) -> bool {
*self == PRSSEL2_A::PRSCH11
}
}
#[doc = "Write proxy for field `PRSSEL2`"]
pub struct PRSSEL2_W<'a> {
w: &'a mut W,
}
impl<'a> PRSSEL2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PRSSEL2_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "PRS Channel 0 selected as input"]
#[inline(always)]
pub fn prsch0(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH0)
}
#[doc = "PRS Channel 1 selected as input"]
#[inline(always)]
pub fn prsch1(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH1)
}
#[doc = "PRS Channel 2 selected as input"]
#[inline(always)]
pub fn prsch2(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH2)
}
#[doc = "PRS Channel 3 selected as input"]
#[inline(always)]
pub fn prsch3(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH3)
}
#[doc = "PRS Channel 4 selected as input"]
#[inline(always)]
pub fn prsch4(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH4)
}
#[doc = "PRS Channel 5 selected as input"]
#[inline(always)]
pub fn prsch5(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH5)
}
#[doc = "PRS Channel 6 selected as input"]
#[inline(always)]
pub fn prsch6(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH6)
}
#[doc = "PRS Channel 7 selected as input"]
#[inline(always)]
pub fn prsch7(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH7)
}
#[doc = "PRS Channel 8 selected as input"]
#[inline(always)]
pub fn prsch8(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH8)
}
#[doc = "PRS Channel 9 selected as input"]
#[inline(always)]
pub fn prsch9(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH9)
}
#[doc = "PRS Channel 10 selected as input"]
#[inline(always)]
pub fn prsch10(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH10)
}
#[doc = "PRS Channel 11 selected as input"]
#[inline(always)]
pub fn prsch11(self) -> &'a mut W {
self.variant(PRSSEL2_A::PRSCH11)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 20)) | (((value as u32) & 0x0f) << 20);
self.w
}
}
#[doc = "LESENSE Decoder PRS Input 3 Configuration\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum PRSSEL3_A {
#[doc = "0: PRS Channel 0 selected as input"]
PRSCH0 = 0,
#[doc = "1: PRS Channel 1 selected as input"]
PRSCH1 = 1,
#[doc = "2: PRS Channel 2 selected as input"]
PRSCH2 = 2,
#[doc = "3: PRS Channel 3 selected as input"]
PRSCH3 = 3,
#[doc = "4: PRS Channel 4 selected as input"]
PRSCH4 = 4,
#[doc = "5: PRS Channel 5 selected as input"]
PRSCH5 = 5,
#[doc = "6: PRS Channel 6 selected as input"]
PRSCH6 = 6,
#[doc = "7: PRS Channel 7 selected as input"]
PRSCH7 = 7,
#[doc = "8: PRS Channel 8 selected as input"]
PRSCH8 = 8,
#[doc = "9: PRS Channel 9 selected as input"]
PRSCH9 = 9,
#[doc = "10: PRS Channel 10 selected as input"]
PRSCH10 = 10,
#[doc = "11: PRS Channel 11 selected as input"]
PRSCH11 = 11,
}
impl From<PRSSEL3_A> for u8 {
#[inline(always)]
fn from(variant: PRSSEL3_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `PRSSEL3`"]
pub type PRSSEL3_R = crate::R<u8, PRSSEL3_A>;
impl PRSSEL3_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, PRSSEL3_A> {
use crate::Variant::*;
match self.bits {
0 => Val(PRSSEL3_A::PRSCH0),
1 => Val(PRSSEL3_A::PRSCH1),
2 => Val(PRSSEL3_A::PRSCH2),
3 => Val(PRSSEL3_A::PRSCH3),
4 => Val(PRSSEL3_A::PRSCH4),
5 => Val(PRSSEL3_A::PRSCH5),
6 => Val(PRSSEL3_A::PRSCH6),
7 => Val(PRSSEL3_A::PRSCH7),
8 => Val(PRSSEL3_A::PRSCH8),
9 => Val(PRSSEL3_A::PRSCH9),
10 => Val(PRSSEL3_A::PRSCH10),
11 => Val(PRSSEL3_A::PRSCH11),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PRSCH0`"]
#[inline(always)]
pub fn is_prsch0(&self) -> bool {
*self == PRSSEL3_A::PRSCH0
}
#[doc = "Checks if the value of the field is `PRSCH1`"]
#[inline(always)]
pub fn is_prsch1(&self) -> bool {
*self == PRSSEL3_A::PRSCH1
}
#[doc = "Checks if the value of the field is `PRSCH2`"]
#[inline(always)]
pub fn is_prsch2(&self) -> bool {
*self == PRSSEL3_A::PRSCH2
}
#[doc = "Checks if the value of the field is `PRSCH3`"]
#[inline(always)]
pub fn is_prsch3(&self) -> bool {
*self == PRSSEL3_A::PRSCH3
}
#[doc = "Checks if the value of the field is `PRSCH4`"]
#[inline(always)]
pub fn is_prsch4(&self) -> bool {
*self == PRSSEL3_A::PRSCH4
}
#[doc = "Checks if the value of the field is `PRSCH5`"]
#[inline(always)]
pub fn is_prsch5(&self) -> bool {
*self == PRSSEL3_A::PRSCH5
}
#[doc = "Checks if the value of the field is `PRSCH6`"]
#[inline(always)]
pub fn is_prsch6(&self) -> bool {
*self == PRSSEL3_A::PRSCH6
}
#[doc = "Checks if the value of the field is `PRSCH7`"]
#[inline(always)]
pub fn is_prsch7(&self) -> bool {
*self == PRSSEL3_A::PRSCH7
}
#[doc = "Checks if the value of the field is `PRSCH8`"]
#[inline(always)]
pub fn is_prsch8(&self) -> bool {
*self == PRSSEL3_A::PRSCH8
}
#[doc = "Checks if the value of the field is `PRSCH9`"]
#[inline(always)]
pub fn is_prsch9(&self) -> bool {
*self == PRSSEL3_A::PRSCH9
}
#[doc = "Checks if the value of the field is `PRSCH10`"]
#[inline(always)]
pub fn is_prsch10(&self) -> bool {
*self == PRSSEL3_A::PRSCH10
}
#[doc = "Checks if the value of the field is `PRSCH11`"]
#[inline(always)]
pub fn is_prsch11(&self) -> bool {
*self == PRSSEL3_A::PRSCH11
}
}
#[doc = "Write proxy for field `PRSSEL3`"]
pub struct PRSSEL3_W<'a> {
w: &'a mut W,
}
impl<'a> PRSSEL3_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PRSSEL3_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "PRS Channel 0 selected as input"]
#[inline(always)]
pub fn prsch0(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH0)
}
#[doc = "PRS Channel 1 selected as input"]
#[inline(always)]
pub fn prsch1(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH1)
}
#[doc = "PRS Channel 2 selected as input"]
#[inline(always)]
pub fn prsch2(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH2)
}
#[doc = "PRS Channel 3 selected as input"]
#[inline(always)]
pub fn prsch3(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH3)
}
#[doc = "PRS Channel 4 selected as input"]
#[inline(always)]
pub fn prsch4(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH4)
}
#[doc = "PRS Channel 5 selected as input"]
#[inline(always)]
pub fn prsch5(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH5)
}
#[doc = "PRS Channel 6 selected as input"]
#[inline(always)]
pub fn prsch6(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH6)
}
#[doc = "PRS Channel 7 selected as input"]
#[inline(always)]
pub fn prsch7(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH7)
}
#[doc = "PRS Channel 8 selected as input"]
#[inline(always)]
pub fn prsch8(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH8)
}
#[doc = "PRS Channel 9 selected as input"]
#[inline(always)]
pub fn prsch9(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH9)
}
#[doc = "PRS Channel 10 selected as input"]
#[inline(always)]
pub fn prsch10(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH10)
}
#[doc = "PRS Channel 11 selected as input"]
#[inline(always)]
pub fn prsch11(self) -> &'a mut W {
self.variant(PRSSEL3_A::PRSCH11)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 25)) | (((value as u32) & 0x0f) << 25);
self.w
}
}
impl R {
#[doc = "Bit 0 - Disable the Decoder"]
#[inline(always)]
pub fn disable(&self) -> DISABLE_R {
DISABLE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Enable Check of Current State"]
#[inline(always)]
pub fn errchk(&self) -> ERRCHK_R {
ERRCHK_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Enable Decoder to Channel Interrupt Mapping"]
#[inline(always)]
pub fn intmap(&self) -> INTMAP_R {
INTMAP_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Enable Decoder Hysteresis on PRS0 Output"]
#[inline(always)]
pub fn hystprs0(&self) -> HYSTPRS0_R {
HYSTPRS0_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Enable Decoder Hysteresis on PRS1 Output"]
#[inline(always)]
pub fn hystprs1(&self) -> HYSTPRS1_R {
HYSTPRS1_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Enable Decoder Hysteresis on PRS2 Output"]
#[inline(always)]
pub fn hystprs2(&self) -> HYSTPRS2_R {
HYSTPRS2_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Enable Decoder Hysteresis on Interrupt Requests"]
#[inline(always)]
pub fn hystirq(&self) -> HYSTIRQ_R {
HYSTIRQ_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Enable Count Mode on Decoder PRS Channels 0 and 1"]
#[inline(always)]
pub fn prscnt(&self) -> PRSCNT_R {
PRSCNT_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - LESENSE Decoder Input Configuration"]
#[inline(always)]
pub fn input(&self) -> INPUT_R {
INPUT_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bits 10:13 - LESENSE Decoder PRS Input 0 Configuration"]
#[inline(always)]
pub fn prssel0(&self) -> PRSSEL0_R {
PRSSEL0_R::new(((self.bits >> 10) & 0x0f) as u8)
}
#[doc = "Bits 15:18 - LESENSE Decoder PRS Input 1 Configuration"]
#[inline(always)]
pub fn prssel1(&self) -> PRSSEL1_R {
PRSSEL1_R::new(((self.bits >> 15) & 0x0f) as u8)
}
#[doc = "Bits 20:23 - LESENSE Decoder PRS Input 2 Configuration"]
#[inline(always)]
pub fn prssel2(&self) -> PRSSEL2_R {
PRSSEL2_R::new(((self.bits >> 20) & 0x0f) as u8)
}
#[doc = "Bits 25:28 - LESENSE Decoder PRS Input 3 Configuration"]
#[inline(always)]
pub fn prssel3(&self) -> PRSSEL3_R {
PRSSEL3_R::new(((self.bits >> 25) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bit 0 - Disable the Decoder"]
#[inline(always)]
pub fn disable(&mut self) -> DISABLE_W {
DISABLE_W { w: self }
}
#[doc = "Bit 1 - Enable Check of Current State"]
#[inline(always)]
pub fn errchk(&mut self) -> ERRCHK_W {
ERRCHK_W { w: self }
}
#[doc = "Bit 2 - Enable Decoder to Channel Interrupt Mapping"]
#[inline(always)]
pub fn intmap(&mut self) -> INTMAP_W {
INTMAP_W { w: self }
}
#[doc = "Bit 3 - Enable Decoder Hysteresis on PRS0 Output"]
#[inline(always)]
pub fn hystprs0(&mut self) -> HYSTPRS0_W {
HYSTPRS0_W { w: self }
}
#[doc = "Bit 4 - Enable Decoder Hysteresis on PRS1 Output"]
#[inline(always)]
pub fn hystprs1(&mut self) -> HYSTPRS1_W {
HYSTPRS1_W { w: self }
}
#[doc = "Bit 5 - Enable Decoder Hysteresis on PRS2 Output"]
#[inline(always)]
pub fn hystprs2(&mut self) -> HYSTPRS2_W {
HYSTPRS2_W { w: self }
}
#[doc = "Bit 6 - Enable Decoder Hysteresis on Interrupt Requests"]
#[inline(always)]
pub fn hystirq(&mut self) -> HYSTIRQ_W {
HYSTIRQ_W { w: self }
}
#[doc = "Bit 7 - Enable Count Mode on Decoder PRS Channels 0 and 1"]
#[inline(always)]
pub fn prscnt(&mut self) -> PRSCNT_W {
PRSCNT_W { w: self }
}
#[doc = "Bit 8 - LESENSE Decoder Input Configuration"]
#[inline(always)]
pub fn input(&mut self) -> INPUT_W {
INPUT_W { w: self }
}
#[doc = "Bits 10:13 - LESENSE Decoder PRS Input 0 Configuration"]
#[inline(always)]
pub fn prssel0(&mut self) -> PRSSEL0_W {
PRSSEL0_W { w: self }
}
#[doc = "Bits 15:18 - LESENSE Decoder PRS Input 1 Configuration"]
#[inline(always)]
pub fn prssel1(&mut self) -> PRSSEL1_W {
PRSSEL1_W { w: self }
}
#[doc = "Bits 20:23 - LESENSE Decoder PRS Input 2 Configuration"]
#[inline(always)]
pub fn prssel2(&mut self) -> PRSSEL2_W {
PRSSEL2_W { w: self }
}
#[doc = "Bits 25:28 - LESENSE Decoder PRS Input 3 Configuration"]
#[inline(always)]
pub fn prssel3(&mut self) -> PRSSEL3_W {
PRSSEL3_W { w: self }
}
}
|
use std::{
collections::HashMap,
path::Path,
sync::mpsc::{self, Receiver},
};
use rbx_dom_weak::{RbxTree, RbxInstanceProperties};
use log::info;
use crate::{
place_runner::{PlaceRunner, PlaceRunnerOptions, open_rbx_place_file},
message_receiver::RobloxMessage,
};
pub const DEFAULT_PORT: u16 = 54023;
pub const DEFAULT_TIMEOUT: u16 = 15;
pub fn run_place(
path: &Path,
extension: &str,
options: PlaceRunnerOptions,
) -> Receiver<Option<RobloxMessage>> {
let tree = open_rbx_place_file(path, extension);
let place = PlaceRunner::new(tree, options);
let (message_tx, message_rx) = mpsc::channel();
place.run_with_sender(message_tx);
message_rx
}
pub fn run_model(_path: &Path, _extension: &str) -> Receiver<Option<RobloxMessage>> {
unimplemented!("Models are not yet supported by run-in-roblox.");
}
pub fn run_script(options: PlaceRunnerOptions) -> Receiver<Option<RobloxMessage>> {
let tree = RbxTree::new(RbxInstanceProperties {
name: String::from("Place"),
class_name: String::from("DataModel"),
properties: HashMap::new(),
});
let place = PlaceRunner::new(tree, options);
let (message_tx, message_rx) = mpsc::channel();
info!("Running place...");
place.run_with_sender(message_tx);
message_rx
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.