hexsha
stringlengths 40
40
| size
int64 4
1.05M
| content
stringlengths 4
1.05M
| avg_line_length
float64 1.33
100
| max_line_length
int64 1
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
4a1b826a55690f0f41b077a5dd64533af7635c5d
| 201 |
use thiserror::Error;
#[allow(dead_code)]
#[derive(Error, Debug, PartialEq)]
pub enum Error {
#[error("not trust input")]
NotTrustedInput,
#[error("unknown handler")]
UnknownHandle,
}
| 18.272727 | 34 | 0.661692 |
23c08cc540c37b52ddc15580d70526b5821966b8
| 3,957 |
use bytes::Bytes;
use rand::{
distributions::Distribution,
Rng
};
use std::{
cmp,
collections::HashMap,
hash::Hash,
iter,
};
struct WeightedSet<T> {
values: HashMap<T, usize>,
total_size: usize,
}
impl<T: Hash + Eq> WeightedSet<T> {
pub fn new() -> Self {
Self {
values: HashMap::new(),
total_size: 0,
}
}
pub fn insert(&mut self, value: T) {
*self.values.entry(value).or_insert(0) += 1;
self.total_size += 1;
}
}
impl<T: Clone> Distribution<T> for WeightedSet<T> {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T {
let selected = rng.gen_range(1..=self.total_size);
self.values.iter()
.scan(0, |accum, (value, weight)| {
*accum += *weight;
Some((*accum >= selected, value))
})
.find_map(|(is_next, value)| is_next.then(|| value.clone()))
.expect("Called `sample` on an empty WeightedSet")
}
}
pub struct Chain {
values: HashMap<Option<Bytes>, WeightedSet<Option<Bytes>>>,
chain_len: usize
}
impl Chain {
pub fn new(len: usize) -> Self {
Self {
values: HashMap::new(),
chain_len: len
}
}
pub fn feed<T: Into<Bytes>>(&mut self, feeder: T) {
fn byte_windows<'a>(bytes: &'a Bytes, size: usize) -> impl Iterator<Item=Bytes> + 'a {
// The idea here is to iterate between 0 and the last window's left
// position and then slice the bytes for the window size
//
// We need to special case for the bytes being smaller than the
// window size though - i.e. we need to iterate at least once, so
// make sure that the iterator range goes to at least 1
(0..=bytes.len().saturating_sub(size))
.into_iter()
// if the bytes are smaller than the window size, then doing
// bytes[idx..idx + size] will overflow the buffer, so we need
// to make sure that the slice we make is within bounds
.map(move |idx| bytes.slice(idx..cmp::min(bytes.len(), idx + size)))
}
fn inner(this: &mut Chain, bytes: Bytes) {
if bytes.len() > 0 {
// We want an iterator like so (for the string "abcde"):
//
// (None, "abc"), ("abc", "bcd"), ("bcd", "cde"), ("cde", None)
//
// To do this we start with an iterator over "abc", "bcd", "cde"
// which is the above byte windows iterator for the bytes
//
// Then we create one iterator which will go through those values,
// and finish with None
let wind_a = byte_windows(&bytes, this.chain_len).map(Option::Some).chain(iter::once(None));
// Then we create another iterator which will start with None, then
// go through the values
let wind_b = iter::once(None).chain(byte_windows(&bytes, this.chain_len).map(Option::Some));
//Then we zip the two iterators together
for (prev, next) in wind_b.zip(wind_a) {
this.values.entry(prev).or_insert_with(WeightedSet::new).insert(next);
}
}
}
inner(self, feeder.into())
}
pub fn generator<'a, R: Rng + 'a>(&'a self, mut rng: R) -> impl Iterator<Item=u8> + 'a {
let mut random_segment = move |base| self.values.get(&base).and_then(|set| rng.sample(set));
let mut segments = iter::successors(random_segment(None), move |b| random_segment(Some(b.clone())));
// Get all bytes of the first segment
segments.next()
.into_iter()
.flatten()
// For every other segment, just get the last character
.chain(segments.map(|b| b[b.len() - 1]))
}
}
| 36.638889 | 108 | 0.535254 |
ff0b62215fefdea770dc82dddad22dfd01786079
| 10,289 |
use common::read_u32_vint;
use super::stacker::{ExpUnrolledLinkedList, MemoryArena};
use crate::indexer::doc_id_mapping::DocIdMapping;
use crate::postings::FieldSerializer;
use crate::DocId;
const POSITION_END: u32 = 0;
#[derive(Default)]
pub(crate) struct BufferLender {
buffer_u8: Vec<u8>,
buffer_u32: Vec<u32>,
}
impl BufferLender {
pub fn lend_u8(&mut self) -> &mut Vec<u8> {
self.buffer_u8.clear();
&mut self.buffer_u8
}
pub fn lend_all(&mut self) -> (&mut Vec<u8>, &mut Vec<u32>) {
self.buffer_u8.clear();
self.buffer_u32.clear();
(&mut self.buffer_u8, &mut self.buffer_u32)
}
}
pub struct VInt32Reader<'a> {
data: &'a [u8],
}
impl<'a> VInt32Reader<'a> {
fn new(data: &'a [u8]) -> VInt32Reader<'a> {
VInt32Reader { data }
}
}
impl<'a> Iterator for VInt32Reader<'a> {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.data.is_empty() {
None
} else {
Some(read_u32_vint(&mut self.data))
}
}
}
/// Recorder is in charge of recording relevant information about
/// the presence of a term in a document.
///
/// Depending on the `TextIndexingOptions` associated to the
/// field, the recorder may records
/// * the document frequency
/// * the document id
/// * the term frequency
/// * the term positions
pub(crate) trait Recorder: Copy + 'static {
///
fn new() -> Self;
/// Returns the current document
fn current_doc(&self) -> u32;
/// Starts recording information about a new document
/// This method shall only be called if the term is within the document.
fn new_doc(&mut self, doc: DocId, arena: &mut MemoryArena);
/// Record the position of a term. For each document,
/// this method will be called `term_freq` times.
fn record_position(&mut self, position: u32, arena: &mut MemoryArena);
/// Close the document. It will help record the term frequency.
fn close_doc(&mut self, arena: &mut MemoryArena);
/// Pushes the postings information to the serializer.
fn serialize(
&self,
arena: &MemoryArena,
doc_id_map: Option<&DocIdMapping>,
serializer: &mut FieldSerializer<'_>,
buffer_lender: &mut BufferLender,
);
/// Returns the number of document containing this term.
///
/// Returns `None` if not available.
fn term_doc_freq(&self) -> Option<u32>;
}
/// Only records the doc ids
#[derive(Clone, Copy)]
pub struct NothingRecorder {
stack: ExpUnrolledLinkedList,
current_doc: DocId,
}
impl Recorder for NothingRecorder {
fn new() -> Self {
NothingRecorder {
stack: ExpUnrolledLinkedList::new(),
current_doc: u32::max_value(),
}
}
fn current_doc(&self) -> DocId {
self.current_doc
}
fn new_doc(&mut self, doc: DocId, arena: &mut MemoryArena) {
self.current_doc = doc;
self.stack.writer(arena).write_u32_vint(doc);
}
fn record_position(&mut self, _position: u32, _arena: &mut MemoryArena) {}
fn close_doc(&mut self, _arena: &mut MemoryArena) {}
fn serialize(
&self,
arena: &MemoryArena,
doc_id_map: Option<&DocIdMapping>,
serializer: &mut FieldSerializer<'_>,
buffer_lender: &mut BufferLender,
) {
let (buffer, doc_ids) = buffer_lender.lend_all();
self.stack.read_to_end(arena, buffer);
// TODO avoid reading twice.
if let Some(doc_id_map) = doc_id_map {
doc_ids.extend(
VInt32Reader::new(&buffer[..])
.map(|old_doc_id| doc_id_map.get_new_doc_id(old_doc_id)),
);
doc_ids.sort_unstable();
for doc in doc_ids {
serializer.write_doc(*doc, 0u32, &[][..]);
}
} else {
for doc in VInt32Reader::new(&buffer[..]) {
serializer.write_doc(doc, 0u32, &[][..]);
}
}
}
fn term_doc_freq(&self) -> Option<u32> {
None
}
}
/// Recorder encoding document ids, and term frequencies
#[derive(Clone, Copy)]
pub struct TermFrequencyRecorder {
stack: ExpUnrolledLinkedList,
current_doc: DocId,
current_tf: u32,
term_doc_freq: u32,
}
impl Recorder for TermFrequencyRecorder {
fn new() -> Self {
TermFrequencyRecorder {
stack: ExpUnrolledLinkedList::new(),
current_doc: 0,
current_tf: 0u32,
term_doc_freq: 0u32,
}
}
fn current_doc(&self) -> DocId {
self.current_doc
}
fn new_doc(&mut self, doc: DocId, arena: &mut MemoryArena) {
self.term_doc_freq += 1;
self.current_doc = doc;
self.stack.writer(arena).write_u32_vint(doc);
}
fn record_position(&mut self, _position: u32, _arena: &mut MemoryArena) {
self.current_tf += 1;
}
fn close_doc(&mut self, arena: &mut MemoryArena) {
debug_assert!(self.current_tf > 0);
self.stack.writer(arena).write_u32_vint(self.current_tf);
self.current_tf = 0;
}
fn serialize(
&self,
arena: &MemoryArena,
doc_id_map: Option<&DocIdMapping>,
serializer: &mut FieldSerializer<'_>,
buffer_lender: &mut BufferLender,
) {
let buffer = buffer_lender.lend_u8();
self.stack.read_to_end(arena, buffer);
let mut u32_it = VInt32Reader::new(&buffer[..]);
if let Some(doc_id_map) = doc_id_map {
let mut doc_id_and_tf = vec![];
while let Some(old_doc_id) = u32_it.next() {
let term_freq = u32_it.next().unwrap_or(self.current_tf);
doc_id_and_tf.push((doc_id_map.get_new_doc_id(old_doc_id), term_freq));
}
doc_id_and_tf.sort_unstable_by_key(|&(doc_id, _)| doc_id);
for (doc_id, tf) in doc_id_and_tf {
serializer.write_doc(doc_id, tf, &[][..]);
}
} else {
while let Some(doc) = u32_it.next() {
let term_freq = u32_it.next().unwrap_or(self.current_tf);
serializer.write_doc(doc, term_freq, &[][..]);
}
}
}
fn term_doc_freq(&self) -> Option<u32> {
Some(self.term_doc_freq)
}
}
/// Recorder encoding term frequencies as well as positions.
#[derive(Clone, Copy)]
pub struct TfAndPositionRecorder {
stack: ExpUnrolledLinkedList,
current_doc: DocId,
term_doc_freq: u32,
}
impl Recorder for TfAndPositionRecorder {
fn new() -> Self {
TfAndPositionRecorder {
stack: ExpUnrolledLinkedList::new(),
current_doc: u32::max_value(),
term_doc_freq: 0u32,
}
}
fn current_doc(&self) -> DocId {
self.current_doc
}
fn new_doc(&mut self, doc: DocId, arena: &mut MemoryArena) {
self.current_doc = doc;
self.term_doc_freq += 1u32;
self.stack.writer(arena).write_u32_vint(doc);
}
fn record_position(&mut self, position: u32, arena: &mut MemoryArena) {
self.stack
.writer(arena)
.write_u32_vint(position.wrapping_add(1u32));
}
fn close_doc(&mut self, arena: &mut MemoryArena) {
self.stack.writer(arena).write_u32_vint(POSITION_END);
}
fn serialize(
&self,
arena: &MemoryArena,
doc_id_map: Option<&DocIdMapping>,
serializer: &mut FieldSerializer<'_>,
buffer_lender: &mut BufferLender,
) {
let (buffer_u8, buffer_positions) = buffer_lender.lend_all();
self.stack.read_to_end(arena, buffer_u8);
let mut u32_it = VInt32Reader::new(&buffer_u8[..]);
let mut doc_id_and_positions = vec![];
while let Some(doc) = u32_it.next() {
let mut prev_position_plus_one = 1u32;
buffer_positions.clear();
loop {
match u32_it.next() {
Some(POSITION_END) | None => {
break;
}
Some(position_plus_one) => {
let delta_position = position_plus_one - prev_position_plus_one;
buffer_positions.push(delta_position);
prev_position_plus_one = position_plus_one;
}
}
}
if let Some(doc_id_map) = doc_id_map {
// this simple variant to remap may consume to much memory
doc_id_and_positions
.push((doc_id_map.get_new_doc_id(doc), buffer_positions.to_vec()));
} else {
serializer.write_doc(doc, buffer_positions.len() as u32, buffer_positions);
}
}
if doc_id_map.is_some() {
doc_id_and_positions.sort_unstable_by_key(|&(doc_id, _)| doc_id);
for (doc_id, positions) in doc_id_and_positions {
serializer.write_doc(doc_id, positions.len() as u32, &positions);
}
}
}
fn term_doc_freq(&self) -> Option<u32> {
Some(self.term_doc_freq)
}
}
#[cfg(test)]
mod tests {
use common::write_u32_vint;
use super::{BufferLender, VInt32Reader};
#[test]
fn test_buffer_lender() {
let mut buffer_lender = BufferLender::default();
{
let buf = buffer_lender.lend_u8();
assert!(buf.is_empty());
buf.push(1u8);
}
{
let buf = buffer_lender.lend_u8();
assert!(buf.is_empty());
buf.push(1u8);
}
{
let (_, buf) = buffer_lender.lend_all();
assert!(buf.is_empty());
buf.push(1u32);
}
{
let (_, buf) = buffer_lender.lend_all();
assert!(buf.is_empty());
buf.push(1u32);
}
}
#[test]
fn test_vint_u32() {
let mut buffer = vec![];
let vals = [0, 1, 324_234_234, u32::max_value()];
for &i in &vals {
assert!(write_u32_vint(i, &mut buffer).is_ok());
}
assert_eq!(buffer.len(), 1 + 1 + 5 + 5);
let res: Vec<u32> = VInt32Reader::new(&buffer[..]).collect();
assert_eq!(&res[..], &vals[..]);
}
}
| 29.736994 | 91 | 0.572456 |
0102cfe3e2754bc1b1256179bcc1a992ec83b4a5
| 7,617 |
use std::cmp::{self, Ordering};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::{Add, Mul, Sub};
use crate::{ASTEROID, EMPTY_SPACE, INPUT};
lazy_static! {
static ref DATA: Vec<Point<i32>> = parse(&INPUT);
}
#[derive(Debug, PartialEq, Hash, Eq)]
pub struct Point<T>(T, T)
where
T: Hash + Eq + Debug;
impl<T> Point<T>
where
T: Copy + Hash + Eq + Debug,
{
pub fn x(&self) -> T {
self.0
}
pub fn y(&self) -> T {
self.1
}
}
pub fn distance<T>(p1: &Point<T>, p2: &Point<T>) -> T
where
T: Copy + Hash + Eq + Debug + Default + Sub<T, Output = T> + Add<T, Output = T> + cmp::Ord,
{
let abs = |v| {
if v < T::default() {
T::default() - v
} else {
v
}
};
abs(p1.x() - p2.x()) + abs(p1.y() + p2.y())
}
pub fn parse<T>(s: &str) -> Vec<Point<T>>
where
T: From<u16> + Hash + Eq + Debug,
{
s.lines()
.enumerate()
.flat_map(|(y, l)| {
l.trim()
.chars()
.enumerate()
.filter_map(move |(x, c)| match c {
ASTEROID => {
let x = T::try_from(x as u16).unwrap_or_else(|_| panic!("invalid x index"));
let y = T::try_from(y as u16).unwrap_or_else(|_| panic!("invalid y index"));
Some(Point(x, y))
}
EMPTY_SPACE => None,
_ => unreachable!(),
})
})
.collect()
}
pub fn contains<T>(pa: &Point<T>, pb: &Point<T>, p: &Point<T>) -> bool
where
T: Copy
+ Sub<T, Output = T>
+ Mul<T, Output = T>
+ Default
+ PartialEq
+ PartialOrd
+ Hash
+ Eq
+ Debug
+ cmp::Ord,
{
let dx = pb.x() - pa.x();
let dy = pb.y() - pa.y();
let in_x = || p.x() >= cmp::min(pa.x(), pb.x()) && p.x() <= cmp::max(pa.x(), pb.x());
let in_y = || p.y() >= cmp::min(pa.y(), pb.y()) && p.y() <= cmp::max(pa.y(), pb.y());
if dx == T::default() {
if dy == T::default() {
false
} else {
p.x() == pa.x() && in_y()
}
} else if dy == T::default() {
p.y() == pa.y() && in_x()
} else {
in_x() && in_y() && (p.x() - pa.x()) * dy == (p.y() - pa.y()) * dx
}
}
pub fn solve_1<T>(points: &[Point<T>]) -> (&Point<T>, usize)
where
T: Eq
+ Hash
+ Copy
+ Sub<T, Output = T>
+ Mul<T, Output = T>
+ Default
+ PartialEq
+ PartialOrd
+ Debug
+ cmp::Ord,
{
let mut los = vec![];
let points = &points[..];
for a in 0..points.len() {
let pa = &points[a];
for b in a + 1..points.len() {
let pb = &points[b];
if !points
.iter()
.enumerate()
.any(|(i, p)| i != a && i != b && contains(&pa, &pb, p))
{
los.push((pa, pb));
}
}
}
los.iter()
.fold(HashMap::<&Point<T>, usize>::new(), |mut acc, (p1, p2)| {
acc.entry(p1).and_modify(|v| *v += 1).or_insert(1);
acc.entry(p2).and_modify(|v| *v += 1).or_insert(1);
acc
})
.into_iter()
.max_by(|(_, va), (_, vb)| va.cmp(&vb))
.unwrap()
}
pub fn solve_2<'a, T>(points: &'a [Point<T>], center: &Point<T>) -> &'a Point<T>
where
T: Eq
+ Hash
+ Copy
+ Sub<T, Output = T>
+ Add<T, Output = T>
+ Mul<T, Output = T>
+ Default
+ PartialEq
+ PartialOrd
+ Debug
+ From<i32>
+ cmp::Ord
+ Into<f64>,
{
let mut v = points
.iter()
.filter_map(|p| {
if p != center
&& !points
.iter()
.any(|c| c != p && c != center && contains(center, p, c))
{
Some((
p,
((p.x() - center.x()).into()).atan2((p.y() - center.y()).into()),
))
} else {
None
}
})
.collect::<Vec<(&'a Point<T>, f64)>>();
v.sort_by(|(_, b), (_, a)| {
if a > b {
Ordering::Greater
} else if (a - b).abs() < std::f64::EPSILON {
Ordering::Equal
} else {
Ordering::Less
}
});
v[199].0
}
pub fn part_1() -> usize {
solve_1(&DATA).1
}
pub fn part_2() -> i32 {
let p = solve_1(&DATA).0;
let p = solve_2(&DATA, p);
p.0 * 100 + p.1
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
lazy_static! {
static ref EXAMPLE: &'static str = r#".#..##.###...#######
##.############..##.
.#.######.########.#
.###.#######.####.#.
#####.##.#.##.###.##
..#####..#.#########
####################
#.####....###.#.#.##
##.#################
#####.##.###..####..
..######..##.#######
####.##.####...##..#
.#####..#.######.###
##...#.##########...
#.##########.#######
.####.#.###.###.#.##
....##.##.###..#####
.#.#.###########.###
#.#.#.#####.####.###
###.##.####.##.#..##"#;
}
#[test]
fn test_parse() {
assert_eq!(
parse::<u16>(
r###"##
.#"###
),
vec![Point(0, 0), Point(1, 0), Point(1, 1)]
);
}
#[test]
fn test_contains() {
assert!(contains(&Point(0, 0), &Point(2, 2), &Point(1, 1)));
}
#[test]
fn test_contains_1() {
assert!(contains(&Point(1, 0), &Point(3, 4), &Point(2, 2)));
assert!(contains(&Point(3, 4), &Point(1, 0), &Point(2, 2)));
assert!(!contains(&Point(1, 0), &Point(2, 2), &Point(3, 4)));
assert!(!contains(&Point(3, 4), &Point(2, 2), &Point(1, 0)));
assert!(!contains(&Point(1, 0), &Point(4, 0), &Point(1, 2)));
assert!(!contains(&Point(4, 3), &Point(3, 4), &Point(4, 4)));
}
#[test]
fn test_example_1() {
let q = parse::<i32>(
r######".#..#
.....
#####
....#
...##"######,
);
assert_eq!(solve_1(&q), (&Point(3, 4), 8));
}
#[test]
fn test_example_1_1() {
assert_eq!(
solve_1(&parse::<i32>(
r#"......#.#.
#..#.#....
..#######.
.#.#.###..
.#..#.....
..#....#.#
#..#....#.
.##.#..###
##...#..#.
.#....####"#
)),
(&Point(5, 8), 33)
);
}
#[test]
fn test_example_1_2() {
assert_eq!(
solve_1(&parse::<i32>(
r#"#.#...#.#.
.###....#.
.#....#...
##.#.#.#.#
....#.#.#.
.##..###.#
..#...##..
..##....##
......#...
.####.###."#
)),
(&Point(1, 2), 35)
);
}
#[test]
fn test_example_1_3() {
assert_eq!(
solve_1(&parse::<i32>(
r#".#..#..###
####.###.#
....###.#.
..###.##.#
##.##.#.#.
....###..#
..#.#..#.#
#..#.#.###
.##...##.#
.....#.#.."#
)),
(&Point(6, 3), 41)
);
}
#[test]
fn test_example_1_large() {
assert_eq!(solve_1(&parse(&EXAMPLE)), (&Point(11, 13), 210));
}
#[test]
fn test_example_2_large() {
assert_eq!(solve_2(&parse(&EXAMPLE), &Point(11, 13)), &Point(8, 2));
}
#[test]
fn test_distance() {
assert_eq!(distance(&Point(0, 0), &Point(10, 10)), 20);
}
#[bench]
fn bench_part_1(b: &mut Bencher) {
b.iter(part_1);
}
#[bench]
fn bench_part_2(b: &mut Bencher) {
b.iter(part_2);
}
}
| 21.639205 | 100 | 0.365761 |
fb878a6eaacfd7167a56d962928107d599497073
| 41,518 |
use {
super::{Pass, SparseDescriptors},
crate::{
animate::Pose,
light::{DirectionalLight, PointLight, SkyLight},
renderer::{
ray_tracing_transform_matrix_from_nalgebra, Context, Mesh,
PoseMesh, PositionNormalTangent3dUV, Renderable, Texture,
VertexType,
},
scene::Global3,
util::BumpaloCellList,
},
bumpalo::{collections::Vec as BVec, Bump},
bytemuck::{Pod, Zeroable},
color_eyre::Report,
eyre::ensure,
hecs::World,
illume::*,
nalgebra as na,
std::{collections::HashMap, convert::TryFrom as _, mem::size_of},
};
const MAX_INSTANCE_COUNT: u16 = 1024 * 32;
pub struct Input<'a> {
pub camera_global: Global3,
pub camera_projection: na::Projective3<f32>,
pub blases: &'a HashMap<Mesh, AccelerationStructure>,
}
pub struct Output {
pub tlas: AccelerationStructure,
pub albedo: Image,
pub normal_depth: Image,
pub emissive: Image,
pub direct: Image,
pub diffuse: Image,
}
pub struct RtPrepass {
pipeline_layout: PipelineLayout,
pipeline: RayTracingPipeline,
shader_binding_table: ShaderBindingTable,
tlas: AccelerationStructure,
scratch: Buffer,
globals_and_instances: MappableBuffer,
set: DescriptorSet,
per_frame_sets: [DescriptorSet; 2],
meshes: SparseDescriptors<Mesh>,
albedo: SparseDescriptors<Texture>,
normal: SparseDescriptors<Texture>,
output_albedo_image: Image,
output_normal_depth_image: Image,
output_emissive_image: Image,
output_direct_image: Image,
output_diffuse_image: Image,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct ShaderInstance {
transform: na::Matrix4<f32>,
mesh: u32,
albedo_sampler: u32,
albedo_factor: [f32; 4],
normal_sampler: u32,
normal_factor: f32,
anim: u32,
}
unsafe impl Zeroable for ShaderInstance {}
unsafe impl Pod for ShaderInstance {}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct ShaderPointLight {
position: [f32; 3],
_pad0: f32,
radiance: [f32; 3],
_pad1: f32,
}
unsafe impl Zeroable for ShaderPointLight {}
unsafe impl Pod for ShaderPointLight {}
impl RtPrepass {
pub fn new(
extent: Extent2d,
ctx: &mut Context,
blue_noise_buffer_256x256x128: Buffer,
) -> Result<Self, Report> {
// Create pipeline.
let set_layout = ctx.create_descriptor_set_layout(DescriptorSetLayoutInfo {
flags: DescriptorSetLayoutFlags::empty(),
bindings: vec![
// TLAS.
DescriptorSetLayoutBinding {
binding: 0,
ty: DescriptorType::AccelerationStructure,
count: 1,
stages: ShaderStageFlags::RAYGEN
| ShaderStageFlags::CLOSEST_HIT,
flags: DescriptorBindingFlags::empty(),
},
// Blue noise
DescriptorSetLayoutBinding {
binding: 1,
ty: DescriptorType::StorageBuffer,
count: 1,
stages: ShaderStageFlags::RAYGEN
| ShaderStageFlags::CLOSEST_HIT,
flags: DescriptorBindingFlags::empty(),
},
// Indices
DescriptorSetLayoutBinding {
binding: 2,
ty: DescriptorType::StorageBuffer,
count: MAX_INSTANCE_COUNT.into(),
stages: ShaderStageFlags::CLOSEST_HIT,
flags: DescriptorBindingFlags::PARTIALLY_BOUND | DescriptorBindingFlags::UPDATE_UNUSED_WHILE_PENDING,
},
// Vertex input.
DescriptorSetLayoutBinding {
binding: 3,
ty: DescriptorType::StorageBuffer,
count: MAX_INSTANCE_COUNT.into(),
stages: ShaderStageFlags::CLOSEST_HIT,
flags: DescriptorBindingFlags::PARTIALLY_BOUND | DescriptorBindingFlags::UPDATE_UNUSED_WHILE_PENDING,
},
// Textures
DescriptorSetLayoutBinding {
binding: 4,
ty: DescriptorType::CombinedImageSampler,
count: MAX_INSTANCE_COUNT.into(),
stages: ShaderStageFlags::CLOSEST_HIT,
flags: DescriptorBindingFlags::PARTIALLY_BOUND | DescriptorBindingFlags::UPDATE_UNUSED_WHILE_PENDING,
},
DescriptorSetLayoutBinding {
binding: 5,
ty: DescriptorType::CombinedImageSampler,
count: MAX_INSTANCE_COUNT.into(),
stages: ShaderStageFlags::CLOSEST_HIT,
flags: DescriptorBindingFlags::PARTIALLY_BOUND | DescriptorBindingFlags::UPDATE_UNUSED_WHILE_PENDING,
},
// G-Buffer
// Albedo
DescriptorSetLayoutBinding {
binding: 6,
ty: DescriptorType::StorageImage,
count: 1,
stages: ShaderStageFlags::RAYGEN,
flags: DescriptorBindingFlags::empty(),
},
// normal-depth
DescriptorSetLayoutBinding {
binding: 7,
ty: DescriptorType::StorageImage,
count: 1,
stages: ShaderStageFlags::RAYGEN,
flags: DescriptorBindingFlags::empty(),
},
// emissive
DescriptorSetLayoutBinding {
binding: 8,
ty: DescriptorType::StorageImage,
count: 1,
stages: ShaderStageFlags::RAYGEN,
flags: DescriptorBindingFlags::empty(),
},
// direct
DescriptorSetLayoutBinding {
binding: 9,
ty: DescriptorType::StorageImage,
count: 1,
stages: ShaderStageFlags::RAYGEN,
flags: DescriptorBindingFlags::empty(),
},
// diffuse
DescriptorSetLayoutBinding {
binding: 10,
ty: DescriptorType::StorageImage,
count: 1,
stages: ShaderStageFlags::RAYGEN,
flags: DescriptorBindingFlags::empty(),
},
],
})?;
let per_frame_set_layout = ctx.device.create_descriptor_set_layout(
DescriptorSetLayoutInfo {
flags: DescriptorSetLayoutFlags::empty(),
bindings: vec![
// Globals
DescriptorSetLayoutBinding {
binding: 0,
ty: DescriptorType::UniformBuffer,
count: 1,
stages: ShaderStageFlags::RAYGEN
| ShaderStageFlags::CLOSEST_HIT
| ShaderStageFlags::MISS,
flags: DescriptorBindingFlags::empty(),
},
// Scene
DescriptorSetLayoutBinding {
binding: 1,
ty: DescriptorType::StorageBuffer,
count: 1,
stages: ShaderStageFlags::CLOSEST_HIT,
flags: DescriptorBindingFlags::empty(),
},
// Lights
DescriptorSetLayoutBinding {
binding: 2,
ty: DescriptorType::StorageBuffer,
count: 1,
stages: ShaderStageFlags::CLOSEST_HIT,
flags: DescriptorBindingFlags::empty(),
},
// Animated vertices
DescriptorSetLayoutBinding {
binding: 3,
ty: DescriptorType::StorageBuffer,
count: 1024,
stages: ShaderStageFlags::CLOSEST_HIT,
flags: DescriptorBindingFlags::PARTIALLY_BOUND,
},
],
},
)?;
let pipeline_layout =
ctx.create_pipeline_layout(PipelineLayoutInfo {
sets: vec![set_layout.clone(), per_frame_set_layout.clone()],
push_constants: Vec::new(),
})?;
let viewport_rgen = RaygenShader::with_main(
ctx.create_shader_module(
Spirv::new(
include_bytes!("rt_prepass/viewport.rgen.spv").to_vec(),
)
.into(),
)?,
);
let primary_rmiss = MissShader::with_main(
ctx.create_shader_module(
Spirv::new(
include_bytes!("rt_prepass/primary.rmiss.spv").to_vec(),
)
.into(),
)?,
);
let primary_rchit = ClosestHitShader::with_main(
ctx.create_shader_module(
Spirv::new(
include_bytes!("rt_prepass/primary.rchit.spv").to_vec(),
)
.into(),
)?,
);
let diffuse_rmiss = MissShader::with_main(
ctx.create_shader_module(
Spirv::new(
include_bytes!("rt_prepass/diffuse.rmiss.spv").to_vec(),
)
.into(),
)?,
);
let diffuse_rchit = ClosestHitShader::with_main(
ctx.create_shader_module(
Spirv::new(
include_bytes!("rt_prepass/diffuse.rchit.spv").to_vec(),
)
.into(),
)?,
);
let shadow_rmiss = MissShader::with_main(
ctx.create_shader_module(
Spirv::new(include_bytes!("common/shadow.rmiss.spv").to_vec())
.into(),
)?,
);
let pipeline =
ctx.create_ray_tracing_pipeline(RayTracingPipelineInfo {
shaders: vec![
viewport_rgen.into(),
primary_rmiss.into(),
primary_rchit.into(),
diffuse_rmiss.into(),
diffuse_rchit.into(),
shadow_rmiss.into(),
],
groups: vec![
RayTracingShaderGroupInfo::Raygen { raygen: 0 },
RayTracingShaderGroupInfo::Miss { miss: 1 },
RayTracingShaderGroupInfo::Miss { miss: 3 },
RayTracingShaderGroupInfo::Miss { miss: 5 },
RayTracingShaderGroupInfo::Triangles {
any_hit: None,
closest_hit: Some(2),
},
RayTracingShaderGroupInfo::Triangles {
any_hit: None,
closest_hit: Some(4),
},
],
max_recursion_depth: 10,
layout: pipeline_layout.clone(),
})?;
let shader_binding_table = ctx.create_shader_binding_table(
&pipeline,
ShaderBindingTableInfo {
raygen: Some(0),
miss: &[1, 2, 3],
hit: &[4, 5],
callable: &[],
},
)?;
tracing::trace!("RT pipeline created");
// Creating TLAS.
let tlas_sizes = ctx.get_acceleration_structure_build_sizes(
AccelerationStructureLevel::Top,
AccelerationStructureBuildFlags::PREFER_FAST_BUILD,
&[AccelerationStructureGeometryInfo::Instances {
max_primitive_count: MAX_INSTANCE_COUNT.into(),
}],
);
let tlas_buffer = ctx.create_buffer(BufferInfo {
align: 255,
size: tlas_sizes.acceleration_structure_size,
usage: BufferUsage::ACCELERATION_STRUCTURE_STORAGE,
})?;
let tlas =
ctx.create_acceleration_structure(AccelerationStructureInfo {
level: AccelerationStructureLevel::Top,
region: BufferRegion::whole(tlas_buffer),
})?;
tracing::trace!("TLAS created");
// Allocate scratch memory for TLAS building.
let scratch = ctx.create_buffer(BufferInfo {
align: 255,
size: tlas_sizes.build_scratch_size,
usage: BufferUsage::DEVICE_ADDRESS,
})?;
tracing::trace!("TLAS scratch allocated");
let globals_and_instances = ctx.create_mappable_buffer(
BufferInfo {
align: globals_and_instances_align(),
size: globals_and_instances_size(),
usage: BufferUsage::UNIFORM
| BufferUsage::STORAGE
| BufferUsage::ACCELERATION_STRUCTURE_BUILD_INPUT
| BufferUsage::DEVICE_ADDRESS,
},
MemoryUsage::FAST_DEVICE_ACCESS,
)?;
tracing::trace!("Globals and instances buffer created");
// Image matching surface extent.
let output_albedo_image = ctx.create_image(ImageInfo {
extent: extent.into(),
format: Format::RGBA8Unorm,
levels: 1,
layers: 1,
samples: Samples::Samples1,
usage: ImageUsage::STORAGE | ImageUsage::SAMPLED,
})?;
// View for whole image
let output_albedo_view = ctx.create_image_view(ImageViewInfo::new(
output_albedo_image.clone(),
))?;
let output_normal_depth_image = ctx.create_image(ImageInfo {
extent: extent.into(),
format: Format::RGBA32Sfloat,
levels: 1,
layers: 1,
samples: Samples::Samples1,
usage: ImageUsage::STORAGE | ImageUsage::SAMPLED,
})?;
// View for whole image
let output_normal_depth_view = ctx.create_image_view(
ImageViewInfo::new(output_normal_depth_image.clone()),
)?;
let output_emissive_image = ctx.create_image(ImageInfo {
extent: extent.into(),
format: Format::RGBA32Sfloat,
levels: 1,
layers: 1,
samples: Samples::Samples1,
usage: ImageUsage::STORAGE | ImageUsage::SAMPLED,
})?;
// View for whole image
let output_emissive_view = ctx.create_image_view(
ImageViewInfo::new(output_emissive_image.clone()),
)?;
let output_direct_image = ctx.create_image(ImageInfo {
extent: extent.into(),
format: Format::RGBA32Sfloat,
levels: 1,
layers: 1,
samples: Samples::Samples1,
usage: ImageUsage::STORAGE | ImageUsage::SAMPLED,
})?;
// View for whole image
let output_direct_view = ctx.create_image_view(ImageViewInfo::new(
output_direct_image.clone(),
))?;
let output_diffuse_image = ctx.create_image(ImageInfo {
extent: extent.into(),
format: Format::RGBA32Sfloat,
levels: 1,
layers: 1,
samples: Samples::Samples1,
usage: ImageUsage::STORAGE | ImageUsage::SAMPLED,
})?;
// View for whole image
let output_diffuse_view = ctx.create_image_view(ImageViewInfo::new(
output_diffuse_image.clone(),
))?;
tracing::trace!("Feature images created");
let set = ctx.create_descriptor_set(DescriptorSetInfo {
layout: set_layout.clone(),
})?;
let per_frame_set0 = ctx.create_descriptor_set(DescriptorSetInfo {
layout: per_frame_set_layout.clone(),
})?;
let per_frame_set1 = ctx.create_descriptor_set(DescriptorSetInfo {
layout: per_frame_set_layout.clone(),
})?;
tracing::trace!("Descriptor sets created");
ctx.update_descriptor_sets(
&[
WriteDescriptorSet {
set: &set,
binding: 0,
element: 0,
descriptors: Descriptors::AccelerationStructure(
std::slice::from_ref(&tlas),
),
},
WriteDescriptorSet {
set: &set,
binding: 1,
element: 0,
descriptors: Descriptors::StorageBuffer(&[(
blue_noise_buffer_256x256x128.clone(),
0,
blue_noise_buffer_256x256x128.info().size,
)]),
},
WriteDescriptorSet {
set: &set,
binding: 6,
element: 0,
descriptors: Descriptors::StorageImage(&[
(output_albedo_view.clone(), Layout::General),
(output_normal_depth_view.clone(), Layout::General),
(output_emissive_view.clone(), Layout::General),
(output_direct_view.clone(), Layout::General),
(output_diffuse_view.clone(), Layout::General),
]),
},
WriteDescriptorSet {
set: &per_frame_set0,
binding: 0,
element: 0,
descriptors: Descriptors::UniformBuffer(&[(
globals_and_instances.clone(),
globals_offset(0),
globals_size(),
)]),
},
WriteDescriptorSet {
set: &per_frame_set1,
binding: 0,
element: 0,
descriptors: Descriptors::UniformBuffer(&[(
globals_and_instances.clone(),
globals_offset(1),
globals_size(),
)]),
},
WriteDescriptorSet {
set: &per_frame_set0,
binding: 1,
element: 0,
descriptors: Descriptors::StorageBuffer(&[(
globals_and_instances.clone(),
instances_offset(0),
instances_size(),
)]),
},
WriteDescriptorSet {
set: &per_frame_set1,
binding: 1,
element: 0,
descriptors: Descriptors::StorageBuffer(&[(
globals_and_instances.clone(),
instances_offset(1),
instances_size(),
)]),
},
WriteDescriptorSet {
set: &per_frame_set0,
binding: 2,
element: 0,
descriptors: Descriptors::StorageBuffer(&[(
globals_and_instances.clone(),
pointlight_offset(0),
pointlight_size(),
)]),
},
WriteDescriptorSet {
set: &per_frame_set1,
binding: 2,
element: 0,
descriptors: Descriptors::StorageBuffer(&[(
globals_and_instances.clone(),
pointlight_offset(1),
pointlight_size(),
)]),
},
],
&[],
);
Ok(RtPrepass {
pipeline_layout,
pipeline,
shader_binding_table,
tlas,
scratch,
globals_and_instances,
set,
per_frame_sets: [per_frame_set0, per_frame_set1],
output_albedo_image,
output_normal_depth_image,
output_emissive_image,
output_direct_image,
output_diffuse_image,
meshes: SparseDescriptors::new(),
albedo: SparseDescriptors::new(),
normal: SparseDescriptors::new(),
})
}
}
impl<'a> Pass<'a> for RtPrepass {
type Input = Input<'a>;
type Output = Output;
#[tracing::instrument(skip(
self, input, frame, wait, signal, fence, ctx, world, bump
))]
fn draw(
&mut self,
input: Input<'a>,
frame: u64,
wait: &[(PipelineStageFlags, Semaphore)],
signal: &[Semaphore],
fence: Option<&Fence>,
ctx: &mut Context,
world: &mut World,
bump: &Bump,
) -> Result<Output, Report> {
tracing::trace!("RtPrepass::draw");
let findex = (frame & 1) as u32;
let storage_buffers = BumpaloCellList::new();
let combined_image_samples = BumpaloCellList::new();
let bind_ray_tracing_descriptor_sets_array;
// https://microsoft.github.io/DirectX-Specs/d3d/Raytracing.html#general-tips-for-building-acceleration-structures
//
// > Rebuild top-level acceleration structure every frame
// Only updating instead of rebuilding is rarely the right thing to
// do. Rebuilds for a few thousand instances are very fast,
// and having a good quality top-level acceleration structure can have
// a significant payoff (bad quality has a higher cost further
// up in the tree).
let mut instances = BVec::new_in(bump);
let mut acc_instances = BVec::new_in(bump);
let mut anim_vertices_descriptors = BVec::new_in(bump);
let mut writes = BVec::new_in(bump);
let mut encoder = ctx.queue.create_encoder()?;
let mut query = world.query::<(
&Renderable,
&Global3,
Option<&Pose>,
Option<&PoseMesh>,
)>();
tracing::trace!("Query all renderable");
for (entity, (renderable, global, pose, pose_mesh)) in query.iter() {
if let Some(blas) = input.blases.get(&renderable.mesh) {
let blas_address =
ctx.get_acceleration_structure_device_address(blas);
// let m = match renderable.transform {
// Some(t) => global.to_homogeneous() * t,
// None => global.to_homogeneous(),
// };
let m = global.to_homogeneous();
let (mut mesh_index, new) =
self.meshes.index(renderable.mesh.clone());
if new {
let vectors = renderable
.mesh
.bindings()
.iter()
.find(|binding| {
binding.layout
== PositionNormalTangent3dUV::layout()
})
.unwrap();
let vectors_buffer = vectors.buffer.clone();
let vectors_offset = vectors.offset;
let vectors_size: u64 = vectors.layout.stride as u64
* renderable.mesh.vertex_count() as u64;
let indices = renderable.mesh.indices().unwrap();
let indices_buffer = indices.buffer.clone();
let indices_offset = indices.offset;
let indices_size: u64 = indices.index_type.size() as u64
* renderable.mesh.count() as u64;
assert_eq!(vectors_offset & 15, 0);
assert_eq!(indices_offset & 15, 0);
// FIXME: Leak
let indices_tuple = storage_buffers.push_in(
(indices_buffer, indices_offset, indices_size),
bump,
);
let vectors_tuple = storage_buffers.push_in(
(vectors_buffer, vectors_offset, vectors_size),
bump,
);
let indices_desc = Descriptors::StorageBuffer(
std::slice::from_ref(indices_tuple),
);
let vectors_desc = Descriptors::StorageBuffer(
std::slice::from_ref(vectors_tuple),
);
writes.push(WriteDescriptorSet {
set: &self.set,
binding: 2,
element: mesh_index,
descriptors: indices_desc,
});
writes.push(WriteDescriptorSet {
set: &self.set,
binding: 3,
element: mesh_index,
descriptors: vectors_desc,
});
}
let anim = if let (Some(_), Some(pose_mesh)) = (pose, pose_mesh)
{
let vectors = pose_mesh
.bindings()
.iter()
.find(|binding| {
binding.layout
== PositionNormalTangent3dUV::layout()
})
.unwrap();
let vectors_buffer = vectors.buffer.clone();
let vectors_offset = vectors.offset;
let vectors_size: u64 = vectors.layout.stride as u64
* renderable.mesh.vertex_count() as u64;
mesh_index = anim_vertices_descriptors.len() as u32;
anim_vertices_descriptors.push((
vectors_buffer,
vectors_offset,
vectors_size,
));
let blas = renderable.mesh.build_pose_triangles_blas(
pose_mesh,
&mut encoder,
&ctx.device,
bump,
)?;
// FIXME: blas leak
let blas_address = ctx
.device
.get_acceleration_structure_device_address(&blas);
acc_instances.push(
AccelerationStructureInstance::new(blas_address)
.with_transform(
ray_tracing_transform_matrix_from_nalgebra(&m),
),
);
true
} else {
acc_instances.push(
AccelerationStructureInstance::new(blas_address)
.with_transform(
ray_tracing_transform_matrix_from_nalgebra(&m),
),
);
false
};
let albedo_index = if let Some(albedo) =
&renderable.material.albedo
{
let (albedo_index, new) = self.albedo.index(albedo.clone());
if new {
let descriptors = Descriptors::CombinedImageSampler(
std::slice::from_ref(
combined_image_samples.push_in(
(
albedo.image.clone(),
Layout::General,
albedo.sampler.clone(),
),
bump,
),
),
);
writes.push(WriteDescriptorSet {
set: &self.set,
binding: 4,
element: albedo_index,
descriptors,
});
}
albedo_index + 1
} else {
0
};
let normal_index = if let Some(normal) =
&renderable.material.normal
{
let (normal_index, new) = self.normal.index(normal.clone());
if new {
let descriptors = Descriptors::CombinedImageSampler(
std::slice::from_ref(
combined_image_samples.push_in(
(
normal.image.clone(),
Layout::General,
normal.sampler.clone(),
),
bump,
),
),
);
writes.push(WriteDescriptorSet {
set: &self.set,
binding: 5,
element: normal_index,
descriptors,
});
}
normal_index + 1
} else {
0
};
instances.push(ShaderInstance {
transform: m,
mesh: mesh_index,
albedo_sampler: albedo_index,
normal_sampler: normal_index,
albedo_factor: {
let [r, g, b, a] = renderable.material.albedo_factor;
[
r.into_inner(),
g.into_inner(),
b.into_inner(),
a.into_inner(),
]
},
normal_factor: renderable
.material
.normal_factor
.into_inner(),
anim: anim as u32,
});
} else {
tracing::error!("Missing BLAS for mesh @ {:?}", entity);
}
}
if !anim_vertices_descriptors.is_empty() {
writes.push(WriteDescriptorSet {
set: &self.per_frame_sets[findex as usize],
binding: 3,
element: 0,
descriptors: Descriptors::StorageBuffer(
&anim_vertices_descriptors,
),
});
}
tracing::trace!("Update descriptors");
ctx.update_descriptor_sets(&writes, &[]);
drop(writes);
ensure!(
instances.len() <= MAX_INSTANCE_COUNT.into(),
"Too many instances"
);
ensure!(
acc_instances.len() <= MAX_INSTANCE_COUNT.into(),
"Too many instances"
);
ensure!(u32::try_from(instances.len()).is_ok(), "Too many instances");
tracing::trace!("Build TLAS");
// Sync BLAS and TLAS builds.
encoder.pipeline_barrier(
PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD,
PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD,
);
let infos = bump.alloc([AccelerationStructureBuildGeometryInfo {
src: None,
dst: self.tlas.clone(),
flags: AccelerationStructureBuildFlags::PREFER_FAST_BUILD,
geometries: bump.alloc([
AccelerationStructureGeometry::Instances {
flags: GeometryFlags::OPAQUE,
data: ctx
.get_buffer_device_address(&self.globals_and_instances)
.unwrap()
.offset(acc_instances_offset(findex)),
primitive_count: instances.len() as u32,
},
]),
scratch: ctx.get_buffer_device_address(&self.scratch).unwrap(),
}]);
encoder.build_acceleration_structure(infos);
tracing::trace!("Update Globals");
ctx.write_buffer(
&mut self.globals_and_instances,
acc_instances_offset(findex),
&acc_instances,
)?;
tracing::trace!("Update Globals");
ctx.write_buffer(
&mut self.globals_and_instances,
instances_offset(findex),
&instances,
)?;
let mut pointlights: BVec<ShaderPointLight> =
BVec::with_capacity_in(32, bump);
pointlights.extend(
world
.query::<(&PointLight, &Global3)>()
.iter()
.map(|(_, (pl, global))| ShaderPointLight {
position: global.iso.translation.vector.into(),
radiance: pl.radiance,
_pad0: 0.0,
_pad1: 0.0,
})
.take(32),
);
tracing::trace!("Update Globals");
ctx.write_buffer(
&mut self.globals_and_instances,
pointlight_offset(findex),
&pointlights,
)?;
let dirlight = world
.query::<&DirectionalLight>()
.iter()
.next()
.map(|(_, dl)| GlobalsDirLight {
rad: dl.radiance,
dir: dl.direction.into(),
_pad0: 0.0,
_pad1: 0.0,
})
.unwrap_or(GlobalsDirLight {
rad: [0.0; 3],
dir: [0.0; 3],
_pad0: 0.0,
_pad1: 0.0,
});
let skylight = world
.query::<&SkyLight>()
.iter()
.next()
.map(|(_, sl)| sl.radiance)
.unwrap_or_default();
let globals = Globals {
camera: GlobalsCamera {
view: input.camera_global.to_homogeneous(),
// iview: input.camera_global.inverse().to_homogeneous(),
iview: na::Matrix4::identity(),
proj: input.camera_projection.to_homogeneous(),
iproj: input.camera_projection.inverse().to_homogeneous(),
},
dirlight,
skylight,
plights: pointlights.len() as u32,
// frame: frame as u32,
frame: 0,
shadow_rays: 8,
diffuse_rays: 16,
pad: 0.0,
};
tracing::trace!("Update Globals");
ctx.write_buffer(
&mut self.globals_and_instances,
globals_offset(findex),
std::slice::from_ref(&globals),
)?;
tracing::trace!("Trace rays");
encoder.bind_ray_tracing_pipeline(&self.pipeline);
bind_ray_tracing_descriptor_sets_array = [
self.set.clone(),
self.per_frame_sets[findex as usize].clone(),
];
encoder.bind_ray_tracing_descriptor_sets(
&self.pipeline_layout,
0,
&bind_ray_tracing_descriptor_sets_array,
&[],
);
// Sync storage image access from last frame.
let images = [
ImageLayoutTransition::initialize_whole(
&self.output_albedo_image,
Layout::General,
)
.into(),
ImageLayoutTransition::initialize_whole(
&self.output_normal_depth_image,
Layout::General,
)
.into(),
ImageLayoutTransition::initialize_whole(
&self.output_emissive_image,
Layout::General,
)
.into(),
ImageLayoutTransition::initialize_whole(
&self.output_direct_image,
Layout::General,
)
.into(),
ImageLayoutTransition::initialize_whole(
&self.output_diffuse_image,
Layout::General,
)
.into(),
];
encoder.image_barriers(
PipelineStageFlags::FRAGMENT_SHADER, // FIXME: Compure barrier.
PipelineStageFlags::RAY_TRACING_SHADER,
&images,
);
// Sync TLAS build with ray-tracing shader where it will be used.
encoder.pipeline_barrier(
PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD,
PipelineStageFlags::RAY_TRACING_SHADER,
);
// Perform ray-trace operation.
encoder.trace_rays(
&self.shader_binding_table,
self.output_albedo_image.info().extent.into_3d(),
);
// Sync storage image access from last frame.
let images = [
ImageLayoutTransition::transition_whole(
&self.output_albedo_image,
Layout::General..Layout::ShaderReadOnlyOptimal,
)
.into(),
ImageLayoutTransition::transition_whole(
&self.output_normal_depth_image,
Layout::General..Layout::ShaderReadOnlyOptimal,
)
.into(),
ImageLayoutTransition::transition_whole(
&self.output_emissive_image,
Layout::General..Layout::ShaderReadOnlyOptimal,
)
.into(),
ImageLayoutTransition::transition_whole(
&self.output_direct_image,
Layout::General..Layout::ShaderReadOnlyOptimal,
)
.into(),
ImageLayoutTransition::transition_whole(
&self.output_diffuse_image,
Layout::General..Layout::ShaderReadOnlyOptimal,
)
.into(),
];
encoder.image_barriers(
PipelineStageFlags::RAY_TRACING_SHADER,
PipelineStageFlags::FRAGMENT_SHADER,
&images,
);
let cbuf = encoder.finish();
tracing::trace!("Submitting");
ctx.queue.submit(wait, cbuf, signal, fence);
Ok(Output {
albedo: self.output_albedo_image.clone(),
normal_depth: self.output_normal_depth_image.clone(),
emissive: self.output_emissive_image.clone(),
direct: self.output_direct_image.clone(),
diffuse: self.output_diffuse_image.clone(),
tlas: self.tlas.clone(),
})
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
struct GlobalsCamera {
view: na::Matrix4<f32>,
proj: na::Matrix4<f32>,
iview: na::Matrix4<f32>,
iproj: na::Matrix4<f32>,
}
unsafe impl Zeroable for GlobalsCamera {}
unsafe impl Pod for GlobalsCamera {}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
struct GlobalsDirLight {
dir: [f32; 3],
_pad0: f32,
rad: [f32; 3],
_pad1: f32,
}
unsafe impl Zeroable for GlobalsDirLight {}
unsafe impl Pod for GlobalsDirLight {}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
struct Globals {
camera: GlobalsCamera,
dirlight: GlobalsDirLight,
skylight: [f32; 3],
pad: f32,
plights: u32,
frame: u32,
shadow_rays: u32,
diffuse_rays: u32,
}
unsafe impl Zeroable for Globals {}
unsafe impl Pod for Globals {}
const fn globals_size() -> u64 {
size_of::<Globals>() as u64
}
fn globals_offset(frame: u32) -> u64 {
u64::from(frame) * align_up(255u8, globals_size()).unwrap()
}
fn globals_end(frame: u32) -> u64 {
globals_offset(frame) + globals_size()
}
const fn instances_size() -> u64 {
size_of::<[ShaderInstance; MAX_INSTANCE_COUNT as usize]>() as u64
}
fn instances_offset(frame: u32) -> u64 {
align_up(255u8, globals_end(1)).unwrap()
+ u64::from(frame) * align_up(255u8, instances_size()).unwrap()
}
fn instances_end(frame: u32) -> u64 {
instances_offset(frame) + instances_size()
}
const fn pointlight_size() -> u64 {
size_of::<[ShaderPointLight; 32]>() as u64
}
fn pointlight_offset(frame: u32) -> u64 {
align_up(255u8, instances_end(1)).unwrap()
+ u64::from(frame) * align_up(255u8, pointlight_size()).unwrap()
}
fn pointlight_end(frame: u32) -> u64 {
pointlight_offset(frame) + pointlight_size()
}
const fn acc_instances_size() -> u64 {
size_of::<[AccelerationStructureInstance; MAX_INSTANCE_COUNT as usize]>()
as u64
}
fn acc_instances_offset(frame: u32) -> u64 {
align_up(255u8, pointlight_end(1)).unwrap()
+ u64::from(frame) * align_up(255u8, acc_instances_size()).unwrap()
}
fn acc_instances_end(frame: u32) -> u64 {
acc_instances_offset(frame) + acc_instances_size()
}
const fn globals_and_instances_align() -> u64 {
255
}
fn globals_and_instances_size() -> u64 {
acc_instances_end(1)
}
| 34.369205 | 125 | 0.480804 |
695844717421def113ff727fe37f135a31684fe1
| 1,854 |
use base64::DecodeError;
use core::num::ParseIntError;
use ed25519_dalek;
use rmp_serde as serde_mgpk;
use serde_cbor;
use serde_json;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("Error during Serialization: {0}")]
SerializationError(String),
#[error("JSON Serialization error")]
JSONSerializationError {
#[from]
source: serde_json::Error,
},
#[error("CBOR Serialization error")]
CBORSerializationError {
#[from]
source: serde_cbor::Error,
},
#[error("MessagePack Serialization error")]
MsgPackSerializationError {
#[from]
source: serde_mgpk::encode::Error,
},
#[error("Error parsing numerical value: {source}")]
IntegerParseValue {
#[from]
source: ParseIntError,
},
#[error("Error while applying event: {0}")]
SemanticError(String),
#[error("Event signature verification faulty")]
FaultySignatureVerification,
#[error("Error while applying event: out of order event")]
EventOutOfOrderError,
#[error("Error while aplying event: duplicate event")]
EventDuplicateError,
#[error("Not enough signatures while verifing")]
NotEnoughSigsError,
#[error("Deserialization error")]
DeserializationError,
#[error("Identifier is not indexed into the DB")]
NotIndexedError,
#[error("Identifier ID is already present in the DB")]
IdentifierPresentError,
#[error("Base64 Decoding error")]
Base64DecodingError {
#[from]
source: DecodeError,
},
#[error("Improper Prefix Type")]
ImproperPrefixType,
#[error("Storage error")]
StorageError,
#[error(transparent)]
Ed25519DalekSignatureError(#[from] ed25519_dalek::SignatureError),
#[error(transparent)]
SledError(#[from] sled::Error),
}
| 23.175 | 70 | 0.655879 |
ccdb805277237baa0f95cc8c3192df0df6bb0fdd
| 1,503 |
#![allow(unused_imports)]
use frame_support::{parameter_types, traits::EnsureOneOf, PalletId};
use frame_system::EnsureRoot;
use sp_core::u32_trait::{_1, _2, _3, _5};
use sp_runtime::{Percent, Permill};
use crate::*;
parameter_types! {
pub const ProposalBond: Permill = Permill::from_percent(5);
pub const ProposalBondMinimum: Balance = 1 * DOLLARS;
pub const SpendPeriod: BlockNumber = 1 * DAYS;
pub const Burn: Permill = Permill::from_percent(50);
pub const TipCountdown: BlockNumber = 1 * DAYS;
pub const TipFindersFee: Percent = Percent::from_percent(20);
pub const TipReportDepositBase: Balance = 1 * DOLLARS;
pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
pub const MaxApprovals: u32 = 100;
}
impl pallet_treasury::Config for Runtime {
type PalletId = TreasuryPalletId;
type Currency = Balances;
type ApproveOrigin = EnsureOneOf<
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
>;
type RejectOrigin = EnsureOneOf<
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>,
>;
type Event = Event;
type OnSlash = ();
type ProposalBond = ProposalBond;
type ProposalBondMinimum = ProposalBondMinimum;
type ProposalBondMaximum = ();
type SpendPeriod = SpendPeriod;
type Burn = Burn;
type BurnDestination = ();
type SpendFunds = Bounties;
type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;
type MaxApprovals = MaxApprovals;
}
| 33.4 | 84 | 0.760479 |
7620f7dfe5518277106f1dd2fe471d21f94d3eed
| 4,919 |
//! Utilities for loading and transposing data from memory.
//! This is useful for SPMD-style operations.
use arrayref::array_ref;
use self::arch::{
__m128i, __m256i, _mm256_castsi128_si256, _mm256_inserti128_si256, _mm256_unpackhi_epi32,
_mm256_unpackhi_epi64, _mm256_unpacklo_epi32, _mm256_unpacklo_epi64, _mm_loadu_si128,
_mm_unpackhi_epi32, _mm_unpackhi_epi64, _mm_unpacklo_epi32, _mm_unpacklo_epi64,
};
#[cfg(target_arch = "x86")]
use std::arch::x86 as arch;
#[cfg(target_arch = "x86_64")]
use std::arch::x86_64 as arch;
#[inline(always)]
/// Loads four u32s (little-endian), potentially unaligned
unsafe fn load_u32x4(slice: &[u8; 16]) -> __m128i {
_mm_loadu_si128(slice as *const [u8; 16] as *const __m128i)
}
/// Load 32 bytes (1 u32x8) out of each lane of `data`, transposed.
#[inline]
#[target_feature(enable = "avx2")]
unsafe fn load_transpose8(data: [&[u8; 32]; 8]) -> [__m256i; 8] {
#[inline(always)]
/// Concatenate two u32x4s into a single u32x8
unsafe fn cat2x4(a: __m128i, b: __m128i) -> __m256i {
// `vinserti128`
_mm256_inserti128_si256(_mm256_castsi128_si256(a), b, 1)
}
let l04 = cat2x4(
load_u32x4(array_ref![data[0], 0, 16]),
load_u32x4(array_ref![data[4], 0, 16]),
);
let l15 = cat2x4(
load_u32x4(array_ref![data[1], 0, 16]),
load_u32x4(array_ref![data[5], 0, 16]),
);
let l26 = cat2x4(
load_u32x4(array_ref![data[2], 0, 16]),
load_u32x4(array_ref![data[6], 0, 16]),
);
let l37 = cat2x4(
load_u32x4(array_ref![data[3], 0, 16]),
load_u32x4(array_ref![data[7], 0, 16]),
);
let h04 = cat2x4(
load_u32x4(array_ref![data[0], 16, 16]),
load_u32x4(array_ref![data[4], 16, 16]),
);
let h15 = cat2x4(
load_u32x4(array_ref![data[1], 16, 16]),
load_u32x4(array_ref![data[5], 16, 16]),
);
let h26 = cat2x4(
load_u32x4(array_ref![data[2], 16, 16]),
load_u32x4(array_ref![data[6], 16, 16]),
);
let h37 = cat2x4(
load_u32x4(array_ref![data[3], 16, 16]),
load_u32x4(array_ref![data[7], 16, 16]),
);
// [data[0][0], data[1][0], data[0][1], data[1][1], data[4][0], data[5][0], data[4][1], data[5][1]]
let a0145 = _mm256_unpacklo_epi32(l04, l15);
// [data[0][2], data[1][2], data[0][3], data[1][3], data[4][2], data[5][2], data[4][3], data[5][3]]
let b0145 = _mm256_unpackhi_epi32(l04, l15);
let a2367 = _mm256_unpacklo_epi32(l26, l37);
let b2367 = _mm256_unpackhi_epi32(l26, l37);
let c0145 = _mm256_unpacklo_epi32(h04, h15);
let d0145 = _mm256_unpackhi_epi32(h04, h15);
let c2367 = _mm256_unpacklo_epi32(h26, h37);
let d2367 = _mm256_unpackhi_epi32(h26, h37);
[
_mm256_unpacklo_epi64(a0145, a2367),
_mm256_unpackhi_epi64(a0145, a2367),
_mm256_unpacklo_epi64(b0145, b2367),
_mm256_unpackhi_epi64(b0145, b2367),
_mm256_unpacklo_epi64(c0145, c2367),
_mm256_unpackhi_epi64(c0145, c2367),
_mm256_unpacklo_epi64(d0145, d2367),
_mm256_unpackhi_epi64(d0145, d2367),
]
}
macro_rules! get_blocks {
($data: ident, ($($lane: tt)*), $from: expr, $width: expr) => ([$(array_ref![&$data($lane), $from, $width]),*]);
}
#[inline]
#[target_feature(enable = "avx2")]
pub unsafe fn load_16x8_avx2<'a, F: Fn(usize) -> &'a [u8; 64]>(data: F) -> [__m256i; 16] {
// We're using transmute to concatenate arrays; not ideal, but it works
core::mem::transmute::<[[__m256i; 8]; 2], [__m256i; 16]>([
load_transpose8(get_blocks!(data, (0 1 2 3 4 5 6 7), 0, 32)),
load_transpose8(get_blocks!(data, (0 1 2 3 4 5 6 7), 32, 32)),
])
}
/// Load 16 bytes (1 u32x4) out of each lane of `data`, transposed.
#[inline]
#[target_feature(enable = "sse2")]
unsafe fn load_transpose4(data: [&[u8; 16]; 4]) -> [__m128i; 4] {
let i0 = load_u32x4(data[0]);
let i1 = load_u32x4(data[1]);
let i2 = load_u32x4(data[2]);
let i3 = load_u32x4(data[3]);
// [data[0][0], data[1][0], data[0][1], data[1][1]]
let l01 = _mm_unpacklo_epi32(i0, i1);
// [data[0][2], data[1][2], data[0][3], data[1][3]]
let h01 = _mm_unpackhi_epi32(i0, i1);
let l23 = _mm_unpacklo_epi32(i2, i3);
let h23 = _mm_unpackhi_epi32(i2, i3);
[
_mm_unpacklo_epi64(l01, l23),
_mm_unpackhi_epi64(l01, l23),
_mm_unpacklo_epi64(h01, h23),
_mm_unpackhi_epi64(h01, h23),
]
}
#[inline]
#[target_feature(enable = "sse2")]
pub unsafe fn load_16x4_sse2<'a, F: Fn(usize) -> &'a [u8; 64]>(data: F) -> [__m128i; 16] {
core::mem::transmute::<[[__m128i; 4]; 4], [__m128i; 16]>([
load_transpose4(get_blocks!(data, (0 1 2 3), 0, 16)),
load_transpose4(get_blocks!(data, (0 1 2 3), 16, 16)),
load_transpose4(get_blocks!(data, (0 1 2 3), 32, 16)),
load_transpose4(get_blocks!(data, (0 1 2 3), 48, 16)),
])
}
| 37.265152 | 116 | 0.614759 |
169e9bf18eceba322b80009b3b0d1b959a0d260e
| 6,057 |
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crossbeam::{SendError, TrySendError};
use kvproto::raft_cmdpb::RaftCmdRequest;
use kvproto::raft_serverpb::RaftMessage;
use crate::store::fsm::RaftRouter;
use crate::store::{
Callback, CasualMessage, LocalReader, PeerMsg, RaftCommand, SignificantMsg, StoreMsg,
};
use crate::{DiscardReason, Error as RaftStoreError, Result as RaftStoreResult};
use engine_rocks::RocksEngine;
use raft::SnapshotStatus;
use txn_types::TxnExtra;
/// Routes messages to the raftstore.
pub trait RaftStoreRouter: Send + Clone {
/// Sends RaftMessage to local store.
fn send_raft_msg(&self, msg: RaftMessage) -> RaftStoreResult<()>;
/// Sends RaftCmdRequest to local store.
fn send_command(&self, req: RaftCmdRequest, cb: Callback<RocksEngine>) -> RaftStoreResult<()> {
self.send_command_txn_extra(req, TxnExtra::default(), cb)
}
/// Sends RaftCmdRequest to local store with txn extras.
fn send_command_txn_extra(
&self,
req: RaftCmdRequest,
txn_extra: TxnExtra,
cb: Callback<RocksEngine>,
) -> RaftStoreResult<()>;
/// Sends a significant message. We should guarantee that the message can't be dropped.
fn significant_send(&self, region_id: u64, msg: SignificantMsg) -> RaftStoreResult<()>;
/// Reports the peer being unreachable to the Region.
fn report_unreachable(&self, region_id: u64, to_peer_id: u64) -> RaftStoreResult<()> {
self.significant_send(
region_id,
SignificantMsg::Unreachable {
region_id,
to_peer_id,
},
)
}
fn broadcast_unreachable(&self, store_id: u64);
/// Reports the sending snapshot status to the peer of the Region.
fn report_snapshot_status(
&self,
region_id: u64,
to_peer_id: u64,
status: SnapshotStatus,
) -> RaftStoreResult<()> {
self.significant_send(
region_id,
SignificantMsg::SnapshotStatus {
region_id,
to_peer_id,
status,
},
)
}
fn casual_send(&self, region_id: u64, msg: CasualMessage<RocksEngine>) -> RaftStoreResult<()>;
}
#[derive(Clone)]
pub struct RaftStoreBlackHole;
impl RaftStoreRouter for RaftStoreBlackHole {
/// Sends RaftMessage to local store.
fn send_raft_msg(&self, _: RaftMessage) -> RaftStoreResult<()> {
Ok(())
}
/// Sends RaftCmdRequest to local store with txn extra.
fn send_command_txn_extra(
&self,
_: RaftCmdRequest,
_: TxnExtra,
_: Callback<RocksEngine>,
) -> RaftStoreResult<()> {
Ok(())
}
/// Sends a significant message. We should guarantee that the message can't be dropped.
fn significant_send(&self, _: u64, _: SignificantMsg) -> RaftStoreResult<()> {
Ok(())
}
fn broadcast_unreachable(&self, _: u64) {}
fn casual_send(&self, _: u64, _: CasualMessage<RocksEngine>) -> RaftStoreResult<()> {
Ok(())
}
}
/// A router that routes messages to the raftstore
#[derive(Clone)]
pub struct ServerRaftStoreRouter {
router: RaftRouter<RocksEngine>,
local_reader: LocalReader<RaftRouter<RocksEngine>, RocksEngine>,
}
impl ServerRaftStoreRouter {
/// Creates a new router.
pub fn new(
router: RaftRouter<RocksEngine>,
local_reader: LocalReader<RaftRouter<RocksEngine>, RocksEngine>,
) -> ServerRaftStoreRouter {
ServerRaftStoreRouter {
router,
local_reader,
}
}
pub fn send_store(&self, msg: StoreMsg) -> RaftStoreResult<()> {
self.router.send_control(msg).map_err(|e| {
RaftStoreError::Transport(match e {
TrySendError::Full(_) => DiscardReason::Full,
TrySendError::Disconnected(_) => DiscardReason::Disconnected,
})
})
}
}
#[inline]
pub fn handle_send_error<T>(region_id: u64, e: TrySendError<T>) -> RaftStoreError {
match e {
TrySendError::Full(_) => RaftStoreError::Transport(DiscardReason::Full),
TrySendError::Disconnected(_) => RaftStoreError::RegionNotFound(region_id),
}
}
impl RaftStoreRouter for ServerRaftStoreRouter {
fn send_raft_msg(&self, msg: RaftMessage) -> RaftStoreResult<()> {
let region_id = msg.get_region_id();
self.router
.send_raft_message(msg)
.map_err(|e| handle_send_error(region_id, e))
}
fn send_command_txn_extra(
&self,
req: RaftCmdRequest,
txn_extra: TxnExtra,
cb: Callback<RocksEngine>,
) -> RaftStoreResult<()> {
let cmd = RaftCommand::with_txn_extra(req, cb, txn_extra);
if LocalReader::<RaftRouter<RocksEngine>, RocksEngine>::acceptable(&cmd.request) {
self.local_reader.execute_raft_command(cmd);
Ok(())
} else {
let region_id = cmd.request.get_header().get_region_id();
self.router
.send_raft_command(cmd)
.map_err(|e| handle_send_error(region_id, e))
}
}
fn significant_send(&self, region_id: u64, msg: SignificantMsg) -> RaftStoreResult<()> {
if let Err(SendError(msg)) = self
.router
.force_send(region_id, PeerMsg::SignificantMsg(msg))
{
// TODO: panic here once we can detect system is shutting down reliably.
error!("failed to send significant msg"; "msg" => ?msg);
return Err(RaftStoreError::RegionNotFound(region_id));
}
Ok(())
}
fn casual_send(&self, region_id: u64, msg: CasualMessage<RocksEngine>) -> RaftStoreResult<()> {
self.router
.send(region_id, PeerMsg::CasualMessage(msg))
.map_err(|e| handle_send_error(region_id, e))
}
fn broadcast_unreachable(&self, store_id: u64) {
let _ = self
.router
.send_control(StoreMsg::StoreUnreachable { store_id });
}
}
| 32.047619 | 99 | 0.624732 |
01b6e7bd208a9e31be183f176da58b8d9369602e
| 29,719 |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[derive(std::fmt::Debug)]
pub(crate) struct Handle<C = aws_hyper::DynConnector> {
client: aws_hyper::Client<C>,
conf: crate::Config,
}
#[derive(Clone, std::fmt::Debug)]
pub struct Client<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<Handle<C>>,
}
impl<C> Client<C> {
pub fn from_conf_conn(conf: crate::Config, conn: C) -> Self {
let client = aws_hyper::Client::new(conn);
Self {
handle: std::sync::Arc::new(Handle { client, conf }),
}
}
pub fn conf(&self) -> &crate::Config {
&self.handle.conf
}
}
impl Client {
#[cfg(any(feature = "rustls", feature = "native-tls"))]
pub fn from_env() -> Self {
Self::from_conf(crate::Config::builder().build())
}
#[cfg(any(feature = "rustls", feature = "native-tls"))]
pub fn from_conf(conf: crate::Config) -> Self {
let client = aws_hyper::Client::https();
Self {
handle: std::sync::Arc::new(Handle { client, conf }),
}
}
}
impl<C> Client<C>
where
C: aws_hyper::SmithyConnector,
{
pub fn create_connection(&self) -> fluent_builders::CreateConnection<C> {
fluent_builders::CreateConnection::new(self.handle.clone())
}
pub fn create_host(&self) -> fluent_builders::CreateHost<C> {
fluent_builders::CreateHost::new(self.handle.clone())
}
pub fn delete_connection(&self) -> fluent_builders::DeleteConnection<C> {
fluent_builders::DeleteConnection::new(self.handle.clone())
}
pub fn delete_host(&self) -> fluent_builders::DeleteHost<C> {
fluent_builders::DeleteHost::new(self.handle.clone())
}
pub fn get_connection(&self) -> fluent_builders::GetConnection<C> {
fluent_builders::GetConnection::new(self.handle.clone())
}
pub fn get_host(&self) -> fluent_builders::GetHost<C> {
fluent_builders::GetHost::new(self.handle.clone())
}
pub fn list_connections(&self) -> fluent_builders::ListConnections<C> {
fluent_builders::ListConnections::new(self.handle.clone())
}
pub fn list_hosts(&self) -> fluent_builders::ListHosts<C> {
fluent_builders::ListHosts::new(self.handle.clone())
}
pub fn list_tags_for_resource(&self) -> fluent_builders::ListTagsForResource<C> {
fluent_builders::ListTagsForResource::new(self.handle.clone())
}
pub fn tag_resource(&self) -> fluent_builders::TagResource<C> {
fluent_builders::TagResource::new(self.handle.clone())
}
pub fn untag_resource(&self) -> fluent_builders::UntagResource<C> {
fluent_builders::UntagResource::new(self.handle.clone())
}
pub fn update_host(&self) -> fluent_builders::UpdateHost<C> {
fluent_builders::UpdateHost::new(self.handle.clone())
}
}
pub mod fluent_builders {
#[derive(std::fmt::Debug)]
pub struct CreateConnection<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::create_connection_input::Builder,
}
impl<C> CreateConnection<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::CreateConnectionOutput,
smithy_http::result::SdkError<crate::error::CreateConnectionError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the external provider where your third-party code repository is
/// configured.</p>
pub fn provider_type(mut self, input: crate::model::ProviderType) -> Self {
self.inner = self.inner.provider_type(input);
self
}
pub fn set_provider_type(
mut self,
input: std::option::Option<crate::model::ProviderType>,
) -> Self {
self.inner = self.inner.set_provider_type(input);
self
}
/// <p>The name of the connection to be created. The name must be unique in the calling AWS
/// account.</p>
pub fn connection_name(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.connection_name(input);
self
}
pub fn set_connection_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_connection_name(input);
self
}
/// <p>The key-value pair to use when tagging the resource.</p>
pub fn tags(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags(inp);
self
}
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags(input);
self
}
/// <p>The Amazon Resource Name (ARN) of the host associated with the connection to be created.</p>
pub fn host_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.host_arn(input);
self
}
pub fn set_host_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_host_arn(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct CreateHost<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::create_host_input::Builder,
}
impl<C> CreateHost<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::CreateHostOutput,
smithy_http::result::SdkError<crate::error::CreateHostError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the host to be created. The name must be unique in the calling AWS
/// account.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.name(input);
self
}
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_name(input);
self
}
/// <p>The name of the installed provider to be associated with your connection. The host
/// resource represents the infrastructure where your provider type is installed. The valid
/// provider type is GitHub Enterprise Server.</p>
pub fn provider_type(mut self, input: crate::model::ProviderType) -> Self {
self.inner = self.inner.provider_type(input);
self
}
pub fn set_provider_type(
mut self,
input: std::option::Option<crate::model::ProviderType>,
) -> Self {
self.inner = self.inner.set_provider_type(input);
self
}
/// <p>The endpoint of the infrastructure to be represented by the host after it is
/// created.</p>
pub fn provider_endpoint(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.provider_endpoint(input);
self
}
pub fn set_provider_endpoint(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_provider_endpoint(input);
self
}
/// <p>The VPC configuration to be provisioned for the host. A VPC must be configured and the
/// infrastructure to be represented by the host must already be connected to the VPC.</p>
pub fn vpc_configuration(mut self, input: crate::model::VpcConfiguration) -> Self {
self.inner = self.inner.vpc_configuration(input);
self
}
pub fn set_vpc_configuration(
mut self,
input: std::option::Option<crate::model::VpcConfiguration>,
) -> Self {
self.inner = self.inner.set_vpc_configuration(input);
self
}
pub fn tags(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags(inp);
self
}
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteConnection<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::delete_connection_input::Builder,
}
impl<C> DeleteConnection<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::DeleteConnectionOutput,
smithy_http::result::SdkError<crate::error::DeleteConnectionError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the connection to be deleted.</p>
/// <note>
/// <p>The ARN is never reused if the connection is deleted.</p>
/// </note>
pub fn connection_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.connection_arn(input);
self
}
pub fn set_connection_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_connection_arn(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteHost<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::delete_host_input::Builder,
}
impl<C> DeleteHost<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::DeleteHostOutput,
smithy_http::result::SdkError<crate::error::DeleteHostError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the host to be deleted.</p>
pub fn host_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.host_arn(input);
self
}
pub fn set_host_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_host_arn(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetConnection<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::get_connection_input::Builder,
}
impl<C> GetConnection<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::GetConnectionOutput,
smithy_http::result::SdkError<crate::error::GetConnectionError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of a connection.</p>
pub fn connection_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.connection_arn(input);
self
}
pub fn set_connection_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_connection_arn(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetHost<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::get_host_input::Builder,
}
impl<C> GetHost<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::GetHostOutput,
smithy_http::result::SdkError<crate::error::GetHostError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the requested host.</p>
pub fn host_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.host_arn(input);
self
}
pub fn set_host_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_host_arn(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListConnections<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::list_connections_input::Builder,
}
impl<C> ListConnections<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListConnectionsOutput,
smithy_http::result::SdkError<crate::error::ListConnectionsError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>Filters the list of connections to those associated with a specified provider, such as
/// Bitbucket.</p>
pub fn provider_type_filter(mut self, input: crate::model::ProviderType) -> Self {
self.inner = self.inner.provider_type_filter(input);
self
}
pub fn set_provider_type_filter(
mut self,
input: std::option::Option<crate::model::ProviderType>,
) -> Self {
self.inner = self.inner.set_provider_type_filter(input);
self
}
/// <p>Filters the list of connections to those associated with a specified host.</p>
pub fn host_arn_filter(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.host_arn_filter(input);
self
}
pub fn set_host_arn_filter(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_host_arn_filter(input);
self
}
/// <p>The maximum number of results to return in a single call. To retrieve the remaining
/// results, make another call with the returned <code>nextToken</code> value.</p>
pub fn max_results(mut self, input: i32) -> Self {
self.inner = self.inner.max_results(input);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_results(input);
self
}
/// <p>The token that was returned from the previous <code>ListConnections</code> call, which
/// can be used to return the next set of connections in the list.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(input);
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListHosts<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::list_hosts_input::Builder,
}
impl<C> ListHosts<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListHostsOutput,
smithy_http::result::SdkError<crate::error::ListHostsError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The maximum number of results to return in a single call. To retrieve the remaining
/// results, make another call with the returned <code>nextToken</code> value.</p>
pub fn max_results(mut self, input: i32) -> Self {
self.inner = self.inner.max_results(input);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_results(input);
self
}
/// <p>The token that was returned from the previous <code>ListHosts</code> call, which can be
/// used to return the next set of hosts in the list.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(input);
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListTagsForResource<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::list_tags_for_resource_input::Builder,
}
impl<C> ListTagsForResource<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListTagsForResourceOutput,
smithy_http::result::SdkError<crate::error::ListTagsForResourceError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the resource for which you want to get information about tags, if any.</p>
pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource_arn(input);
self
}
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_resource_arn(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct TagResource<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::tag_resource_input::Builder,
}
impl<C> TagResource<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::TagResourceOutput,
smithy_http::result::SdkError<crate::error::TagResourceError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the resource to which you want to add or update tags.</p>
pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource_arn(input);
self
}
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_resource_arn(input);
self
}
/// <p>The tags you want to modify or add to the resource.</p>
pub fn tags(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags(inp);
self
}
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UntagResource<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::untag_resource_input::Builder,
}
impl<C> UntagResource<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::UntagResourceOutput,
smithy_http::result::SdkError<crate::error::UntagResourceError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the resource to remove tags from.</p>
pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource_arn(input);
self
}
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_resource_arn(input);
self
}
/// <p>The list of keys for the tags to be removed from the resource.</p>
pub fn tag_keys(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.tag_keys(inp);
self
}
pub fn set_tag_keys(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_tag_keys(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UpdateHost<C = aws_hyper::DynConnector> {
handle: std::sync::Arc<super::Handle<C>>,
inner: crate::input::update_host_input::Builder,
}
impl<C> UpdateHost<C> {
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::UpdateHostOutput,
smithy_http::result::SdkError<crate::error::UpdateHostError>,
>
where
C: aws_hyper::SmithyConnector,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the host to be updated.</p>
pub fn host_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.host_arn(input);
self
}
pub fn set_host_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_host_arn(input);
self
}
/// <p>The URL or endpoint of the host to be updated.</p>
pub fn provider_endpoint(mut self, input: impl Into<std::string::String>) -> Self {
self.inner = self.inner.provider_endpoint(input);
self
}
pub fn set_provider_endpoint(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_provider_endpoint(input);
self
}
/// <p>The VPC configuration of the host to be updated. A VPC must be configured and the
/// infrastructure to be represented by the host must already be connected to the VPC.</p>
pub fn vpc_configuration(mut self, input: crate::model::VpcConfiguration) -> Self {
self.inner = self.inner.vpc_configuration(input);
self
}
pub fn set_vpc_configuration(
mut self,
input: std::option::Option<crate::model::VpcConfiguration>,
) -> Self {
self.inner = self.inner.set_vpc_configuration(input);
self
}
}
}
| 38.696615 | 123 | 0.550052 |
48e609542793b2de9f086f53d74aae96b7e8a2c0
| 2,683 |
use crate::utils::{match_type, paths, span_lint_and_sugg, walk_ptrs_ty};
use if_chain::if_chain;
use rustc_ast::ast::LitKind;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use std::path::{Component, Path};
declare_clippy_lint! {
/// **What it does:*** Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)
/// calls on `PathBuf` that can cause overwrites.
///
/// **Why is this bad?** Calling `push` with a root path at the start can overwrite the
/// previous defined path.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// use std::path::PathBuf;
///
/// let mut x = PathBuf::from("/foo");
/// x.push("/bar");
/// assert_eq!(x, PathBuf::from("/bar"));
/// ```
/// Could be written:
///
/// ```rust
/// use std::path::PathBuf;
///
/// let mut x = PathBuf::from("/foo");
/// x.push("bar");
/// assert_eq!(x, PathBuf::from("/foo/bar"));
/// ```
pub PATH_BUF_PUSH_OVERWRITE,
nursery,
"calling `push` with file system root on `PathBuf` can overwrite it"
}
declare_lint_pass!(PathBufPushOverwrite => [PATH_BUF_PUSH_OVERWRITE]);
impl<'tcx> LateLintPass<'tcx> for PathBufPushOverwrite {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if_chain! {
if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind;
if path.ident.name == sym!(push);
if args.len() == 2;
if match_type(cx, walk_ptrs_ty(cx.tables().expr_ty(&args[0])), &paths::PATH_BUF);
if let Some(get_index_arg) = args.get(1);
if let ExprKind::Lit(ref lit) = get_index_arg.kind;
if let LitKind::Str(ref path_lit, _) = lit.node;
if let pushed_path = Path::new(&*path_lit.as_str());
if let Some(pushed_path_lit) = pushed_path.to_str();
if pushed_path.has_root();
if let Some(root) = pushed_path.components().next();
if root == Component::RootDir;
then {
span_lint_and_sugg(
cx,
PATH_BUF_PUSH_OVERWRITE,
lit.span,
"Calling `push` with '/' or '\\' (file system root) will overwrite the previous path definition",
"try",
format!("\"{}\"", pushed_path_lit.trim_start_matches(|c| c == '/' || c == '\\')),
Applicability::MachineApplicable,
);
}
}
}
}
| 37.263889 | 117 | 0.560194 |
7525957370619a47f65ec2ca95af718598aef604
| 389 |
use failure::Error;
use futures::Future;
use crate::error::Result;
use crate::model::order_book::{GetOrderBookL2Request, GetOrderBookL2Response};
use crate::BitMEX;
impl BitMEX {
pub fn get_order_book_l2(&self, req: GetOrderBookL2Request) -> Result<impl Future<Item = Vec<GetOrderBookL2Response>, Error = Error>> {
Ok(self.transport.get("/orderBook/L2", Some(req))?)
}
}
| 29.923077 | 139 | 0.722365 |
90d2e63a1fa3b95a0eebdb22782cdc9cf52897be
| 27,220 |
// 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.
//! Test tools for building Fuchsia packages.
use {
failure::{format_err, Error, ResultExt},
fidl::endpoints::ServerEnd,
fidl_fuchsia_io::{DirectoryProxy, FileMarker, FileObject, NodeInfo},
fuchsia_component::client::{launcher, AppBuilder},
fuchsia_merkle::{Hash, MerkleTree},
fuchsia_pkg::{MetaContents, MetaPackage},
fuchsia_zircon::{self as zx, prelude::*, Status},
futures::{join, prelude::*},
maplit::btreeset,
std::{
collections::{BTreeMap, BTreeSet, HashSet},
fs::{self, File},
io::{self, Write},
path::{Path, PathBuf},
},
tempfile::TempDir,
walkdir::WalkDir,
};
/// A package generated by a [`PackageBuilder`], suitable for assembling into a TUF repository.
#[derive(Debug)]
pub struct Package {
name: String,
meta_far_merkle: Hash,
artifacts: TempDir,
}
#[derive(Debug, PartialEq)]
enum PackageEntry {
Directory,
File(Vec<u8>),
}
impl PackageEntry {
fn is_dir(&self) -> bool {
match self {
PackageEntry::Directory => true,
_ => false,
}
}
}
pub struct BlobFile {
pub merkle: fuchsia_merkle::Hash,
pub file: File,
}
impl Package {
/// The merkle root of the package's meta.far.
pub fn meta_far_merkle_root(&self) -> &Hash {
&self.meta_far_merkle
}
/// The package's meta.far.
pub fn meta_far(&self) -> io::Result<File> {
File::open(self.artifacts.path().join("meta.far"))
}
/// The name of the package.
pub fn name(&self) -> &str {
self.name.as_str()
}
/// The directory containing the blobs contained in the package, including the meta.far.
pub fn artifacts(&self) -> &Path {
self.artifacts.path()
}
/// Builds and returns the package located at "/pkg" in the current namespace.
pub async fn identity() -> Result<Self, Error> {
Self::from_dir("/pkg").await
}
/// Builds and returns the package located at the given path in the current namespace.
pub async fn from_dir(root: impl AsRef<Path>) -> Result<Self, Error> {
let root = root.as_ref();
let meta_package = MetaPackage::deserialize(File::open(root.join("meta/package"))?)?;
let mut pkg = PackageBuilder::new(meta_package.name());
fn is_generated_file(path: &Path) -> bool {
match path.to_str() {
Some("meta/contents") => true,
Some("meta/package") => true,
_ => false,
}
}
// Add all non-generated files from this package into `pkg`.
for entry in WalkDir::new(root) {
let entry = entry?;
let path = entry.path();
if !entry.file_type().is_file() || is_generated_file(path) {
continue;
}
let relative_path = path.strip_prefix(root).unwrap();
let f = File::open(path)?;
pkg = pkg.add_resource_at(relative_path.to_str().unwrap(), f);
}
Ok(pkg.build().await?)
}
/// Returns the parsed contents of the meta/contents file.
pub fn meta_contents(&self) -> Result<MetaContents, Error> {
let mut raw_meta_far = self.meta_far()?;
let mut meta_far = fuchsia_archive::Reader::new(&mut raw_meta_far)?;
let raw_meta_contents = meta_far.read_file("meta/contents")?;
Ok(MetaContents::deserialize(raw_meta_contents.as_slice())?)
}
/// Returns a set of all unique blobs contained in this package.
pub fn list_blobs(&self) -> Result<BTreeSet<Hash>, Error> {
let meta_contents = self.meta_contents()?;
let mut res = btreeset![self.meta_far_merkle.clone()];
res.extend(meta_contents.contents().iter().map(|(_, merkle)| merkle));
Ok(res)
}
/// Returns an iterator of merkle/File pairs for each content blob in the package.
///
/// Does not include the meta.far, see `meta_far()` and `meta_far_merkle_root()`, instead.
pub fn content_blob_files(&self) -> impl Iterator<Item = BlobFile> {
let bytes = fs::read(self.artifacts().join("manifest.json")).expect("read manifest blob");
let manifest: fuchsia_pkg::PackageManifest = serde_json::from_slice(&bytes).unwrap();
struct Blob {
merkle: fuchsia_merkle::Hash,
path: PathBuf,
}
let blobs = manifest
.into_blobs()
.into_iter()
.filter(|blob| blob.path != "meta/")
.map(|blob| Blob {
merkle: blob.merkle,
path: self.artifacts().join(
// fixup source_path to be relative to artifacts by stripping
// "/packages/{name}/" off the front.
&blob.source_path[("/packages/".len() + self.name().len() + "/".len())..],
),
})
.collect::<Vec<_>>();
blobs
.into_iter()
.map(|blob| BlobFile { merkle: blob.merkle, file: File::open(blob.path).unwrap() })
}
/// Puts all the blobs for the package in blobfs.
pub fn write_to_blobfs_dir(&self, dir: &openat::Dir) {
use std::convert::TryInto;
fn write_blob(
dir: &openat::Dir,
merkle: &fuchsia_merkle::Hash,
mut source: impl std::io::Read,
) -> Result<(), failure::Error> {
let mut bytes = vec![];
source.read_to_end(&mut bytes)?;
let mut file = dir.write_file(merkle.to_string(), 0777)?;
file.set_len(bytes.len().try_into().unwrap())?;
file.write_all(&bytes)?;
Ok(())
}
write_blob(dir, &self.meta_far_merkle_root(), self.meta_far().unwrap()).unwrap();
for blob in self.content_blob_files() {
write_blob(dir, &blob.merkle, blob.file).unwrap();
}
}
/// Verifies that the given directory serves the contents of this package.
pub async fn verify_contents(&self, dir: &DirectoryProxy) -> Result<(), VerificationError> {
let mut raw_meta_far = self.meta_far()?;
let mut meta_far = fuchsia_archive::Reader::new(&mut raw_meta_far)?;
let mut expected_paths = HashSet::new();
// Verify all entries referenced by meta/contents exist and have the correct merkle root.
let raw_meta_contents = meta_far.read_file("meta/contents")?;
let meta_contents = MetaContents::deserialize(raw_meta_contents.as_slice())?;
for (path, merkle) in meta_contents.contents() {
let actual_merkle =
MerkleTree::from_reader(read_file(dir, path).await?.as_slice())?.root();
if merkle != &actual_merkle {
return Err(VerificationError::DifferentFileData { path: path.to_owned() });
}
expected_paths.insert(path.clone());
}
// Verify all entries in the meta FAR exist and have the correct contents.
for path in meta_far.list().map(|s| s.to_owned()).collect::<Vec<_>>() {
if read_file(dir, path.as_str()).await? != meta_far.read_file(path.as_str())? {
return Err(VerificationError::DifferentFileData { path });
}
expected_paths.insert(path);
}
// Verify no other entries exist in the served directory.
for path in files_async::readdir_recursive(dir).await?.into_iter().map(|entry| entry.name) {
if !expected_paths.contains(path.as_str()) {
return Err(VerificationError::ExtraFile { path });
}
}
Ok(())
}
}
async fn read_file(dir: &DirectoryProxy, path: &str) -> Result<Vec<u8>, VerificationError> {
let (file, server_end) = fidl::endpoints::create_proxy::<FileMarker>().unwrap();
let flags = fidl_fuchsia_io::OPEN_FLAG_DESCRIBE | fidl_fuchsia_io::OPEN_RIGHT_READABLE;
dir.open(flags, 0, path, ServerEnd::new(server_end.into_channel()))
.expect("open request to send");
let mut events = file.take_event_stream();
let open = async move {
let fidl_fuchsia_io::FileEvent::OnOpen_ { s, info } =
events.next().await.expect("Some(event)").expect("no fidl error");
match Status::ok(s) {
Err(Status::NOT_FOUND) => Err(VerificationError::MissingFile { path: path.to_owned() }),
Err(status) => Err(format_err!("unable to open {:?}: {:?}", path, status).into()),
Ok(()) => Ok(()),
}?;
let event = match *info.expect("FileEvent to have NodeInfo") {
NodeInfo::File(FileObject { event }) => event,
other => {
panic!("NodeInfo from FileEventStream to be File variant with event: {:?}", other)
}
};
// Files served by the package will either provide an event in its describe info (if that
// file is actually a blob from blobfs) or not provide an event (if that file is, for
// example, a file contained within the meta far being served in the meta/ directory).
//
// If the file is a blobfs blob, we want to make sure it is readable. We can just try to
// read from it, but the preferred method to wait for a blobfs blob to become readable is
// to wait on the USER_0 signal to become asserted on the file's event.
//
// As all blobs served by a package should already be readable, we assert that USER_0 is
// already asserted on the event.
if let Some(event) = event {
match event.wait_handle(zx::Signals::USER_0, zx::Time::after(0.seconds())) {
Err(Status::TIMED_OUT) => Err(VerificationError::from(format_err!(
"file served by blobfs is not complete/readable as USER_0 signal was not set on the File's event: {}",
path
))),
Err(other_status) => Err(VerificationError::from(format_err!(
"wait_handle failed with status: {:?} {:?}",
other_status,
path
))),
Ok(_) => Ok(()),
}
} else {
Ok(())
}
};
let mut buf = vec![];
let read = async {
loop {
let (status, chunk) =
file.read(fidl_fuchsia_io::MAX_BUF).await.context("file read to respond")?;
Status::ok(status)
.map_err(|status| VerificationError::FileReadError { path: path.into(), status })?;
if chunk.is_empty() {
return Ok(buf);
}
buf.extend(chunk);
}
};
let (open, read) = join!(open, read);
let close_result = file.close().await.context("file close to respond");
let result = open.and(read)?;
// Only check close_result if everything that came before it looks good.
Status::ok(close_result?)
.map_err(|status| format_err!("unable to close {:?}: {:?}", path, status))?;
Ok(result)
}
/// An error that can occur while verifying the contents of a directory.
#[derive(Debug)]
pub enum VerificationError {
/// The directory is serving a file that isn't in the package.
ExtraFile {
/// Path to the extra file.
path: String,
},
/// The directory is not serving a particular file that it should be serving.
MissingFile {
/// Path to the missing file.
path: String,
},
/// The actual merkle of the file does not match the merkle listed in the meta FAR.
DifferentFileData {
/// Path to the file.
path: String,
},
/// Read method on file failed.
FileReadError {
/// Path to the file
path: String,
/// Read result
status: Status,
},
/// Anything else.
Other(Error),
}
impl<T: Into<Error>> From<T> for VerificationError {
fn from(x: T) -> Self {
VerificationError::Other(x.into())
}
}
/// A builder to simplify construction of Fuchsia packages.
pub struct PackageBuilder {
name: String,
contents: BTreeMap<PathBuf, PackageEntry>,
}
impl PackageBuilder {
/// Creates a new `PackageBuilder`.
pub fn new(name: impl Into<String>) -> Self {
Self { name: name.into(), contents: BTreeMap::new() }
}
/// Create a subdirectory within the package.
///
/// # Panics
///
/// Panics if the package contains a file entry at `path` or any of its ancestors.
pub fn dir(mut self, path: impl Into<PathBuf>) -> PackageDir {
let path = path.into();
self.make_dirs(&path);
PackageDir::new(self, path)
}
/// Adds the provided `contents` to the package at the given `path`.
///
/// # Panics
///
/// Panics if either:
/// * The package already contains a file or directory at `path`.
/// * The package contains a file at any of `path`'s ancestors.
pub fn add_resource_at(
mut self,
path: impl Into<PathBuf>,
mut contents: impl io::Read,
) -> Self {
let path = path.into();
let mut data = vec![];
contents.read_to_end(&mut data).unwrap();
if let Some(parent) = path.parent() {
self.make_dirs(parent);
}
let replaced = self.contents.insert(path.clone(), PackageEntry::File(data));
assert_eq!(None, replaced, "already contains an entry at {:?}", path);
self
}
fn make_dirs(&mut self, path: &Path) {
for ancestor in path.ancestors() {
if ancestor == Path::new("") {
continue;
}
assert!(
self.contents
.entry(ancestor.to_owned())
.or_insert(PackageEntry::Directory)
.is_dir(),
"{:?} is not a directory",
ancestor
);
}
}
/// Builds the package.
pub async fn build(self) -> Result<Package, Error> {
// TODO Consider switching indir/packagedir to be a VFS instead
// indir contains temporary inputs to package creation
let indir = tempfile::tempdir().context("create /in")?;
// packagedir contains outputs from package creation (manifest.json/meta.far) as well as
// all blobs contained in the package. Pm will build the package manifest with absolute
// source paths to /packages/{self.name}/contents/*.
//
// Sample layout of packagedir:
// - {name}/
// - manifest.json
// - meta.far
// - contents/
// - file{N}
let packagedir = tempfile::tempdir().context("create /packages")?;
fs::create_dir(packagedir.path().join("contents")).context("create /packages/contents")?;
let package_mount_path = format!("/packages/{}", &self.name);
{
let mut manifest = File::create(indir.path().join("package.manifest"))?;
MetaPackage::from_name_and_variant(self.name.clone(), "0")?
.serialize(File::create(indir.path().join("meta_package"))?)?;
writeln!(manifest, "meta/package=/in/meta_package")?;
for (i, (name, contents)) in self.contents.iter().enumerate() {
let contents = match contents {
PackageEntry::File(data) => data,
_ => continue,
};
let path = format!("file{}", i);
fs::write(packagedir.path().join("contents").join(&path), contents)?;
writeln!(
manifest,
"{}={}/contents/{}",
&name.to_string_lossy(),
package_mount_path,
path
)?;
}
}
let fut = AppBuilder::new("fuchsia-pkg://fuchsia.com/pm#meta/pm.cmx")
.arg(format!("-n={}", self.name))
.arg("-version=0")
.arg("-m=/in/package.manifest")
.arg(format!("-o={}", package_mount_path))
.arg("build")
.arg("-depfile=false")
.arg(format!("-output-package-manifest={}/manifest.json", &package_mount_path))
.add_dir_to_namespace("/in".to_owned(), File::open(indir.path()).context("open /in")?)?
.add_dir_to_namespace(
package_mount_path.clone(),
File::open(packagedir.path()).context("open /packages")?,
)?
.output(&launcher()?)?;
fut.await?.ok()?;
let meta_far_merkle =
fs::read_to_string(packagedir.path().join("meta.far.merkle"))?.parse()?;
// clean up after pm
fs::remove_file(packagedir.path().join("meta/contents"))?;
fs::remove_dir(packagedir.path().join("meta"))?;
fs::remove_file(packagedir.path().join("meta.far.merkle"))?;
Ok(Package { name: self.name, meta_far_merkle, artifacts: packagedir })
}
}
/// A subdirectory of a package being built.
pub struct PackageDir {
pkg: PackageBuilder,
path: PathBuf,
}
impl PackageDir {
fn new(pkg: PackageBuilder, path: impl Into<PathBuf>) -> Self {
Self { pkg, path: path.into() }
}
/// Adds the provided `contents` to the package at the given `path`, relative to this
/// `PackageDir`.
///
/// # Panics
/// If the package already contains a resource at `path`, relative to this `PackageDir`.
pub fn add_resource_at(mut self, path: impl AsRef<Path>, contents: impl io::Read) -> Self {
self.pkg = self.pkg.add_resource_at(self.path.join(path.as_ref()), contents);
self
}
/// Finish adding resources to this directory, returning the modified [`PackageBuilder`].
pub fn finish(self) -> PackageBuilder {
self.pkg
}
}
#[cfg(test)]
mod tests {
use {super::*, fuchsia_merkle::MerkleTree, matches::assert_matches, std::io::Read};
#[test]
#[should_panic(expected = r#""data" is not a directory"#)]
fn test_panics_file_with_existing_parent_as_file() {
let _ = (|| -> Result<(), Error> {
PackageBuilder::new("test")
.add_resource_at("data", "data contents".as_bytes())
.add_resource_at("data/foo", "data/foo contents".as_bytes());
Ok(())
})();
}
#[test]
#[should_panic(expected = r#""data" is not a directory"#)]
fn test_panics_dir_with_existing_file() {
let _ = (|| -> Result<(), Error> {
PackageBuilder::new("test")
.add_resource_at("data", "data contents".as_bytes())
.dir("data");
Ok(())
})();
}
#[test]
#[should_panic(expected = r#""data" is not a directory"#)]
fn test_panics_nested_dir_with_existing_file() {
let _ = (|| -> Result<(), Error> {
PackageBuilder::new("test")
.add_resource_at("data", "data contents".as_bytes())
.dir("data/foo");
Ok(())
})();
}
#[test]
#[should_panic(expected = r#"already contains an entry at "data""#)]
fn test_panics_file_with_existing_dir() {
let _ = (|| -> Result<(), Error> {
PackageBuilder::new("test")
.dir("data")
.add_resource_at("foo", "data/foo contents".as_bytes())
.finish()
.add_resource_at("data", "data contents".as_bytes());
Ok(())
})();
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_basic() -> Result<(), Error> {
let pkg = PackageBuilder::new("rolldice")
.dir("bin")
.add_resource_at("rolldice", "asldkfjaslkdfjalskdjfalskdf".as_bytes())
.finish()
.build()
.await?;
assert_eq!(
pkg.meta_far_merkle,
"7b3591496961a5b8918525feb2e49e6d1439580fd805a2b4178fc7581c011a0d".parse()?
);
assert_eq!(pkg.meta_far_merkle, MerkleTree::from_reader(pkg.meta_far()?)?.root());
assert_eq!(
pkg.list_blobs()?,
btreeset![
"7b3591496961a5b8918525feb2e49e6d1439580fd805a2b4178fc7581c011a0d".parse()?,
"b5b34f6234631edc7ccaa25533e2050e5d597a7331c8974306b617a3682a3197".parse()?
]
);
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_content_blob_files() -> Result<(), Error> {
let pkg = PackageBuilder::new("rolldice")
.dir("bin")
.add_resource_at("rolldice", "asldkfjaslkdfjalskdjfalskdf".as_bytes())
.add_resource_at("rolldice2", "asldkfjaslkdfjalskdjfalskdf".as_bytes())
.finish()
.build()
.await?;
let mut iter = pkg.content_blob_files();
// 2 identical entries
for _ in 0..2 {
let BlobFile { merkle, mut file } = iter.next().unwrap();
assert_eq!(
merkle,
"b5b34f6234631edc7ccaa25533e2050e5d597a7331c8974306b617a3682a3197".parse().unwrap()
);
let mut contents = vec![];
file.read_to_end(&mut contents).unwrap();
assert_eq!(contents, b"asldkfjaslkdfjalskdjfalskdf")
}
assert_eq!(iter.next().map(|b| b.merkle), None);
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_dir_semantics() -> Result<(), Error> {
let with_dir = PackageBuilder::new("data-file")
.dir("data")
.add_resource_at("file", "contents".as_bytes())
.finish()
.build()
.await?;
let with_direct = PackageBuilder::new("data-file")
.add_resource_at("data/file", "contents".as_bytes())
.build()
.await?;
assert_eq!(with_dir.meta_far_merkle_root(), with_direct.meta_far_merkle_root());
Ok(())
}
/// Creates a clone of the contents of /pkg in a tempdir so that tests can manipulate its
/// contents.
fn make_this_package_dir() -> Result<tempfile::TempDir, Error> {
let dir = tempfile::tempdir()?;
let this_package_root = Path::new("/pkg");
for entry in WalkDir::new(this_package_root) {
let entry = entry?;
let path = entry.path();
let relative_path = path.strip_prefix(this_package_root).unwrap();
let rebased_path = dir.path().join(relative_path);
if entry.file_type().is_dir() {
fs::create_dir_all(rebased_path)?;
} else if entry.file_type().is_file() {
fs::copy(path, rebased_path)?;
}
}
Ok(dir)
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_from_dir() -> Result<(), Error> {
let root = {
let dir = tempfile::tempdir()?;
fs::create_dir(dir.path().join("meta"))?;
fs::create_dir(dir.path().join("data"))?;
MetaPackage::from_name_and_variant("asdf", "0")?
.serialize(File::create(dir.path().join("meta/package"))?)?;
fs::write(dir.path().join("data/hello"), "world")?;
dir
};
let from_dir = Package::from_dir(root.path()).await?;
let pkg = PackageBuilder::new("asdf")
.add_resource_at("data/hello", "world".as_bytes())
.build()
.await?;
assert_eq!(from_dir.meta_far_merkle, pkg.meta_far_merkle);
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_identity() -> Result<(), Error> {
let pkg = Package::identity().await?;
assert_eq!(pkg.meta_far_merkle, MerkleTree::from_reader(pkg.meta_far()?)?.root());
// Verify the generated package's merkle root is the same as this test package's merkle root.
assert_eq!(pkg.meta_far_merkle, fs::read_to_string("/pkg/meta")?.parse()?);
let this_pkg_dir =
io_util::open_directory_in_namespace("/pkg", io_util::OPEN_RIGHT_READABLE)?;
pkg.verify_contents(&this_pkg_dir).await.expect("contents to be equivalent");
let pkg_dir = make_this_package_dir()?;
let this_pkg_dir = io_util::open_directory_in_namespace(
pkg_dir.path().to_str().unwrap(),
io_util::OPEN_RIGHT_READABLE,
)?;
assert_matches!(pkg.verify_contents(&this_pkg_dir).await, Ok(()));
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_verify_contents_rejects_extra_blob() -> Result<(), Error> {
let pkg = Package::identity().await?;
let pkg_dir = make_this_package_dir()?;
fs::write(pkg_dir.path().join("unexpected"), "unexpected file".as_bytes())?;
let pkg_dir_proxy = io_util::open_directory_in_namespace(
pkg_dir.path().to_str().unwrap(),
io_util::OPEN_RIGHT_READABLE,
)?;
assert_matches!(
pkg.verify_contents(&pkg_dir_proxy).await,
Err(VerificationError::ExtraFile{ref path}) if path == "unexpected");
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_verify_contents_rejects_extra_meta_file() -> Result<(), Error> {
let pkg = Package::identity().await?;
let pkg_dir = make_this_package_dir()?;
fs::write(pkg_dir.path().join("meta/unexpected"), "unexpected file".as_bytes())?;
let pkg_dir_proxy = io_util::open_directory_in_namespace(
pkg_dir.path().to_str().unwrap(),
io_util::OPEN_RIGHT_READABLE,
)?;
assert_matches!(
pkg.verify_contents(&pkg_dir_proxy).await,
Err(VerificationError::ExtraFile{ref path}) if path == "meta/unexpected");
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_verify_contents_rejects_missing_blob() -> Result<(), Error> {
let pkg = Package::identity().await?;
let pkg_dir = make_this_package_dir()?;
fs::remove_file(pkg_dir.path().join("bin/pkgsvr"))?;
let pkg_dir_proxy = io_util::open_directory_in_namespace(
pkg_dir.path().to_str().unwrap(),
io_util::OPEN_RIGHT_READABLE,
)?;
assert_matches!(
pkg.verify_contents(&pkg_dir_proxy).await,
Err(VerificationError::MissingFile{ref path}) if path == "bin/pkgsvr");
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_verify_contents_rejects_different_contents() -> Result<(), Error> {
let pkg = Package::identity().await?;
let pkg_dir = make_this_package_dir()?;
fs::write(pkg_dir.path().join("bin/pkgsvr"), "broken".as_bytes())?;
let pkg_dir_proxy = io_util::open_directory_in_namespace(
pkg_dir.path().to_str().unwrap(),
io_util::OPEN_RIGHT_READABLE,
)?;
assert_matches!(
pkg.verify_contents(&pkg_dir_proxy).await,
Err(VerificationError::DifferentFileData{ref path}) if path == "bin/pkgsvr");
Ok(())
}
}
| 35.674967 | 122 | 0.573402 |
672b5faf9e37ea3e1bbe531877e1003b54e784e3
| 246 |
// SPDX-License-Identifier: Apache-2.0
/*
* File: src/math/sin.rs
*
* The sin function.
*
* Author: HTG-YT
* Copyright (c) 2021 The LibM Team of the HaruxOS Project
*/
#[no_mangle]
pub extern "C" fn sin(x: f64) -> f64 {
libm::sin(x)
}
| 17.571429 | 58 | 0.621951 |
ab383bd953dd3c61e7d16660d8d46cbc9c679514
| 4,193 |
use crate::read_string;
use regex::Regex;
use std::collections::HashSet;
pub fn part1() -> u32 {
let s = read_string("./data/day16.txt").unwrap();
let parts: Vec<&str> = s.split("\n\n").collect();
let bounds = merge_bound(parts[0]);
let mut res = 0;
for line in parts[2].trim().split('\n').skip(1) {
res += line
.split(',')
.map(|x| x.parse().unwrap())
.filter(|&x| !is_valid(&bounds, x))
.sum::<u32>()
}
res
}
fn merge_bound(part: &str) -> Vec<(u32, u32)> {
let mut pairs = vec![];
let re = Regex::new(r"(\d+)-(\d+)").unwrap();
for caps in re.captures_iter(part) {
pairs.push((
caps.get(1).unwrap().as_str().parse::<u32>().unwrap(),
caps.get(2).unwrap().as_str().parse::<u32>().unwrap(),
));
}
pairs.sort_unstable();
let mut bounds = vec![pairs[0]];
let mut count = 0;
for (lo, hi) in pairs.into_iter().skip(1) {
if lo > bounds[count].1 {
bounds.push((lo, hi));
count += 1;
} else if hi > bounds[count].1 {
bounds[count].1 = hi;
}
}
bounds
}
fn is_valid(bounds: &[(u32, u32)], v: u32) -> bool {
let mut lo = 0;
let mut hi = bounds.len() - 1;
while hi >= lo {
let mid = (lo + hi) >> 1;
if bounds[mid].0 <= v && bounds[mid].1 >= v {
return true;
} else if bounds[mid].0 > v {
if mid == 0 {
return false;
}
hi = mid - 1;
} else {
lo = mid + 1;
}
}
false
}
fn get_valid_rows(parts: &[&str]) -> Vec<Vec<u32>> {
let bounds = merge_bound(parts[0]);
let mut valid_rows = vec![];
for line in parts[2].trim().split('\n').skip(1) {
let row: Vec<u32> = line.split(',').map(|x| x.parse().unwrap()).collect();
if row.iter().all(|&x| is_valid(&bounds, x)) {
valid_rows.push(row);
}
}
valid_rows
}
pub fn part2() -> usize {
let s = read_string("./data/day16.txt").unwrap();
let parts: Vec<&str> = s.split("\n\n").collect();
let re = Regex::new(r"(\d+)-(\d+)").unwrap();
let mut bounds_lst = vec![];
for line in parts[0].trim().split('\n') {
let mut bounds = vec![];
for caps in re.captures_iter(line) {
bounds.push((
caps.get(1).unwrap().as_str().parse::<u32>().unwrap(),
caps.get(2).unwrap().as_str().parse::<u32>().unwrap(),
));
}
bounds_lst.push(bounds); // NOTE: bounds is already sorted
}
let mine = parts[1]
.trim()
.split('\n')
.nth(1)
.unwrap()
.split(',')
.map(|x| x.parse().unwrap())
.collect::<Vec<u32>>();
let mut valid_rows = get_valid_rows(&parts);
valid_rows.push(mine.clone());
let n = bounds_lst.len();
let mut poss = Vec::with_capacity(n);
for _ in 0..n {
poss.push((0..n).into_iter().collect::<HashSet<usize>>());
}
for row in valid_rows {
for i in 0..n {
for j in poss[i].clone() {
if !is_valid(&bounds_lst[i], row[j]) {
poss[i].remove(&j);
}
}
}
}
get_match_lst(&mut poss)
.into_iter()
.take(6) // fields starts with `departure` is 1-6
.map(|i| mine[i] as usize)
.product::<usize>()
}
fn get_match_lst(poss: &mut Vec<HashSet<usize>>) -> Vec<usize> {
let n = poss.len();
let mut used = vec![false; n];
let mut match_lst = vec![0; n];
let mut i = 0;
let mut count = 0;
loop {
if !used[i] && poss[i].len() == 1 {
used[i] = true;
match_lst[i] = *poss[i].iter().next().unwrap();
count += 1;
if count == n {
return match_lst;
}
for j in 0..n {
if !used[j] {
poss[j].remove(&match_lst[i]);
}
}
}
i += 1;
i %= n;
}
}
#[test]
fn test_16() {
assert_eq!(19060, part1());
assert_eq!(953713095011, part2());
}
| 26.707006 | 82 | 0.464584 |
d9afb16bd53a500312cee78fccc492faceb3314c
| 753 |
/**
* Copyright (c) 2019, Jesús Rubio <[email protected]>
*
* This source code is licensed under the MIT License found in
* the LICENSE.txt file in the root directory of this source tree.
*/
use leg::*;
fn main() {
head("leg", Some("🔈"), Some("1.0.0"));
info("Informational message", None, None);
success("Succesfull operation", None, None);
warn("Warn message", None, None);
error("Error message", None, None);
wait("Waiting for something", None, None);
done("Something finished", None, None);
print!("Not shown");
remove();
info("Informational message with scope", Some("myscope"), None);
info("Informational message without new line", None, Some(false));
println!(" => same line");
}
| 28.961538 | 70 | 0.642762 |
d7f37429f52628804f2f64970b98bd6aebcfdb17
| 12,786 |
// Copyright (c) Microsoft. All rights reserved.
use std::env;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{io, io::IoSlice};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
pub enum MaybeProxyStream<S> {
NoProxy(S),
Proxy(hyper_proxy::ProxyStream<S>),
}
impl<S> AsyncRead for MaybeProxyStream<S>
where
S: AsyncRead + AsyncWrite + Unpin,
{
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
match &mut *self {
MaybeProxyStream::NoProxy(s) => Pin::new(s).poll_read(cx, buf),
MaybeProxyStream::Proxy(s) => Pin::new(s).poll_read(cx, buf),
}
}
}
impl<S> AsyncWrite for MaybeProxyStream<S>
where
S: AsyncRead + AsyncWrite + Unpin,
{
fn poll_write(
mut self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
match &mut *self {
MaybeProxyStream::NoProxy(s) => Pin::new(s).poll_write(ctx, buf),
MaybeProxyStream::Proxy(s) => Pin::new(s).poll_write(ctx, buf),
}
}
fn poll_write_vectored(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<Result<usize, io::Error>> {
match &mut *self {
MaybeProxyStream::NoProxy(s) => Pin::new(s).poll_write_vectored(cx, bufs),
MaybeProxyStream::Proxy(s) => Pin::new(s).poll_write_vectored(cx, bufs),
}
}
fn is_write_vectored(&self) -> bool {
match self {
MaybeProxyStream::NoProxy(s) => s.is_write_vectored(),
MaybeProxyStream::Proxy(s) => s.is_write_vectored(),
}
}
fn poll_flush(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> {
match &mut *self {
MaybeProxyStream::NoProxy(s) => Pin::new(s).poll_flush(ctx),
MaybeProxyStream::Proxy(s) => Pin::new(s).poll_flush(ctx),
}
}
fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> {
match &mut *self {
MaybeProxyStream::NoProxy(s) => Pin::new(s).poll_shutdown(ctx),
MaybeProxyStream::Proxy(s) => Pin::new(s).poll_shutdown(ctx),
}
}
}
impl<S> hyper::client::connect::Connection for MaybeProxyStream<S>
where
S: hyper::client::connect::Connection,
hyper_proxy::ProxyStream<S>: hyper::client::connect::Connection,
{
fn connected(&self) -> hyper::client::connect::Connected {
match self {
MaybeProxyStream::NoProxy(stream) => stream.connected(),
MaybeProxyStream::Proxy(stream) => stream.connected(),
}
}
}
#[derive(Clone)]
pub enum MaybeProxyConnector<C> {
NoProxy(C),
Proxy(hyper_proxy::ProxyConnector<C>),
}
impl MaybeProxyConnector<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>> {
pub fn new(
proxy_uri: Option<hyper::Uri>,
identity: Option<(&openssl::pkey::PKeyRef<openssl::pkey::Private>, &[u8])>,
trusted_certs: &[openssl::x509::X509],
) -> io::Result<Self> {
let mut http_connector = hyper::client::HttpConnector::new();
http_connector.enforce_http(false);
let tls_connector = make_tls_connector(identity, trusted_certs)?;
let https_connector =
hyper_openssl::HttpsConnector::with_connector(http_connector, tls_connector)?;
if let Some(proxy_uri) = proxy_uri {
let proxy = uri_to_proxy(proxy_uri)?;
let mut proxy_connector =
hyper_proxy::ProxyConnector::from_proxy(https_connector, proxy)?;
// There are two TLS connectors involved with a proxy:
//
// - the connector used to connect to the proxy itself
// - the connector used to connect to the proxied destination
//
// We don't have separate configuration of TLS client identity and trusted certs for these two,
// so we apply the same config to both. Therefore, we create a new `openssl::ssl::SslConnectorBuilder`
// identical to the original `tls_connector` and use that with `proxy_connector.set_tls`
//
// `tls_connector` was already consumed by `hyper_openssl::HttpsConnector::with_connector`
// and doesn't impl `Clone`, so the new one has to be built from scratch via `make_tls_connector`
let proxy_tls_connector = make_tls_connector(identity, trusted_certs)?;
proxy_connector.set_tls(Some(proxy_tls_connector.build()));
Ok(MaybeProxyConnector::Proxy(proxy_connector))
} else {
Ok(MaybeProxyConnector::NoProxy(https_connector))
}
}
}
fn make_tls_connector(
identity: Option<(&openssl::pkey::PKeyRef<openssl::pkey::Private>, &[u8])>,
trusted_certs: &[openssl::x509::X509],
) -> io::Result<openssl::ssl::SslConnectorBuilder> {
let mut tls_connector = openssl::ssl::SslConnector::builder(openssl::ssl::SslMethod::tls())?;
let cert_store = tls_connector.cert_store_mut();
for trusted_cert in trusted_certs {
if let Err(err) = cert_store.add_cert(trusted_cert.clone()) {
// openssl 1.0 raises X509_R_CERT_ALREADY_IN_HASH_TABLE if a duplicate cert is added to a cert store. [1]
// 1.1 silently ignores the duplicate. [2]
//
// Trusted certs can come from the user, and it's benign to ignore such duplicate certs, so we want to ignore it too.
//
// native-tls's implementation ignores *all errors* [3]. But we would like to check and just ignore this particular one.
//
// [1]: https://github.com/openssl/openssl/blob/OpenSSL_1_0_2u/crypto/x509/x509_lu.c#L370-L375
// [2]: https://github.com/openssl/openssl/blob/OpenSSL_1_1_1k/crypto/x509/x509_lu.c#L354-L355
// [3]: https://github.com/sfackler/rust-native-tls/blob/41522daa6f6e76182c3118a7f9c23f6949e6d59f/src/imp/openssl.rs#L272-L274
let is_duplicate_cert_error = err.errors().iter().any(|err| {
// https://github.com/openssl/openssl/blob/OpenSSL_1_0_2u/crypto/err/err.h#L171
// https://github.com/openssl/openssl/blob/OpenSSL_1_1_1k/include/openssl/err.h#L64
const ERR_LIB_X509: std::os::raw::c_int = 11;
// https://github.com/openssl/openssl/blob/OpenSSL_1_0_2u/crypto/x509/x509.h#L1280
// https://github.com/openssl/openssl/blob/OpenSSL_1_1_1k/include/openssl/x509err.h#L73
const X509_F_X509_STORE_ADD_CERT: std::os::raw::c_int = 124;
// https://github.com/openssl/openssl/blob/OpenSSL_1_0_2u/crypto/x509/x509.h#L1296
// https://github.com/openssl/openssl/blob/OpenSSL_1_1_1k/include/openssl/x509err.h#L95
const X509_R_CERT_ALREADY_IN_HASH_TABLE: std::os::raw::c_int = 101;
let code = err.code();
let library = openssl_sys::ERR_GET_LIB(code);
let function = openssl_sys::ERR_GET_FUNC(code);
let reason = openssl_sys::ERR_GET_REASON(code);
library == ERR_LIB_X509
&& function == X509_F_X509_STORE_ADD_CERT
&& reason == X509_R_CERT_ALREADY_IN_HASH_TABLE
});
if !is_duplicate_cert_error {
return Err(err.into());
}
}
}
if let Some((key, certs)) = identity {
let mut device_id_certs = openssl::x509::X509::stack_from_pem(certs)?.into_iter();
let client_cert = device_id_certs.next().ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "device identity cert not found")
})?;
tls_connector.set_certificate(&client_cert)?;
for cert in device_id_certs {
tls_connector.add_extra_chain_cert(cert)?;
}
tls_connector.set_private_key(key)?;
}
Ok(tls_connector)
}
impl<C> hyper::service::Service<http::uri::Uri> for MaybeProxyConnector<C>
where
C: hyper::service::Service<http::uri::Uri> + Send + Unpin + Clone + 'static,
C::Response:
AsyncRead + AsyncWrite + hyper::client::connect::Connection + Send + Unpin + 'static,
C::Future: Send + 'static,
C::Error: Into<Box<dyn std::error::Error + Sync + Send>>,
{
type Response = MaybeProxyStream<C::Response>;
type Error = io::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self {
MaybeProxyConnector::NoProxy(c) => c
.poll_ready(cx)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
MaybeProxyConnector::Proxy(c) => c.poll_ready(cx),
}
}
fn call(&mut self, req: http::uri::Uri) -> Self::Future {
match self {
MaybeProxyConnector::NoProxy(c) => {
let stream = c.call(req);
Box::pin(async {
let stream = stream
.await
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(MaybeProxyStream::NoProxy(stream))
})
}
MaybeProxyConnector::Proxy(c) => {
let stream = c.call(req);
Box::pin(async {
let stream = stream.await?;
Ok(MaybeProxyStream::Proxy(stream))
})
}
}
}
}
fn uri_to_proxy(uri: hyper::Uri) -> io::Result<hyper_proxy::Proxy> {
let proxy_url =
url::Url::parse(&uri.to_string()).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
let mut proxy = hyper_proxy::Proxy::new(hyper_proxy::Intercept::All, uri);
if !proxy_url.username().is_empty() {
let username = percent_encoding::percent_decode_str(proxy_url.username())
.decode_utf8()
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
let credentials = match proxy_url.password() {
Some(password) => {
let password = percent_encoding::percent_decode_str(password)
.decode_utf8()
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
headers::Authorization::basic(&username, &password)
}
None => headers::Authorization::basic(&username, ""),
};
proxy.set_authorization(credentials);
}
Ok(proxy)
}
pub fn get_proxy_uri(https_proxy: Option<String>) -> io::Result<Option<hyper::Uri>> {
let proxy_uri = https_proxy
.or_else(|| env::var("HTTPS_PROXY").ok())
.or_else(|| env::var("https_proxy").ok());
let proxy_uri = match proxy_uri {
None => None,
Some(s) => {
let proxy = s
.parse::<hyper::Uri>()
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;
// Mask the password in the proxy URI before logging it
let mut sanitized_proxy = url::Url::parse(&proxy.to_string())
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;
if sanitized_proxy.password().is_some() {
sanitized_proxy.set_password(Some("******")).map_err(|()| {
io::Error::new(io::ErrorKind::Other, "set proxy password failed")
})?;
}
log::info!("Detected HTTPS proxy server {}", sanitized_proxy);
Some(proxy)
}
};
Ok(proxy_uri)
}
#[cfg(test)]
mod tests {
use super::get_proxy_uri;
#[test]
fn get_proxy_uri_recognizes_https_proxy() {
let proxy_val = "https://example.com"
.to_string()
.parse::<hyper::Uri>()
.unwrap()
.to_string();
assert_eq!(
get_proxy_uri(Some(proxy_val.clone()))
.unwrap()
.unwrap()
.to_string(),
proxy_val
);
}
#[test]
fn get_proxy_uri_allows_credentials_in_authority() {
let proxy_val = "https://username:[email protected]/".to_string();
assert_eq!(
get_proxy_uri(Some(proxy_val.clone()))
.unwrap()
.unwrap()
.to_string(),
proxy_val
);
let proxy_val = "https://username%2f:password%[email protected]/".to_string();
assert_eq!(
get_proxy_uri(Some(proxy_val.clone()))
.unwrap()
.unwrap()
.to_string(),
proxy_val
);
}
}
| 37.385965 | 138 | 0.578993 |
62a5c8182282d09addbb8e5211d935ca1a460b2a
| 5,190 |
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::BCLRFR {
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
}
#[doc = r" Proxy"]
pub struct _LFSDETW<'a> {
w: &'a mut W,
}
impl<'a> _LFSDETW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CAFSDETW<'a> {
w: &'a mut W,
}
impl<'a> _CAFSDETW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CNRDYW<'a> {
w: &'a mut W,
}
impl<'a> _CNRDYW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _WCKCFGW<'a> {
w: &'a mut W,
}
impl<'a> _WCKCFGW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _MUTEDETW<'a> {
w: &'a mut W,
}
impl<'a> _MUTEDETW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _OVRUDRW<'a> {
w: &'a mut W,
}
impl<'a> _OVRUDRW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 6 - Clear late frame synchronization detection flag"]
#[inline]
pub fn lfsdet(&mut self) -> _LFSDETW {
_LFSDETW { w: self }
}
#[doc = "Bit 5 - Clear anticipated frame synchronization detection flag"]
#[inline]
pub fn cafsdet(&mut self) -> _CAFSDETW {
_CAFSDETW { w: self }
}
#[doc = "Bit 4 - Clear codec not ready flag"]
#[inline]
pub fn cnrdy(&mut self) -> _CNRDYW {
_CNRDYW { w: self }
}
#[doc = "Bit 2 - Clear wrong clock configuration flag"]
#[inline]
pub fn wckcfg(&mut self) -> _WCKCFGW {
_WCKCFGW { w: self }
}
#[doc = "Bit 1 - Mute detection flag"]
#[inline]
pub fn mutedet(&mut self) -> _MUTEDETW {
_MUTEDETW { w: self }
}
#[doc = "Bit 0 - Clear overrun / underrun"]
#[inline]
pub fn ovrudr(&mut self) -> _OVRUDRW {
_OVRUDRW { w: self }
}
}
| 26.212121 | 77 | 0.506936 |
e213201ab091a5089cdacc15b64a030b1523e7e5
| 2,126 |
use tokio_threadpool::Sender;
use futures::future::{self, Future};
/// Executes futures on the runtime
///
/// All futures spawned using this executor will be submitted to the associated
/// Runtime's executor. This executor is usually a thread pool.
///
/// For more details, see the [module level](index.html) documentation.
#[derive(Debug, Clone)]
pub struct TaskExecutor {
pub(super) inner: Sender,
}
impl TaskExecutor {
/// Spawn a future onto the Tokio runtime.
///
/// This spawns the given future onto the runtime's executor, usually a
/// thread pool. The thread pool is then responsible for polling the future
/// until it completes.
///
/// See [module level][mod] documentation for more details.
///
/// [mod]: index.html
///
/// # Examples
///
/// ```rust
/// # extern crate tokio;
/// # extern crate futures;
/// # use futures::{future, Future, Stream};
/// use tokio::runtime::Runtime;
///
/// # fn dox() {
/// // Create the runtime
/// let mut rt = Runtime::new().unwrap();
/// let executor = rt.executor();
///
/// // Spawn a future onto the runtime
/// executor.spawn(future::lazy(|| {
/// println!("now running on a worker thread");
/// Ok(())
/// }));
/// # }
/// # pub fn main() {}
/// ```
///
/// # Panics
///
/// This function panics if the spawn fails. Failure occurs if the executor
/// is currently at capacity and is unable to spawn a new future.
pub fn spawn<F>(&self, future: F)
where F: Future<Item = (), Error = ()> + Send + 'static,
{
self.inner.spawn(future).unwrap();
}
}
impl<T> future::Executor<T> for TaskExecutor
where T: Future<Item = (), Error = ()> + Send + 'static,
{
fn execute(&self, future: T) -> Result<(), future::ExecuteError<T>> {
self.inner.execute(future)
}
}
impl ::executor::Executor for TaskExecutor {
fn spawn(&mut self, future: Box<Future<Item = (), Error = ()> + Send>)
-> Result<(), ::executor::SpawnError>
{
self.inner.spawn(future)
}
}
| 27.973684 | 79 | 0.579962 |
f8166b4bd16c63683580367026b9659d4111f2d1
| 61 |
pub mod error;
pub mod presigner;
pub mod rds;
pub mod util;
| 12.2 | 18 | 0.737705 |
1ad29627b45e19ca573674458166d5df92353b82
| 676 |
use std::io;
use ser::{Stream, Reader};
use {Payload, MessageResult};
#[derive(Debug, PartialEq)]
pub struct SendCompact {
pub first: bool,
pub second: u64,
}
impl Payload for SendCompact {
fn version() -> u32 {
70014
}
fn command() -> &'static str {
"sendcmpct"
}
fn deserialize_payload<T>(reader: &mut Reader<T>, _version: u32) -> MessageResult<Self> where T: io::Read {
let send_compact = SendCompact {
first: try!(reader.read()),
second: try!(reader.read()),
};
Ok(send_compact)
}
fn serialize_payload(&self, stream: &mut Stream, _version: u32) -> MessageResult<()> {
stream
.append(&self.first)
.append(&self.second);
Ok(())
}
}
| 18.777778 | 108 | 0.647929 |
6479618abfc2f727c14d02f198273440a2cea6f5
| 21,123 |
use pdf::file::File;
use pdf::primitive::Primitive;
pub use crate::logging::ResultExt;
enum TransactionType {
Dividends,
Sold,
Trade,
}
enum ParserState {
SearchingTransactionEntry,
ProcessingTransaction(TransactionType),
}
pub trait Entry {
fn parse(&mut self, pstr: &pdf::primitive::PdfString);
fn getf32(&self) -> Option<f32> {
None
}
fn geti32(&self) -> Option<i32> {
None
}
fn getdate(&self) -> Option<String> {
None
}
fn getstring(&self) -> Option<String> {
None
}
fn is_pattern(&self) -> bool {
false
}
}
struct F32Entry {
pub val: f32,
}
impl Entry for F32Entry {
fn parse(&mut self, pstr: &pdf::primitive::PdfString) {
let mystr = pstr
.clone()
.into_string()
.expect(&format!("Error parsing : {:#?} to f32", pstr));
self.val = mystr
.parse::<f32>()
.expect(&format!("Error parsing : {} to f32", mystr));
}
fn getf32(&self) -> Option<f32> {
Some(self.val)
}
}
struct I32Entry {
pub val: i32,
}
impl Entry for I32Entry {
fn parse(&mut self, pstr: &pdf::primitive::PdfString) {
let mystr = pstr
.clone()
.into_string()
.expect(&format!("Error parsing : {:#?} to f32", pstr));
self.val = mystr
.parse::<i32>()
.expect(&format!("Error parsing : {} to f32", mystr));
}
fn geti32(&self) -> Option<i32> {
Some(self.val)
}
}
struct DateEntry {
pub val: String,
}
impl Entry for DateEntry {
fn parse(&mut self, pstr: &pdf::primitive::PdfString) {
let mystr = pstr
.clone()
.into_string()
.expect(&format!("Error parsing : {:#?} to f32", pstr));
if chrono::NaiveDate::parse_from_str(&mystr, "%m/%d/%y").is_ok() {
self.val = mystr;
}
}
fn getdate(&self) -> Option<String> {
Some(self.val.clone())
}
}
struct StringEntry {
pub val: String,
pub pattern: String,
}
impl Entry for StringEntry {
fn parse(&mut self, pstr: &pdf::primitive::PdfString) {
self.val = pstr
.clone()
.into_string()
.expect(&format!("Error parsing : {:#?} to f32", pstr));
}
fn getstring(&self) -> Option<String> {
Some(self.val.clone())
}
fn is_pattern(&self) -> bool {
self.pattern == self.val
}
}
fn create_dividend_parsing_sequence(sequence: &mut std::collections::VecDeque<Box<dyn Entry>>) {
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "INTC".to_owned(),
})); // INTC
sequence.push_back(Box::new(F32Entry { val: 0.0 })); // Tax Entry
sequence.push_back(Box::new(F32Entry { val: 0.0 })); // Income Entry
}
fn create_sold_parsing_sequence(sequence: &mut std::collections::VecDeque<Box<dyn Entry>>) {
sequence.push_back(Box::new(I32Entry { val: 0 })); // Quantity
sequence.push_back(Box::new(F32Entry { val: 0.0 })); // Price
sequence.push_back(Box::new(F32Entry { val: 0.0 })); // Amount Sold
}
fn create_trade_parsing_sequence(sequence: &mut std::collections::VecDeque<Box<dyn Entry>>) {
sequence.push_back(Box::new(DateEntry { val: String::new() })); // Trade date
sequence.push_back(Box::new(DateEntry { val: String::new() })); // Settlement date
sequence.push_back(Box::new(I32Entry { val: 0 })); // MKT /
sequence.push_back(Box::new(I32Entry { val: 0 })); // / CPT
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "INTC".to_owned(),
}));
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "SELL".to_owned(),
}));
sequence.push_back(Box::new(I32Entry { val: 0 })); // Quantity
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "$".to_owned(),
})); // $...
sequence.push_back(Box::new(F32Entry { val: 0.0 })); // ..<price>
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "Stock".to_owned(),
}));
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "Plan".to_owned(),
}));
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "PRINCIPAL".to_owned(),
}));
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "$".to_owned(),
})); // $...
sequence.push_back(Box::new(F32Entry { val: 0.0 })); // ..<principal>
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "INTEL".to_owned(),
}));
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "CORP".to_owned(),
}));
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "COMMISSION".to_owned(),
}));
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "$".to_owned(),
})); // $...
sequence.push_back(Box::new(F32Entry { val: 0.0 })); // ..<commission>
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "FEE".to_owned(),
}));
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "$".to_owned(),
})); // $...
sequence.push_back(Box::new(F32Entry { val: 0.0 })); // ..<fee>
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "NET".to_owned(),
}));
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "AMOUNT".to_owned(),
}));
sequence.push_back(Box::new(StringEntry {
val: String::new(),
pattern: "$".to_owned(),
})); // $...
sequence.push_back(Box::new(F32Entry { val: 0.0 })); // ..<net amount>
}
pub fn parse_brokerage_statement(
pdftoparse: &str,
) -> (
Vec<(String, f32, f32)>,
Vec<(String, String, i32, f32, f32)>,
Vec<(String, String, i32, f32, f32, f32, f32, f32)>,
) {
//2. parsing each pdf
let mypdffile = File::<Vec<u8>>::open(pdftoparse)
.expect_and_log(&format!("Error opening and parsing file: {}", pdftoparse));
let mut state = ParserState::SearchingTransactionEntry;
let mut sequence: std::collections::VecDeque<Box<dyn Entry>> =
std::collections::VecDeque::new();
let mut processed_sequence: Vec<Box<dyn Entry>> = vec![];
// Queue for transaction dates. Pop last one or last two as trade and settlement dates
let mut transaction_dates: Vec<String> = vec![];
let mut div_transactions: Vec<(String, f32, f32)> = vec![];
let mut sold_transactions: Vec<(String, String, i32, f32, f32)> = vec![];
let mut trades: Vec<(String, String, i32, f32, f32, f32, f32, f32)> = vec![];
log::info!("Parsing: {} of {} pages", pdftoparse, mypdffile.num_pages());
for page in mypdffile.pages() {
let page = page.unwrap();
let contents = page.contents.as_ref().unwrap();
for op in contents.operations.iter() {
match op.operator.as_ref() {
"TJ" => {
// Text show
if op.operands.len() > 0 {
//transaction_date = op.operands[0];
let a = &op.operands[0];
match a {
Primitive::Array(c) => {
for e in c {
if let Primitive::String(actual_string) = e {
match state {
ParserState::SearchingTransactionEntry => {
let rust_string =
actual_string.clone().into_string().unwrap();
//println!("rust_string: {}", rust_string);
if rust_string == "Dividend" {
create_dividend_parsing_sequence(&mut sequence);
state = ParserState::ProcessingTransaction(
TransactionType::Dividends,
);
} else if rust_string == "Sold" {
create_sold_parsing_sequence(&mut sequence);
state = ParserState::ProcessingTransaction(
TransactionType::Sold,
);
} else if rust_string == "TYPE" {
create_trade_parsing_sequence(&mut sequence);
state = ParserState::ProcessingTransaction(
TransactionType::Trade,
);
} else {
//if this is date then store it
if chrono::NaiveDate::parse_from_str(
&rust_string,
"%m/%d/%y",
)
.is_ok()
{
transaction_dates.push(rust_string.clone());
}
}
}
ParserState::ProcessingTransaction(
transaction_type,
) => {
// So process transaction element and store it in SOLD
// or DIV
let possible_obj = sequence.pop_front();
match possible_obj {
// Move executed parser objects into Vector
// attach only i32 and f32 elements to
// processed queue
Some(mut obj) => {
obj.parse(actual_string);
// attach to sequence the same string parser if pattern is not met
if obj.getstring().is_some() {
if obj.is_pattern() == false {
sequence.push_front(obj);
}
} else {
processed_sequence.push(obj);
}
// If sequence of expected entries is
// empty then extract data from
// processeed elements
if sequence.is_empty() {
state =
ParserState::SearchingTransactionEntry;
let mut transaction =
processed_sequence.iter();
match transaction_type {
TransactionType::Dividends => {
let tax_us = transaction.next().unwrap().getf32().expect_and_log("Processing of Dividend transaction went wrong");
let gross_us = transaction.next().unwrap().getf32().expect_and_log("Processing of Dividend transaction went wrong");
div_transactions.push((
transaction_dates.pop().expect("Error: missing transaction dates when parsing"),
gross_us,
tax_us,
));
}
TransactionType::Sold => {
let quantity = transaction.next().unwrap().geti32().expect_and_log("Processing of Sold transaction went wrong");
let price = transaction.next().unwrap().getf32().expect_and_log("Processing of Sold transaction went wrong");
let amount_sold = transaction.next().unwrap().getf32().expect_and_log("Prasing of Sold transaction went wrong");
// Last transaction date is settlement date
// next to last is trade date
let settlement_date = transaction_dates.pop().expect("Error: missing trade date when parsing");
let trade_date = transaction_dates.pop().expect("Error: missing settlement_date when parsing");
sold_transactions.push((
trade_date,
settlement_date,
quantity,
price,
amount_sold, // net income
));
}
TransactionType::Trade => {
let transaction_date = transaction.next().unwrap().getdate().expect("Prasing of Trade confirmation went wrong"); // quantity
let settlement_date = transaction.next().unwrap().getdate().expect("Prasing of Trade confirmation went wrong"); // quantity
transaction.next().unwrap(); // MKT??
transaction.next().unwrap(); // CPT??
let quantity = transaction.next().unwrap().geti32().expect("Prasing of Trade confirmation went wrong"); // quantity
let price = transaction.next().unwrap().getf32().expect("Prasing of Trade confirmation went wrong"); // price
let principal = transaction.next().unwrap().getf32().expect("Prasing of Trade confirmation went wrong"); // principal
let commission = transaction.next().unwrap().getf32().expect("Prasing of Trade confirmation went wrong"); // commission
let fee = transaction.next().unwrap().getf32().expect("Prasing of Trade confirmation went wrong"); // fee
let net = transaction.next().unwrap().getf32().expect("Prasing of Trade confirmation went wrong"); // net
trades.push((
transaction_date,
settlement_date,
quantity,
price,
principal,
commission,
fee,
net,
));
}
}
processed_sequence.clear();
} else {
state =
ParserState::ProcessingTransaction(
transaction_type,
);
}
}
// In nothing more to be done then just extract
// parsed data from paser objects
None => {
state = ParserState::ProcessingTransaction(
transaction_type,
);
}
}
}
}
}
}
}
_ => (),
}
}
}
_ => {}
}
}
}
(div_transactions, sold_transactions, trades)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_parse_brokerage_statement() -> Result<(), String> {
assert_eq!(
parse_brokerage_statement("data/example.pdf"),
(vec![("03/01/21".to_owned(), 574.42, 86.16)], vec![], vec![])
);
assert_eq!(
parse_brokerage_statement("data/example2.pdf"),
(vec![], vec![], vec![])
);
assert_eq!(
parse_brokerage_statement("data/example3.pdf"),
(
vec![
("06/01/21".to_owned(), 0.17, 0.03),
("06/01/21".to_owned(), 45.87, 6.88)
],
vec![],
vec![]
)
);
assert_eq!(
parse_brokerage_statement("data/example4.pdf"),
(
vec![],
vec![(
"04/11/22".to_owned(),
"04/13/22".to_owned(),
-1,
46.92,
46.90
)],
vec![]
)
);
assert_eq!(
parse_brokerage_statement("data/example5.pdf"),
(
vec![],
vec![],
vec![(
"04/11/22".to_owned(),
"04/13/22".to_owned(),
1,
46.92,
46.92,
0.01,
0.01,
46.9
)]
)
);
Ok(())
}
}
| 47.149554 | 192 | 0.373526 |
f409a29b3c26ed6f7e8b9b67fb1c7d2792bad2ff
| 4,721 |
use crate::ics02_client::client_consensus::AnyConsensusState;
use crate::ics02_client::client_def::ClientDef;
use crate::ics02_client::client_state::AnyClientState;
use crate::ics03_connection::connection::ConnectionEnd;
use crate::ics04_channel::channel::ChannelEnd;
use crate::ics04_channel::packet::Sequence;
use crate::ics23_commitment::commitment::{CommitmentPrefix, CommitmentProofBytes, CommitmentRoot};
use crate::ics23_commitment::merkle::apply_prefix;
use crate::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId};
use crate::ics24_host::Path;
use crate::mock::client_state::{MockClientState, MockConsensusState};
use crate::mock::header::MockHeader;
use crate::Height;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MockClient;
impl ClientDef for MockClient {
type Header = MockHeader;
type ClientState = MockClientState;
type ConsensusState = MockConsensusState;
fn check_header_and_update_state(
&self,
client_state: Self::ClientState,
header: Self::Header,
) -> Result<(Self::ClientState, Self::ConsensusState), Box<dyn std::error::Error>> {
if client_state.latest_height() >= header.height() {
return Err(
"received header height is lower than (or equal to) client latest height".into(),
);
}
Ok((MockClientState(header), MockConsensusState(header)))
}
fn verify_client_consensus_state(
&self,
_client_state: &Self::ClientState,
height: Height,
prefix: &CommitmentPrefix,
_proof: &CommitmentProofBytes,
client_id: &ClientId,
_consensus_height: Height,
_expected_consensus_state: &AnyConsensusState,
) -> Result<(), Box<dyn std::error::Error>> {
let client_prefixed_path = Path::ClientConsensusState {
client_id: client_id.clone(),
epoch: height.revision_number,
height: height.revision_height,
}
.to_string();
let _path = apply_prefix(prefix, vec![client_prefixed_path])?;
// TODO - add ctx to all client verification functions
// let cs = ctx.fetch_self_consensus_state(height);
// TODO - implement this
// proof.verify_membership(cs.root(), path, expected_consensus_state)
Ok(())
}
fn verify_connection_state(
&self,
_client_state: &Self::ClientState,
_height: Height,
_prefix: &CommitmentPrefix,
_proof: &CommitmentProofBytes,
_connection_id: Option<&ConnectionId>,
_expected_connection_end: &ConnectionEnd,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn verify_channel_state(
&self,
_client_state: &Self::ClientState,
_height: Height,
_prefix: &CommitmentPrefix,
_proof: &CommitmentProofBytes,
_port_id: &PortId,
_channel_id: &ChannelId,
_expected_channel_end: &ChannelEnd,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn verify_client_full_state(
&self,
_client_state: &Self::ClientState,
_height: Height,
_root: &CommitmentRoot,
_prefix: &CommitmentPrefix,
_client_id: &ClientId,
_proof: &CommitmentProofBytes,
_expected_client_state: &AnyClientState,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn verify_packet_data(
&self,
_client_state: &Self::ClientState,
_height: Height,
_proof: &CommitmentProofBytes,
_port_id: &PortId,
_channel_id: &ChannelId,
_seq: &Sequence,
_data: String,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn verify_packet_acknowledgement(
&self,
_client_state: &Self::ClientState,
_height: Height,
_proof: &CommitmentProofBytes,
_port_id: &PortId,
_channel_id: &ChannelId,
_seq: &Sequence,
_data: Vec<u8>,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn verify_next_sequence_recv(
&self,
_client_state: &Self::ClientState,
_height: Height,
_proof: &CommitmentProofBytes,
_port_id: &PortId,
_channel_id: &ChannelId,
_seq: &Sequence,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn verify_packet_receipt_absence(
&self,
_client_state: &Self::ClientState,
_height: Height,
_proof: &CommitmentProofBytes,
_port_id: &PortId,
_channel_id: &ChannelId,
_seq: &Sequence,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
}
| 31.264901 | 98 | 0.621902 |
ccf13022543d8e529ae2be3acd681f2cffafb439
| 30,492 |
#[doc = "Reader of register PCR2"]
pub type R = crate::R<u32, super::PCR2>;
#[doc = "Writer for register PCR2"]
pub type W = crate::W<u32, super::PCR2>;
#[doc = "Register PCR2 `reset()`'s with value 0x0743"]
impl crate::ResetValue for super::PCR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0743
}
}
#[doc = "Pull Select\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PS_A {
#[doc = "0: Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set."]
_0 = 0,
#[doc = "1: Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set."]
_1 = 1,
}
impl From<PS_A> for bool {
#[inline(always)]
fn from(variant: PS_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PS`"]
pub type PS_R = crate::R<bool, PS_A>;
impl PS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PS_A {
match self.bits {
false => PS_A::_0,
true => PS_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
*self == PS_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
*self == PS_A::_1
}
}
#[doc = "Write proxy for field `PS`"]
pub struct PS_W<'a> {
w: &'a mut W,
}
impl<'a> PS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PS_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(PS_A::_0)
}
#[doc = "Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(PS_A::_1)
}
#[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 = "Pull Enable\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PE_A {
#[doc = "0: Internal pullup or pulldown resistor is not enabled on the corresponding pin."]
_0 = 0,
#[doc = "1: Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input."]
_1 = 1,
}
impl From<PE_A> for bool {
#[inline(always)]
fn from(variant: PE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PE`"]
pub type PE_R = crate::R<bool, PE_A>;
impl PE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PE_A {
match self.bits {
false => PE_A::_0,
true => PE_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
*self == PE_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
*self == PE_A::_1
}
}
#[doc = "Write proxy for field `PE`"]
pub struct PE_W<'a> {
w: &'a mut W,
}
impl<'a> PE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Internal pullup or pulldown resistor is not enabled on the corresponding pin."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(PE_A::_0)
}
#[doc = "Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(PE_A::_1)
}
#[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 = "Slew Rate Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SRE_A {
#[doc = "0: Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output."]
_0 = 0,
#[doc = "1: Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output."]
_1 = 1,
}
impl From<SRE_A> for bool {
#[inline(always)]
fn from(variant: SRE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SRE`"]
pub type SRE_R = crate::R<bool, SRE_A>;
impl SRE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SRE_A {
match self.bits {
false => SRE_A::_0,
true => SRE_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
*self == SRE_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
*self == SRE_A::_1
}
}
#[doc = "Write proxy for field `SRE`"]
pub struct SRE_W<'a> {
w: &'a mut W,
}
impl<'a> SRE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SRE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(SRE_A::_0)
}
#[doc = "Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(SRE_A::_1)
}
#[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 = "Passive Filter Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PFE_A {
#[doc = "0: Passive input filter is disabled on the corresponding pin."]
_0 = 0,
#[doc = "1: Passive input filter is enabled on the corresponding pin, if the pin is configured as a digital input. Refer to the device data sheet for filter characteristics."]
_1 = 1,
}
impl From<PFE_A> for bool {
#[inline(always)]
fn from(variant: PFE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PFE`"]
pub type PFE_R = crate::R<bool, PFE_A>;
impl PFE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PFE_A {
match self.bits {
false => PFE_A::_0,
true => PFE_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
*self == PFE_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
*self == PFE_A::_1
}
}
#[doc = "Write proxy for field `PFE`"]
pub struct PFE_W<'a> {
w: &'a mut W,
}
impl<'a> PFE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PFE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Passive input filter is disabled on the corresponding pin."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(PFE_A::_0)
}
#[doc = "Passive input filter is enabled on the corresponding pin, if the pin is configured as a digital input. Refer to the device data sheet for filter characteristics."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(PFE_A::_1)
}
#[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 = "Open Drain Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ODE_A {
#[doc = "0: Open drain output is disabled on the corresponding pin."]
_0 = 0,
#[doc = "1: Open drain output is enabled on the corresponding pin, if the pin is configured as a digital output."]
_1 = 1,
}
impl From<ODE_A> for bool {
#[inline(always)]
fn from(variant: ODE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `ODE`"]
pub type ODE_R = crate::R<bool, ODE_A>;
impl ODE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ODE_A {
match self.bits {
false => ODE_A::_0,
true => ODE_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
*self == ODE_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
*self == ODE_A::_1
}
}
#[doc = "Write proxy for field `ODE`"]
pub struct ODE_W<'a> {
w: &'a mut W,
}
impl<'a> ODE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ODE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Open drain output is disabled on the corresponding pin."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(ODE_A::_0)
}
#[doc = "Open drain output is enabled on the corresponding pin, if the pin is configured as a digital output."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(ODE_A::_1)
}
#[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 = "Drive Strength Enable\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DSE_A {
#[doc = "0: Low drive strength is configured on the corresponding pin, if pin is configured as a digital output."]
_0 = 0,
#[doc = "1: High drive strength is configured on the corresponding pin, if pin is configured as a digital output."]
_1 = 1,
}
impl From<DSE_A> for bool {
#[inline(always)]
fn from(variant: DSE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `DSE`"]
pub type DSE_R = crate::R<bool, DSE_A>;
impl DSE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DSE_A {
match self.bits {
false => DSE_A::_0,
true => DSE_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
*self == DSE_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
*self == DSE_A::_1
}
}
#[doc = "Write proxy for field `DSE`"]
pub struct DSE_W<'a> {
w: &'a mut W,
}
impl<'a> DSE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DSE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Low drive strength is configured on the corresponding pin, if pin is configured as a digital output."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(DSE_A::_0)
}
#[doc = "High drive strength is configured on the corresponding pin, if pin is configured as a digital output."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(DSE_A::_1)
}
#[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 = "Pin Mux Control\n\nValue on reset: 7"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum MUX_A {
#[doc = "0: Pin disabled (analog)."]
_000 = 0,
#[doc = "1: Alternative 1 (GPIO)."]
_001 = 1,
#[doc = "2: Alternative 2 (chip-specific)."]
_010 = 2,
#[doc = "3: Alternative 3 (chip-specific)."]
_011 = 3,
#[doc = "4: Alternative 4 (chip-specific)."]
_100 = 4,
#[doc = "5: Alternative 5 (chip-specific)."]
_101 = 5,
#[doc = "6: Alternative 6 (chip-specific)."]
_110 = 6,
#[doc = "7: Alternative 7 (chip-specific)."]
_111 = 7,
}
impl From<MUX_A> for u8 {
#[inline(always)]
fn from(variant: MUX_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `MUX`"]
pub type MUX_R = crate::R<u8, MUX_A>;
impl MUX_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MUX_A {
match self.bits {
0 => MUX_A::_000,
1 => MUX_A::_001,
2 => MUX_A::_010,
3 => MUX_A::_011,
4 => MUX_A::_100,
5 => MUX_A::_101,
6 => MUX_A::_110,
7 => MUX_A::_111,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `_000`"]
#[inline(always)]
pub fn is_000(&self) -> bool {
*self == MUX_A::_000
}
#[doc = "Checks if the value of the field is `_001`"]
#[inline(always)]
pub fn is_001(&self) -> bool {
*self == MUX_A::_001
}
#[doc = "Checks if the value of the field is `_010`"]
#[inline(always)]
pub fn is_010(&self) -> bool {
*self == MUX_A::_010
}
#[doc = "Checks if the value of the field is `_011`"]
#[inline(always)]
pub fn is_011(&self) -> bool {
*self == MUX_A::_011
}
#[doc = "Checks if the value of the field is `_100`"]
#[inline(always)]
pub fn is_100(&self) -> bool {
*self == MUX_A::_100
}
#[doc = "Checks if the value of the field is `_101`"]
#[inline(always)]
pub fn is_101(&self) -> bool {
*self == MUX_A::_101
}
#[doc = "Checks if the value of the field is `_110`"]
#[inline(always)]
pub fn is_110(&self) -> bool {
*self == MUX_A::_110
}
#[doc = "Checks if the value of the field is `_111`"]
#[inline(always)]
pub fn is_111(&self) -> bool {
*self == MUX_A::_111
}
}
#[doc = "Write proxy for field `MUX`"]
pub struct MUX_W<'a> {
w: &'a mut W,
}
impl<'a> MUX_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MUX_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "Pin disabled (analog)."]
#[inline(always)]
pub fn _000(self) -> &'a mut W {
self.variant(MUX_A::_000)
}
#[doc = "Alternative 1 (GPIO)."]
#[inline(always)]
pub fn _001(self) -> &'a mut W {
self.variant(MUX_A::_001)
}
#[doc = "Alternative 2 (chip-specific)."]
#[inline(always)]
pub fn _010(self) -> &'a mut W {
self.variant(MUX_A::_010)
}
#[doc = "Alternative 3 (chip-specific)."]
#[inline(always)]
pub fn _011(self) -> &'a mut W {
self.variant(MUX_A::_011)
}
#[doc = "Alternative 4 (chip-specific)."]
#[inline(always)]
pub fn _100(self) -> &'a mut W {
self.variant(MUX_A::_100)
}
#[doc = "Alternative 5 (chip-specific)."]
#[inline(always)]
pub fn _101(self) -> &'a mut W {
self.variant(MUX_A::_101)
}
#[doc = "Alternative 6 (chip-specific)."]
#[inline(always)]
pub fn _110(self) -> &'a mut W {
self.variant(MUX_A::_110)
}
#[doc = "Alternative 7 (chip-specific)."]
#[inline(always)]
pub fn _111(self) -> &'a mut W {
self.variant(MUX_A::_111)
}
#[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 & !(0x07 << 8)) | (((value as u32) & 0x07) << 8);
self.w
}
}
#[doc = "Lock Register\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LK_A {
#[doc = "0: Pin Control Register fields \\[15:0\\]
are not locked."]
_0 = 0,
#[doc = "1: Pin Control Register fields \\[15:0\\]
are locked and cannot be updated until the next system reset."]
_1 = 1,
}
impl From<LK_A> for bool {
#[inline(always)]
fn from(variant: LK_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LK`"]
pub type LK_R = crate::R<bool, LK_A>;
impl LK_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LK_A {
match self.bits {
false => LK_A::_0,
true => LK_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
*self == LK_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
*self == LK_A::_1
}
}
#[doc = "Write proxy for field `LK`"]
pub struct LK_W<'a> {
w: &'a mut W,
}
impl<'a> LK_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LK_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Pin Control Register fields \\[15:0\\]
are not locked."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(LK_A::_0)
}
#[doc = "Pin Control Register fields \\[15:0\\]
are locked and cannot be updated until the next system reset."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(LK_A::_1)
}
#[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 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Interrupt Configuration\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum IRQC_A {
#[doc = "0: Interrupt/DMA request disabled."]
_0000 = 0,
#[doc = "1: DMA request on rising edge."]
_0001 = 1,
#[doc = "2: DMA request on falling edge."]
_0010 = 2,
#[doc = "3: DMA request on either edge."]
_0011 = 3,
#[doc = "8: Interrupt when logic zero."]
_1000 = 8,
#[doc = "9: Interrupt on rising edge."]
_1001 = 9,
#[doc = "10: Interrupt on falling edge."]
_1010 = 10,
#[doc = "11: Interrupt on either edge."]
_1011 = 11,
#[doc = "12: Interrupt when logic one."]
_1100 = 12,
}
impl From<IRQC_A> for u8 {
#[inline(always)]
fn from(variant: IRQC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `IRQC`"]
pub type IRQC_R = crate::R<u8, IRQC_A>;
impl IRQC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, IRQC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(IRQC_A::_0000),
1 => Val(IRQC_A::_0001),
2 => Val(IRQC_A::_0010),
3 => Val(IRQC_A::_0011),
8 => Val(IRQC_A::_1000),
9 => Val(IRQC_A::_1001),
10 => Val(IRQC_A::_1010),
11 => Val(IRQC_A::_1011),
12 => Val(IRQC_A::_1100),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `_0000`"]
#[inline(always)]
pub fn is_0000(&self) -> bool {
*self == IRQC_A::_0000
}
#[doc = "Checks if the value of the field is `_0001`"]
#[inline(always)]
pub fn is_0001(&self) -> bool {
*self == IRQC_A::_0001
}
#[doc = "Checks if the value of the field is `_0010`"]
#[inline(always)]
pub fn is_0010(&self) -> bool {
*self == IRQC_A::_0010
}
#[doc = "Checks if the value of the field is `_0011`"]
#[inline(always)]
pub fn is_0011(&self) -> bool {
*self == IRQC_A::_0011
}
#[doc = "Checks if the value of the field is `_1000`"]
#[inline(always)]
pub fn is_1000(&self) -> bool {
*self == IRQC_A::_1000
}
#[doc = "Checks if the value of the field is `_1001`"]
#[inline(always)]
pub fn is_1001(&self) -> bool {
*self == IRQC_A::_1001
}
#[doc = "Checks if the value of the field is `_1010`"]
#[inline(always)]
pub fn is_1010(&self) -> bool {
*self == IRQC_A::_1010
}
#[doc = "Checks if the value of the field is `_1011`"]
#[inline(always)]
pub fn is_1011(&self) -> bool {
*self == IRQC_A::_1011
}
#[doc = "Checks if the value of the field is `_1100`"]
#[inline(always)]
pub fn is_1100(&self) -> bool {
*self == IRQC_A::_1100
}
}
#[doc = "Write proxy for field `IRQC`"]
pub struct IRQC_W<'a> {
w: &'a mut W,
}
impl<'a> IRQC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: IRQC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Interrupt/DMA request disabled."]
#[inline(always)]
pub fn _0000(self) -> &'a mut W {
self.variant(IRQC_A::_0000)
}
#[doc = "DMA request on rising edge."]
#[inline(always)]
pub fn _0001(self) -> &'a mut W {
self.variant(IRQC_A::_0001)
}
#[doc = "DMA request on falling edge."]
#[inline(always)]
pub fn _0010(self) -> &'a mut W {
self.variant(IRQC_A::_0010)
}
#[doc = "DMA request on either edge."]
#[inline(always)]
pub fn _0011(self) -> &'a mut W {
self.variant(IRQC_A::_0011)
}
#[doc = "Interrupt when logic zero."]
#[inline(always)]
pub fn _1000(self) -> &'a mut W {
self.variant(IRQC_A::_1000)
}
#[doc = "Interrupt on rising edge."]
#[inline(always)]
pub fn _1001(self) -> &'a mut W {
self.variant(IRQC_A::_1001)
}
#[doc = "Interrupt on falling edge."]
#[inline(always)]
pub fn _1010(self) -> &'a mut W {
self.variant(IRQC_A::_1010)
}
#[doc = "Interrupt on either edge."]
#[inline(always)]
pub fn _1011(self) -> &'a mut W {
self.variant(IRQC_A::_1011)
}
#[doc = "Interrupt when logic one."]
#[inline(always)]
pub fn _1100(self) -> &'a mut W {
self.variant(IRQC_A::_1100)
}
#[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 << 16)) | (((value as u32) & 0x0f) << 16);
self.w
}
}
#[doc = "Interrupt Status Flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ISF_A {
#[doc = "0: Configured interrupt is not detected."]
_0 = 0,
#[doc = "1: Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared."]
_1 = 1,
}
impl From<ISF_A> for bool {
#[inline(always)]
fn from(variant: ISF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `ISF`"]
pub type ISF_R = crate::R<bool, ISF_A>;
impl ISF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ISF_A {
match self.bits {
false => ISF_A::_0,
true => ISF_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
*self == ISF_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
*self == ISF_A::_1
}
}
#[doc = "Write proxy for field `ISF`"]
pub struct ISF_W<'a> {
w: &'a mut W,
}
impl<'a> ISF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ISF_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Configured interrupt is not detected."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(ISF_A::_0)
}
#[doc = "Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(ISF_A::_1)
}
#[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 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
impl R {
#[doc = "Bit 0 - Pull Select"]
#[inline(always)]
pub fn ps(&self) -> PS_R {
PS_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Pull Enable"]
#[inline(always)]
pub fn pe(&self) -> PE_R {
PE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Slew Rate Enable"]
#[inline(always)]
pub fn sre(&self) -> SRE_R {
SRE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 4 - Passive Filter Enable"]
#[inline(always)]
pub fn pfe(&self) -> PFE_R {
PFE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Open Drain Enable"]
#[inline(always)]
pub fn ode(&self) -> ODE_R {
ODE_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Drive Strength Enable"]
#[inline(always)]
pub fn dse(&self) -> DSE_R {
DSE_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bits 8:10 - Pin Mux Control"]
#[inline(always)]
pub fn mux(&self) -> MUX_R {
MUX_R::new(((self.bits >> 8) & 0x07) as u8)
}
#[doc = "Bit 15 - Lock Register"]
#[inline(always)]
pub fn lk(&self) -> LK_R {
LK_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bits 16:19 - Interrupt Configuration"]
#[inline(always)]
pub fn irqc(&self) -> IRQC_R {
IRQC_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bit 24 - Interrupt Status Flag"]
#[inline(always)]
pub fn isf(&self) -> ISF_R {
ISF_R::new(((self.bits >> 24) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Pull Select"]
#[inline(always)]
pub fn ps(&mut self) -> PS_W {
PS_W { w: self }
}
#[doc = "Bit 1 - Pull Enable"]
#[inline(always)]
pub fn pe(&mut self) -> PE_W {
PE_W { w: self }
}
#[doc = "Bit 2 - Slew Rate Enable"]
#[inline(always)]
pub fn sre(&mut self) -> SRE_W {
SRE_W { w: self }
}
#[doc = "Bit 4 - Passive Filter Enable"]
#[inline(always)]
pub fn pfe(&mut self) -> PFE_W {
PFE_W { w: self }
}
#[doc = "Bit 5 - Open Drain Enable"]
#[inline(always)]
pub fn ode(&mut self) -> ODE_W {
ODE_W { w: self }
}
#[doc = "Bit 6 - Drive Strength Enable"]
#[inline(always)]
pub fn dse(&mut self) -> DSE_W {
DSE_W { w: self }
}
#[doc = "Bits 8:10 - Pin Mux Control"]
#[inline(always)]
pub fn mux(&mut self) -> MUX_W {
MUX_W { w: self }
}
#[doc = "Bit 15 - Lock Register"]
#[inline(always)]
pub fn lk(&mut self) -> LK_W {
LK_W { w: self }
}
#[doc = "Bits 16:19 - Interrupt Configuration"]
#[inline(always)]
pub fn irqc(&mut self) -> IRQC_W {
IRQC_W { w: self }
}
#[doc = "Bit 24 - Interrupt Status Flag"]
#[inline(always)]
pub fn isf(&mut self) -> ISF_W {
ISF_W { w: self }
}
}
| 29.806452 | 431 | 0.543684 |
5097f55b7172cf632fcfa954befe2580750e2109
| 24,056 |
use crate::build_tools::ast;
use crate::build_tools::lexer::Lexer;
use crate::build_tools::token::*;
use std::collections::HashMap;
/// Operator precedence constants
static LOWEST: usize = 1;
/// =
static EQUALS: usize = 2;
/// && and ||
static LOGICAL: usize = 3;
/// > or <
static LESS_GREATER: usize = 4;
/// +
static SUM: usize = 5;
/// *
static PRODUCT: usize = 6;
/// %
static MODULO: usize = 7;
/// -x or !x
static PREFIX: usize = 8;
/// myFunction(x)
static CALL: usize = 9;
/// array[index], hash[key]
static INDEX: usize = 10;
struct Precedences;
/// Operator precedence table
impl Precedences {
pub fn all() -> HashMap<TokenType, usize> {
let mut precendences: HashMap<TokenType, usize> = HashMap::new();
precendences.insert(TokenType::EQUAL_EQUAL, EQUALS);
precendences.insert(TokenType::BANG_EQUAL, EQUALS);
precendences.insert(TokenType::LESS, LESS_GREATER);
precendences.insert(TokenType::GREATER, LESS_GREATER);
precendences.insert(TokenType::LESS_EQUAL, LESS_GREATER);
precendences.insert(TokenType::GREATER_EQUAL, LESS_GREATER);
precendences.insert(TokenType::PLUS, SUM);
precendences.insert(TokenType::MINUS, SUM);
precendences.insert(TokenType::SLASH, PRODUCT);
precendences.insert(TokenType::STAR, PRODUCT);
precendences.insert(TokenType::MOD, MODULO);
precendences.insert(TokenType::AND, LOGICAL);
precendences.insert(TokenType::OR, LOGICAL);
precendences.insert(TokenType::LEFT_PAREN, CALL);
precendences.insert(TokenType::LEFT_BRACKET, INDEX);
precendences
}
}
type PrefixParseFunc = fn(parser: &mut Parser) -> Box<dyn ast::Expression>;
type InfixParseFunc =
fn(parser: &mut Parser, expr: Box<dyn ast::Expression>) -> Box<dyn ast::Expression>;
type PostfixParseFunc = fn(parser: &mut Parser) -> Box<dyn ast::Expression>;
/// Parser holds a Lexer, its errors, the current_token, peek_token (next token), and
/// prev_token (used for ++ and --), as well as the prefix/infix/postfix functions
pub struct Parser {
lexer: Lexer,
errors: Vec<String>,
current_token: Token,
peek_token: Token,
prev_token: Token,
prefix_parse_funcs: HashMap<TokenType, PrefixParseFunc>,
infix_parse_funcs: HashMap<TokenType, InfixParseFunc>,
postfix_parse_funcs: HashMap<TokenType, PostfixParseFunc>,
}
impl Parser {
/// New takes a Lexer, creates a Parser with that Lexer, sets the
/// current and peek tokens, and returns the Parser.
pub fn new(lexer: Lexer) -> Parser {
let mut parser = Parser {
lexer,
errors: vec![],
current_token: Token {
line: 0,
literal: "".to_owned(),
token_type: TokenType::NONE,
},
peek_token: Token {
line: 0,
literal: "".to_owned(),
token_type: TokenType::NONE,
},
prev_token: Token {
line: 0,
literal: "".to_owned(),
token_type: TokenType::NONE,
},
prefix_parse_funcs: HashMap::new(),
infix_parse_funcs: HashMap::new(),
postfix_parse_funcs: HashMap::new(),
};
// Register all of our prefix parse funcs
parser.register_prefix(TokenType::IDENTIFIER, parse_identifier);
parser.register_prefix(TokenType::INTEGER, parse_integer_literal);
parser.register_prefix(TokenType::BANG, parse_prefix_expr);
parser.register_prefix(TokenType::MINUS, parse_prefix_expr);
parser.register_prefix(TokenType::TRUE, parse_boolean);
parser.register_prefix(TokenType::FALSE, parse_boolean);
parser.register_prefix(TokenType::LEFT_PAREN, parse_grouped_expr);
parser.register_prefix(TokenType::IF, parse_if_expr);
parser.register_prefix(TokenType::FUNCTION, parse_function_literal);
parser.register_prefix(TokenType::STRING, parse_string_literal);
parser.register_prefix(TokenType::LEFT_BRACKET, parse_array_literal);
parser.register_prefix(TokenType::LEFT_BRACE, parse_hash_literal);
// Register all of our infix parse funcs
parser.register_infix(TokenType::PLUS, parse_infix_expr);
// p.registerInfix(token.Minus, p.parseInfixExpression)
// p.registerInfix(token.Slash, p.parseInfixExpression)
// p.registerInfix(token.Star, p.parseInfixExpression)
// p.registerInfix(token.Mod, p.parseInfixExpression)
// p.registerInfix(token.EqualEqual, p.parseInfixExpression)
// p.registerInfix(token.BangEqual, p.parseInfixExpression)
// p.registerInfix(token.Less, p.parseInfixExpression)
// p.registerInfix(token.Greater, p.parseInfixExpression)
// p.registerInfix(token.LessEqual, p.parseInfixExpression)
// p.registerInfix(token.GreaterEqual, p.parseInfixExpression)
// p.registerInfix(token.LeftParen, p.parseCallExpression)
// p.registerInfix(token.LeftBracket, p.parseIndexExpr)
// p.registerInfix(token.And, p.parseInfixExpression)
// p.registerInfix(token.Or, p.parseInfixExpression)
parser
}
fn register_prefix(&mut self, token_type: TokenType, func: PrefixParseFunc) {
self.prefix_parse_funcs.insert(token_type, func);
}
fn register_infix(&mut self, token_type: TokenType, func: InfixParseFunc) {
self.infix_parse_funcs.insert(token_type, func);
}
fn next_token(&mut self) {
self.prev_token = self.current_token.clone();
self.current_token = self.peek_token.clone();
self.peek_token = self.lexer.clone().next_token();
}
fn parse_expr(&mut self, precedence: usize) -> Option<Box<dyn ast::Expression>> {
let prefix = match self.prefix_parse_funcs.get(&self.current_token.token_type) {
Some(&func) => func,
_ => {
self.no_prefix_parse_func_error(self.current_token.clone());
return None;
}
};
let mut left_expr = prefix(self);
while !self.peek_token_type_is(TokenType::SEMICOLON)
&& precedence < self.peek_token_precedence()
{
let infix = match self.infix_parse_funcs.get(&self.peek_token.token_type) {
Some(&func) => func,
_ => {
return Some(left_expr);
}
};
self.next_token();
left_expr = infix(self, left_expr);
}
Some(left_expr)
}
fn parse_block_stmt(&mut self) -> ast::BlockStatement {
let mut block = ast::BlockStatement {
token: self.current_token.clone(),
statements: vec![],
};
self.next_token();
while !self.current_token_type_is(TokenType::RIGHT_BRACE)
&& !self.current_token_type_is(TokenType::EOF)
{
let stmt = match self.parse_stmt() {
Some(stmt) => {
block.statements.push(stmt);
}
_ => {
return ast::BlockStatement {
token: Token {
line: 0,
literal: "".to_owned(),
token_type: TokenType::NONE,
},
statements: vec![],
}
}
};
self.next_token();
}
block
}
fn parse_stmt(&mut self) -> Option<Box<dyn ast::Statement>> {
let ret = match self.current_token.token_type {
TokenType::LET => parse_let_stmt(self),
TokenType::CONST => parse_const_stmt(self),
TokenType::RETURN => parse_return_stmt(self),
_ => parse_expr_stmt(self),
};
Some(ret)
}
fn parse_function_params(&mut self) -> Vec<ast::Identifier> {
let mut identifiers: Vec<ast::Identifier> = vec![];
if self.peek_token_type_is(TokenType::RIGHT_PAREN) {
self.next_token();
return identifiers;
}
self.next_token();
identifiers.push(ast::Identifier{
token: self.current_token.clone(),
value: self.current_token.literal.clone(),
});
while self.peek_token_type_is(TokenType::COMMA) {
self.next_token();
self.next_token();
identifiers.push(ast::Identifier{
token: self.current_token.clone(),
value: self.current_token.literal.clone(),
})
}
if !self.expect_peek_type(TokenType::RIGHT_PAREN) {
return vec![];
}
identifiers
}
fn parse_expr_list(&mut self, end: TokenType) -> Vec<Box<dyn ast::Expression>> {
let mut list: Vec<Box<dyn ast::Expression>> = vec![Box::new(ast::ZeroValueExpression{})];
if self.peek_token_type_is(end) {
self.next_token();
return list;
}
self.next_token();
let expr = match self.parse_expr(LOWEST) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
self.current_token.line, self.current_token.literal
);
self.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
list.push(expr);
while self.peek_token_type_is(TokenType::COMMA) {
self.next_token();
self.next_token();
let expr = match self.parse_expr(LOWEST) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
self.current_token.line, self.current_token.literal
);
self.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
list.push(expr);
}
if self.expect_peek_type(end) {
return vec![Box::new(ast::ZeroValueExpression {})];
}
list
}
fn peek_token_type_is(&self, token_type: TokenType) -> bool {
self.peek_token.token_type == token_type
}
fn peek_token_precedence(&self) -> usize {
match Precedences::all().get(&self.peek_token.token_type) {
Some(precedence) => return *precedence,
_ => return LOWEST,
};
}
fn expect_peek_type(&mut self, token_type: TokenType) -> bool {
if self.peek_token_type_is(token_type) {
self.next_token();
return true;
}
self.peek_error(token_type);
return false;
}
fn peek_error(&mut self, token_type: TokenType) {
let msg = format!(
"Line {}: Expected token to be {}, but found, {}",
self.current_token.line, token_type, self.peek_token.literal,
);
self.errors.push(msg);
}
fn no_prefix_parse_func_error(&mut self, token: Token) {
let msg = format!(
"Line {}: No prefix parse function for {} found",
self.current_token.line, token.literal
);
self.errors.push(msg);
}
fn current_token_type_is(&self, token_type: TokenType) -> bool {
self.current_token.token_type == token_type
}
fn current_token_precedence(&self) -> usize {
match Precedences::all().get(&self.current_token.token_type) {
Some(precedence) => *precedence,
None => LOWEST,
}
}
}
fn parse_identifier(parser: &mut Parser) -> Box<dyn ast::Expression> {
let contains_key = parser
.postfix_parse_funcs
.contains_key(&parser.peek_token.token_type);
if contains_key {
let postfix = parser.postfix_parse_funcs[&parser.peek_token.token_type];
parser.next_token();
return postfix(parser);
}
Box::new(ast::Identifier {
token: parser.current_token.clone(),
value: parser.current_token.literal.clone(),
})
}
fn parse_integer_literal(parser: &mut Parser) -> Box<dyn ast::Expression> {
Box::new(ast::IntegerLiteral {
token: parser.current_token.clone(),
value: parser.current_token.literal.parse::<usize>().unwrap(),
})
}
fn parse_prefix_expr(parser: &mut Parser) -> Box<dyn ast::Expression> {
let mut expr = ast::PrefixExpression {
token: parser.current_token.clone(),
operator: parser.current_token.literal.clone(),
right: Box::new(ast::ZeroValueExpression {}),
};
parser.next_token();
expr.right = match parser.parse_expr(PREFIX) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
parser.current_token.line, parser.current_token.literal
);
parser.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
Box::new(expr)
}
fn parse_boolean(parser: &mut Parser) -> Box<dyn ast::Expression> {
Box::new(ast::Boolean {
token: parser.current_token.clone(),
value: parser.current_token_type_is(TokenType::TRUE),
})
}
fn parse_grouped_expr(parser: &mut Parser) -> Box<dyn ast::Expression> {
parser.next_token();
let expr = match parser.parse_expr(LOWEST) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
parser.current_token.line, parser.current_token.literal
);
parser.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
if !parser.expect_peek_type(TokenType::RIGHT_PAREN) {
return Box::new(ast::ZeroValueExpression {});
}
expr
}
fn parse_if_expr(parser: &mut Parser) -> Box<dyn ast::Expression> {
let mut expr = ast::IfExpression {
token: parser.current_token.clone(),
condition: Box::new(ast::ZeroValueExpression {}),
consequence: ast::BlockStatement {
token: parser.current_token.clone(),
statements: vec![],
},
alternative: ast::BlockStatement {
token: parser.current_token.clone(),
statements: vec![],
},
};
if !parser.expect_peek_type(TokenType::LEFT_PAREN) {
return Box::new(ast::ZeroValueExpression {});
}
parser.next_token();
expr.condition = match parser.parse_expr(LOWEST) {
Some(cond) => cond,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
parser.current_token.line, parser.current_token.literal
);
parser.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
if !parser.expect_peek_type(TokenType::RIGHT_PAREN) {
return Box::new(ast::ZeroValueExpression {});
}
if !parser.expect_peek_type(TokenType::LEFT_BRACE) {
return Box::new(ast::ZeroValueExpression {});
}
expr.consequence = parser.parse_block_stmt();
if parser.peek_token_type_is(TokenType::ELSE) {
parser.next_token();
if !parser.expect_peek_type(TokenType::LEFT_BRACE) {
return Box::new(ast::ZeroValueExpression {});
}
expr.alternative = parser.parse_block_stmt();
}
Box::new(expr)
}
fn parse_let_stmt(parser: &mut Parser) -> Box<dyn ast::Statement> {
let zero_value_token: Token = Token {
token_type: TokenType::NONE,
literal: "".to_owned(),
line: 0,
};
let zero_value_identifier: ast::Identifier = ast::Identifier {
token: zero_value_token,
value: "".to_owned(),
};
let mut stmt = ast::LetStatement {
token: parser.current_token.clone(),
name: zero_value_identifier,
value: Box::new(ast::ZeroValueExpression {}),
};
if !parser.expect_peek_type(TokenType::IDENTIFIER) {
return Box::new(ast::ZeroValueStatement {});
}
stmt.name = ast::Identifier {
token: parser.current_token.clone(),
value: parser.current_token.literal.clone(),
};
if !parser.expect_peek_type(TokenType::EQUAL) {
return Box::new(ast::ZeroValueStatement {});
}
parser.next_token();
stmt.value = match parser.parse_expr(LOWEST) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
parser.current_token.line, parser.current_token.literal
);
parser.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
// TODO: Handle function literal piece here
// if fl, ok := stmt.Value.(*ast.FunctionLiteral); ok {
// fl.Name = stmt.Name.Value
// }
if parser.peek_token_type_is(TokenType::SEMICOLON) {
parser.next_token();
}
Box::new(stmt)
}
fn parse_const_stmt(parser: &mut Parser) -> Box<dyn ast::Statement> {
let zero_value_token: Token = Token {
token_type: TokenType::NONE,
literal: "".to_owned(),
line: 0,
};
let zero_value_identifier: ast::Identifier = ast::Identifier {
token: zero_value_token,
value: "".to_owned(),
};
let mut stmt = ast::ConstStatement {
token: parser.current_token.clone(),
name: zero_value_identifier,
value: Box::new(ast::ZeroValueExpression {}),
};
if !parser.expect_peek_type(TokenType::IDENTIFIER) {
return Box::new(ast::ZeroValueStatement {});
}
stmt.name = ast::Identifier {
token: parser.current_token.clone(),
value: parser.current_token.literal.clone(),
};
if !parser.expect_peek_type(TokenType::EQUAL) {
return Box::new(ast::ZeroValueStatement {});
}
parser.next_token();
stmt.value = match parser.parse_expr(LOWEST) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
parser.current_token.line, parser.current_token.literal
);
parser.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
// TODO: Handle function literal piece here
// if fl, ok := stmt.Value.(*ast.FunctionLiteral); ok {
// fl.Name = stmt.Name.Value
// }
if parser.peek_token_type_is(TokenType::SEMICOLON) {
parser.next_token();
}
Box::new(stmt)
}
fn parse_return_stmt(parser: &mut Parser) -> Box<dyn ast::Statement> {
let mut stmt = ast::ReturnStatement {
token: parser.current_token.clone(),
return_value: Box::new(ast::ZeroValueExpression {}),
};
parser.next_token();
stmt.return_value = match parser.parse_expr(LOWEST) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
parser.current_token.line, parser.current_token.literal,
);
parser.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
if parser.peek_token_type_is(TokenType::SEMICOLON) {
parser.next_token();
}
Box::new(stmt)
}
fn parse_expr_stmt(parser: &mut Parser) -> Box<dyn ast::Statement> {
let mut stmt = ast::ExpressionStatement {
token: parser.current_token.clone(),
expression: Box::new(ast::ZeroValueExpression {}),
};
stmt.expression = match parser.parse_expr(LOWEST) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
parser.current_token.line, parser.current_token.literal,
);
parser.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
if parser.peek_token_type_is(TokenType::SEMICOLON) {
parser.next_token();
}
Box::new(stmt)
}
fn parse_function_literal(parser: &mut Parser) -> Box<dyn ast::Expression> {
let zero_value_token: Token = Token {
token_type: TokenType::NONE,
literal: "".to_owned(),
line: 0,
};
let mut lit = ast::FunctionLiteral{
token: parser.current_token.clone(),
parameters: vec![],
body: ast::BlockStatement{
token: zero_value_token,
statements: vec![],
},
name: "".to_owned(),
};
if !parser.expect_peek_type(TokenType::LEFT_PAREN) {
return Box::new(ast::ZeroValueExpression {});
}
lit.parameters = parser.parse_function_params();
if !parser.expect_peek_type(TokenType::LEFT_BRACE) {
return Box::new(ast::ZeroValueExpression {});
}
lit.body = parser.parse_block_stmt();
Box::new(lit)
}
fn parse_string_literal(parser: &mut Parser) -> Box<dyn ast::Expression> {
Box::new(ast::StringLiteral{
token: parser.current_token.clone(),
value: parser.current_token.literal.clone(),
})
}
fn parse_array_literal(parser: &mut Parser) -> Box<dyn ast::Expression> {
let mut array = ast::ArrayLiteral{
token: parser.current_token.clone(),
elements: vec![],
};
array.elements = parser.parse_expr_list(TokenType::RIGHT_BRACKET);
Box::new(array)
}
fn parse_hash_literal(parser: &mut Parser) -> Box<dyn ast::Expression> {
let mut hash = ast::HashLiteral{
token: parser.current_token.clone(),
pairs: HashMap::new(),
};
while !parser.peek_token_type_is(TokenType::RIGHT_BRACE) {
parser.next_token();
let key = match parser.parse_expr(LOWEST) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
parser.current_token.line, parser.current_token.literal,
);
parser.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
if !parser.expect_peek_type(TokenType::COLON) {
return Box::new(ast::ZeroValueExpression {});
}
parser.next_token();
let value = match parser.parse_expr(LOWEST) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
parser.current_token.line, parser.current_token.literal,
);
parser.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
hash.pairs.insert(key.string(), value);
if !parser.peek_token_type_is(TokenType::RIGHT_BRACE) && !parser.expect_peek_type(TokenType::COMMA) {
return Box::new(ast::ZeroValueExpression {});
}
}
if !parser.peek_token_type_is(TokenType::RIGHT_BRACE) && !parser.expect_peek_type(TokenType::COMMA) {
return Box::new(ast::ZeroValueExpression {});
}
Box::new(hash)
}
fn parse_infix_expr(parser: &mut Parser, left: Box<dyn ast::Expression>) -> Box<dyn ast::Expression> {
let mut expr = ast::InfixExpression{
token: parser.current_token.clone(),
operator: parser.current_token.literal.clone(),
left,
right: Box::new(ast::ZeroValueExpression {}),
};
let precedence = parser.current_token_precedence();
parser.next_token();
expr.right = match parser.parse_expr(precedence) {
Some(expr) => expr,
_ => {
let msg = format!(
"Line {}: Failed to parse expression {}.",
parser.current_token.line, parser.current_token.literal,
);
parser.errors.push(msg);
Box::new(ast::ZeroValueExpression {})
}
};
Box::new(expr)
}
| 31.282185 | 109 | 0.581851 |
71f88f58c310546680a62f529b020157eef4532a
| 17,533 |
use crate::*;
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "persistence", serde(default))]
pub(crate) struct State {
/// Positive offset means scrolling down/right
offset: Vec2,
show_scroll: bool,
/// Momentum, used for kinetic scrolling
#[cfg_attr(feature = "persistence", serde(skip))]
pub vel: Vec2,
/// Mouse offset relative to the top of the handle when started moving the handle.
scroll_start_offset_from_top: Option<f32>,
}
impl Default for State {
fn default() -> Self {
Self {
offset: Vec2::ZERO,
show_scroll: false,
vel: Vec2::ZERO,
scroll_start_offset_from_top: None,
}
}
}
// TODO: rename VScroll
/// Add vertical scrolling to a contained [`Ui`].
#[derive(Clone, Debug)]
#[must_use = "You should call .show()"]
pub struct ScrollArea {
max_height: f32,
always_show_scroll: bool,
id_source: Option<Id>,
offset: Option<Vec2>,
scrolling_enabled: bool,
}
impl ScrollArea {
/// Will make the area be as high as it is allowed to be (i.e. fill the [`Ui`] it is in)
pub fn auto_sized() -> Self {
Self::from_max_height(f32::INFINITY)
}
/// Use `f32::INFINITY` if you want the scroll area to expand to fit the surrounding Ui
pub fn from_max_height(max_height: f32) -> Self {
Self {
max_height,
always_show_scroll: false,
id_source: None,
offset: None,
scrolling_enabled: true,
}
}
/// If `false` (default), the scroll bar will be hidden when not needed/
/// If `true`, the scroll bar will always be displayed even if not needed.
pub fn always_show_scroll(mut self, always_show_scroll: bool) -> Self {
self.always_show_scroll = always_show_scroll;
self
}
/// A source for the unique `Id`, e.g. `.id_source("second_scroll_area")` or `.id_source(loop_index)`.
pub fn id_source(mut self, id_source: impl std::hash::Hash) -> Self {
self.id_source = Some(Id::new(id_source));
self
}
/// Set the vertical scroll offset position.
///
/// See also: [`Ui::scroll_to_cursor`](crate::ui::Ui::scroll_to_cursor) and
/// [`Response::scroll_to_me`](crate::Response::scroll_to_me)
pub fn scroll_offset(mut self, offset: f32) -> Self {
self.offset = Some(Vec2::new(0.0, offset));
self
}
/// Control the scrolling behavior
/// If `true` (default), the scroll area will respond to user scrolling
/// If `false`, the scroll area will not respond to user scrolling
///
/// This can be used, for example, to optionally freeze scrolling while the user
/// is inputing text in a `TextEdit` widget contained within the scroll area
pub fn enable_scrolling(mut self, enable: bool) -> Self {
self.scrolling_enabled = enable;
self
}
}
struct Prepared {
id: Id,
state: State,
current_scroll_bar_width: f32,
always_show_scroll: bool,
inner_rect: Rect,
content_ui: Ui,
/// Relative coordinates: the offset and size of the view of the inner UI.
/// `viewport.min == ZERO` means we scrolled to the top.
viewport: Rect,
scrolling_enabled: bool,
}
impl ScrollArea {
fn begin(self, ui: &mut Ui) -> Prepared {
let Self {
max_height,
always_show_scroll,
id_source,
offset,
scrolling_enabled,
} = self;
let ctx = ui.ctx().clone();
let id_source = id_source.unwrap_or_else(|| Id::new("scroll_area"));
let id = ui.make_persistent_id(id_source);
let mut state = *ctx.memory().id_data.get_or_default::<State>(id);
if let Some(offset) = offset {
state.offset = offset;
}
// content: size of contents (generally large; that's why we want scroll bars)
// outer: size of scroll area including scroll bar(s)
// inner: excluding scroll bar(s). The area we clip the contents to.
let max_scroll_bar_width = max_scroll_bar_width_with_margin(ui);
let current_scroll_bar_width = if always_show_scroll {
max_scroll_bar_width
} else {
max_scroll_bar_width * ui.ctx().animate_bool(id, state.show_scroll)
};
let available_outer = ui.available_rect_before_wrap();
let outer_size = vec2(
available_outer.width(),
available_outer.height().at_most(max_height),
);
let inner_size = outer_size - vec2(current_scroll_bar_width, 0.0);
let inner_rect = Rect::from_min_size(available_outer.min, inner_size);
let mut content_ui = ui.child_ui(
Rect::from_min_size(
inner_rect.min - state.offset,
vec2(inner_size.x, f32::INFINITY),
),
*ui.layout(),
);
let mut content_clip_rect = inner_rect.expand(ui.visuals().clip_rect_margin);
content_clip_rect = content_clip_rect.intersect(ui.clip_rect());
content_clip_rect.max.x = ui.clip_rect().max.x - current_scroll_bar_width; // Nice handling of forced resizing beyond the possible
content_ui.set_clip_rect(content_clip_rect);
let viewport = Rect::from_min_size(Pos2::ZERO + state.offset, inner_size);
Prepared {
id,
state,
current_scroll_bar_width,
always_show_scroll,
inner_rect,
content_ui,
viewport,
scrolling_enabled,
}
}
/// Show the `ScrollArea`, and add the contents to the viewport.
///
/// If the inner area can be very long, consider using [`Self::show_rows`] instead.
pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R {
self.show_viewport(ui, |ui, _viewport| add_contents(ui))
}
/// Efficiently show only the visible part of a large number of rows.
///
/// ```
/// # let ui = &mut egui::Ui::__test();
/// let text_style = egui::TextStyle::Body;
/// let row_height = ui.fonts()[text_style].row_height();
/// // let row_height = ui.spacing().interact_size.y; // if you are adding buttons instead of labels.
/// let num_rows = 10_000;
/// egui::ScrollArea::auto_sized().show_rows(ui, row_height, num_rows, |ui, row_range| {
/// for row in row_range {
/// let text = format!("Row {}/{}", row + 1, num_rows);
/// ui.label(text);
/// }
/// });
pub fn show_rows<R>(
self,
ui: &mut Ui,
row_height_sans_spacing: f32,
num_rows: usize,
add_contents: impl FnOnce(&mut Ui, std::ops::Range<usize>) -> R,
) -> R {
let spacing = ui.spacing().item_spacing;
let row_height_with_spacing = row_height_sans_spacing + spacing.y;
self.show_viewport(ui, |ui, viewport| {
ui.set_height((row_height_with_spacing * num_rows as f32 - spacing.y).at_least(0.0));
let min_row = (viewport.min.y / row_height_with_spacing)
.floor()
.at_least(0.0) as usize;
let max_row = (viewport.max.y / row_height_with_spacing).ceil() as usize + 1;
let max_row = max_row.at_most(num_rows);
let y_min = ui.max_rect().top() + min_row as f32 * row_height_with_spacing;
let y_max = ui.max_rect().top() + max_row as f32 * row_height_with_spacing;
let mut viewport_ui = ui.child_ui(
Rect::from_x_y_ranges(ui.max_rect().x_range(), y_min..=y_max),
*ui.layout(),
);
viewport_ui.skip_ahead_auto_ids(min_row); // Make sure we get consistent IDs.
add_contents(&mut viewport_ui, min_row..max_row)
})
}
/// This can be used to only paint the visible part of the contents.
///
/// `add_contents` is past the viewport, which is the relative view of the content.
/// So if the passed rect has min = zero, then show the top left content (the user has not scrolled).
pub fn show_viewport<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui, Rect) -> R) -> R {
let mut prepared = self.begin(ui);
let ret = add_contents(&mut prepared.content_ui, prepared.viewport);
prepared.end(ui);
ret
}
}
impl Prepared {
fn end(self, ui: &mut Ui) {
let Prepared {
id,
mut state,
inner_rect,
always_show_scroll,
mut current_scroll_bar_width,
content_ui,
viewport: _,
scrolling_enabled,
} = self;
let content_size = content_ui.min_size();
// We take the scroll target so only this ScrollArea will use it.
let scroll_target = content_ui.ctx().frame_state().scroll_target.take();
if let Some((scroll_y, align)) = scroll_target {
let center_factor = align.to_factor();
let top = content_ui.min_rect().top();
let visible_range = top..=top + content_ui.clip_rect().height();
let offset_y = scroll_y - lerp(visible_range, center_factor);
let mut spacing = ui.spacing().item_spacing.y;
// Depending on the alignment we need to add or subtract the spacing
spacing *= remap(center_factor, 0.0..=1.0, -1.0..=1.0);
state.offset.y = offset_y + spacing;
}
let inner_rect = {
let width = if inner_rect.width().is_finite() {
inner_rect.width().max(content_size.x) // Expand width to fit content
} else {
// ScrollArea is in an infinitely wide parent
content_size.x
};
let mut inner_rect =
Rect::from_min_size(inner_rect.min, vec2(width, inner_rect.height()));
// The window that egui sits in can't be expanded by egui, so we need to respect it:
let max_x = ui.input().screen_rect().right()
- current_scroll_bar_width
- ui.spacing().item_spacing.x;
inner_rect.max.x = inner_rect.max.x.at_most(max_x);
// TODO: when we support it, we should maybe auto-enable
// horizontal scrolling if this limit is reached
inner_rect
};
let outer_rect = Rect::from_min_size(
inner_rect.min,
inner_rect.size() + vec2(current_scroll_bar_width, 0.0),
);
let content_is_too_small = content_size.y > inner_rect.height();
if content_is_too_small {
// Drag contents to scroll (for touch screens mostly):
let sense = if self.scrolling_enabled {
Sense::drag()
} else {
Sense::hover()
};
let content_response = ui.interact(inner_rect, id.with("area"), sense);
let input = ui.input();
if content_response.dragged() {
state.offset.y -= input.pointer.delta().y;
state.vel = input.pointer.velocity();
} else {
let stop_speed = 20.0; // Pixels per second.
let friction_coeff = 1000.0; // Pixels per second squared.
let dt = input.unstable_dt;
let friction = friction_coeff * dt;
if friction > state.vel.length() || state.vel.length() < stop_speed {
state.vel = Vec2::ZERO;
} else {
state.vel -= friction * state.vel.normalized();
// Offset has an inverted coordinate system compared to
// the velocity, so we subtract it instead of adding it
state.offset.y -= state.vel.y * dt;
ui.ctx().request_repaint();
}
}
}
let max_offset = content_size.y - inner_rect.height();
if scrolling_enabled && ui.rect_contains_pointer(outer_rect) {
let mut frame_state = ui.ctx().frame_state();
let scroll_delta = frame_state.scroll_delta;
let scrolling_up = state.offset.y > 0.0 && scroll_delta.y > 0.0;
let scrolling_down = state.offset.y < max_offset && scroll_delta.y < 0.0;
if scrolling_up || scrolling_down {
state.offset.y -= scroll_delta.y;
// Clear scroll delta so no parent scroll will use it.
frame_state.scroll_delta = Vec2::ZERO;
}
}
let show_scroll_this_frame = content_is_too_small || always_show_scroll;
let max_scroll_bar_width = max_scroll_bar_width_with_margin(ui);
if show_scroll_this_frame && current_scroll_bar_width <= 0.0 {
// Avoid frame delay; start showing scroll bar right away:
current_scroll_bar_width = max_scroll_bar_width * ui.ctx().animate_bool(id, true);
}
if current_scroll_bar_width > 0.0 {
let animation_t = current_scroll_bar_width / max_scroll_bar_width;
// margin between contents and scroll bar
let margin = animation_t * ui.spacing().item_spacing.x;
let left = inner_rect.right() + margin;
let right = outer_rect.right();
let top = inner_rect.top();
let bottom = inner_rect.bottom();
let outer_scroll_rect = Rect::from_min_max(
pos2(left, inner_rect.top()),
pos2(right, inner_rect.bottom()),
);
let from_content =
|content_y| remap_clamp(content_y, 0.0..=content_size.y, top..=bottom);
let handle_rect = Rect::from_min_max(
pos2(left, from_content(state.offset.y)),
pos2(right, from_content(state.offset.y + inner_rect.height())),
);
let interact_id = id.with("vertical");
let sense = if self.scrolling_enabled {
Sense::click_and_drag()
} else {
Sense::hover()
};
let response = ui.interact(outer_scroll_rect, interact_id, sense);
if let Some(pointer_pos) = response.interact_pointer_pos() {
let scroll_start_offset_from_top =
state.scroll_start_offset_from_top.get_or_insert_with(|| {
if handle_rect.contains(pointer_pos) {
pointer_pos.y - handle_rect.top()
} else {
let handle_top_pos_at_bottom = bottom - handle_rect.height();
// Calculate the new handle top position, centering the handle on the mouse.
let new_handle_top_pos = (pointer_pos.y - handle_rect.height() / 2.0)
.clamp(top, handle_top_pos_at_bottom);
pointer_pos.y - new_handle_top_pos
}
});
let new_handle_top = pointer_pos.y - *scroll_start_offset_from_top;
state.offset.y = remap(new_handle_top, top..=bottom, 0.0..=content_size.y);
} else {
state.scroll_start_offset_from_top = None;
}
let unbounded_offset_y = state.offset.y;
state.offset.y = state.offset.y.max(0.0);
state.offset.y = state.offset.y.min(max_offset);
if state.offset.y != unbounded_offset_y {
state.vel = Vec2::ZERO;
}
// Avoid frame-delay by calculating a new handle rect:
let mut handle_rect = Rect::from_min_max(
pos2(left, from_content(state.offset.y)),
pos2(right, from_content(state.offset.y + inner_rect.height())),
);
let min_handle_height = ui.spacing().scroll_bar_width;
if handle_rect.size().y < min_handle_height {
handle_rect = Rect::from_center_size(
handle_rect.center(),
vec2(handle_rect.size().x, min_handle_height),
);
}
let visuals = if scrolling_enabled {
ui.style().interact(&response)
} else {
&ui.style().visuals.widgets.inactive
};
ui.painter().add(epaint::Shape::rect_filled(
outer_scroll_rect,
visuals.corner_radius,
ui.visuals().extreme_bg_color,
));
ui.painter().add(epaint::Shape::rect_filled(
handle_rect,
visuals.corner_radius,
visuals.bg_fill,
));
}
let size = vec2(
outer_rect.size().x,
outer_rect.size().y.min(content_size.y), // shrink if content is so small that we don't need scroll bars
);
ui.advance_cursor_after_rect(Rect::from_min_size(outer_rect.min, size));
if show_scroll_this_frame != state.show_scroll {
ui.ctx().request_repaint();
}
state.offset.y = state.offset.y.min(content_size.y - inner_rect.height());
state.offset.y = state.offset.y.max(0.0);
state.show_scroll = show_scroll_this_frame;
ui.memory().id_data.insert(id, state);
}
}
fn max_scroll_bar_width_with_margin(ui: &Ui) -> f32 {
ui.spacing().item_spacing.x + ui.spacing().scroll_bar_width
}
| 37.705376 | 138 | 0.577197 |
d642c48d34821c748d6c48f866b24968e88f1502
| 1,459 |
//! Utilities for scheduling work to happen after a period of time.
//!
//! This crate provides a number of utilities for working with periods of time:
//!
//! * [`Delay`]: A future that completes at a specified instant in time.
//!
//! * [`Interval`] A stream that yields at fixed time intervals.
//!
//! * [`Deadline`]: Wraps a future, requiring it to complete before a specified
//! instant in time, erroring if the future takes too long.
//!
//! These three types are backed by a [`Timer`] instance. In order for
//! [`Delay`], [`Interval`], and [`Deadline`] to function, the associated
//! [`Timer`] instance must be running on some thread.
//!
//! [`Delay`]: struct.Delay.html
//! [`Deadline`]: struct.Deadline.html
//! [`Interval`]: struct.Interval.html
//! [`Timer`]: timer/struct.Timer.html
#![doc(html_root_url = "https://docs.rs/tokio-timer/0.2.4")]
#![deny(missing_docs, warnings, missing_debug_implementations)]
extern crate tokio_executor;
#[macro_use]
extern crate futures;
pub mod clock;
pub mod timer;
mod atomic;
mod deadline;
mod delay;
mod error;
mod interval;
use std::time::{Duration, Instant};
pub use self::deadline::{Deadline, DeadlineError};
pub use self::delay::Delay;
pub use self::error::Error;
pub use self::interval::Interval;
pub use self::timer::{with_default, Timer};
/// Create a Future that completes in `duration` from now.
pub fn sleep(duration: Duration) -> Delay {
Delay::new(Instant::now() + duration)
}
| 29.18 | 79 | 0.697738 |
6422e3cfa94f29aee997493034ea0a903446ee87
| 149 |
#[derive(Clone, Debug)]
pub struct LoginData {
pub username: String,
pub passwd: String,
pub signup: bool,
pub client_ver: String,
}
| 18.625 | 27 | 0.657718 |
b96df6d0db3bffdb1b7f8efcf71033dcb455ab54
| 14,859 |
use crate::messages::{Message, MessageHeader, Ping, Version, NODE_BITCOIN_CASH, NODE_NETWORK};
use crate::network::Network;
use crate::peer::atomic_reader::AtomicReader;
use crate::util::rx::{Observable, Observer, Single, Subject};
use crate::util::{secs_since, Error, Result};
use snowflake::ProcessUniqueId;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::io;
use std::io::Write;
use std::net::{IpAddr, Shutdown, SocketAddr, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::thread;
use std::time::{Duration, UNIX_EPOCH};
/// Time to wait for the initial TCP connection
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Time to wait for handshake messages before failing to connect
const HANDSHAKE_READ_TIMEOUT: Duration = Duration::from_secs(3);
/// Event emitted when a connection is established with the peer
#[derive(Clone, Debug)]
pub struct PeerConnected {
pub peer: Arc<Peer>,
}
/// Event emitted when the connection with the peer is terminated
#[derive(Clone, Debug)]
pub struct PeerDisconnected {
pub peer: Arc<Peer>,
}
/// Event emitted when the peer receives a network message
#[derive(Clone, Debug)]
pub struct PeerMessage {
pub peer: Arc<Peer>,
pub message: Message,
}
/// Filters peers based on their version information before connecting
pub trait PeerFilter: Send + Sync {
fn connectable(&self, _: &Version) -> bool;
}
/// Filters out all peers except for Bitcoin SV full nodes
#[derive(Clone, Default, Debug)]
pub struct SVPeerFilter {
pub min_start_height: i32,
}
impl SVPeerFilter {
/// Creates a new SV filter that requires a minimum starting chain height
pub fn new(min_start_height: i32) -> Arc<SVPeerFilter> {
Arc::new(SVPeerFilter { min_start_height })
}
}
impl PeerFilter for SVPeerFilter {
fn connectable(&self, version: &Version) -> bool {
version.user_agent.contains("Bitcoin SV")
&& version.start_height >= self.min_start_height
&& version.services & (NODE_BITCOIN_CASH | NODE_NETWORK) != 0
}
}
/// Node on the network to send and receive messages
///
/// It will setup a connection, respond to pings, and store basic properties about the connection,
/// but any real logic to process messages will be handled outside. Network messages received will
/// be published to an observable on the peer's receiver thread. Messages may be sent via send()
/// from any thread. Once shutdown, the Peer may no longer be used.
pub struct Peer {
/// Unique id for this connection
pub id: ProcessUniqueId,
/// IP address
pub ip: IpAddr,
/// Port
pub port: u16,
/// Network
pub network: Network,
pub(crate) connected_event: Single<PeerConnected>,
pub(crate) disconnected_event: Single<PeerDisconnected>,
pub(crate) messages: Subject<PeerMessage>,
tcp_writer: Mutex<Option<TcpStream>>,
connected: AtomicBool,
time_delta: Mutex<i64>,
minfee: Mutex<u64>,
sendheaders: AtomicBool,
sendcmpct: AtomicBool,
version: Mutex<Option<Version>>,
/// Weak reference to self so we can pass ourselves in emitted events. This is a
/// bit ugly, but we hopefully can able to remove it once arbitrary self types goes in.
weak_self: Mutex<Option<Weak<Peer>>>,
}
impl Peer {
/// Creates a new peer and begins connecting
pub fn connect(
ip: IpAddr,
port: u16,
network: Network,
version: Version,
filter: Arc<dyn PeerFilter>,
) -> Arc<Peer> {
let peer = Arc::new(Peer {
id: ProcessUniqueId::new(),
ip,
port,
network,
connected_event: Single::new(),
disconnected_event: Single::new(),
messages: Subject::new(),
tcp_writer: Mutex::new(None),
connected: AtomicBool::new(false),
time_delta: Mutex::new(0),
minfee: Mutex::new(0),
sendheaders: AtomicBool::new(false),
sendcmpct: AtomicBool::new(false),
version: Mutex::new(None),
weak_self: Mutex::new(None),
});
*peer.weak_self.lock().unwrap() = Some(Arc::downgrade(&peer));
Peer::connect_internal(&peer, version, filter);
peer
}
/// Sends a message to the peer
pub fn send(&self, message: &Message) -> Result<()> {
if !self.connected.load(Ordering::Relaxed) {
return Err(Error::IllegalState("Not connected".to_string()));
}
let mut io_error: Option<io::Error> = None;
{
let mut tcp_writer = self.tcp_writer.lock().unwrap();
let mut tcp_writer = match tcp_writer.as_mut() {
Some(tcp_writer) => tcp_writer,
None => return Err(Error::IllegalState("No tcp stream".to_string())),
};
debug!("{:?} Write {:#?}", self, message);
if let Err(e) = message.write(&mut tcp_writer, self.network.magic()) {
io_error = Some(e);
} else {
if let Err(e) = tcp_writer.flush() {
io_error = Some(e);
}
}
}
match io_error {
Some(e) => {
self.disconnect();
Err(Error::IOError(e))
}
None => Ok(()),
}
}
/// Disconects and disables the peer
pub fn disconnect(&self) {
self.connected.swap(false, Ordering::Relaxed);
info!("{:?} Disconnecting", self);
let mut tcp_stream = self.tcp_writer.lock().unwrap();
if let Some(tcp_stream) = tcp_stream.as_mut() {
if let Err(e) = tcp_stream.shutdown(Shutdown::Both) {
warn!("{:?} Problem shutting down tcp stream: {:?}", self, e);
}
}
if let Some(peer) = self.strong_self() {
self.disconnected_event.next(&PeerDisconnected { peer });
}
}
/// Returns a Single that emits a message when connected
pub fn connected_event(&self) -> &impl Observable<PeerConnected> {
&self.connected_event
}
/// Returns a Single that emits a message when connected
pub fn disconnected_event(&self) -> &impl Observable<PeerDisconnected> {
&self.disconnected_event
}
/// Returns an Observable that emits network messages
pub fn messages(&self) -> &impl Observable<PeerMessage> {
&self.messages
}
/// Returns whether the peer is connected
pub fn connected(&self) -> bool {
self.connected.load(Ordering::Relaxed)
}
/// Returns the time difference in seconds between our time and theirs, which is valid after connecting
pub fn time_delta(&self) -> i64 {
*self.time_delta.lock().unwrap()
}
/// Returns the minimum fee this peer accepts in sats/1000bytes
pub fn minfee(&self) -> u64 {
*self.minfee.lock().unwrap()
}
/// Returns whether this peer may announce new blocks with headers instead of inv
pub fn sendheaders(&self) -> bool {
self.sendheaders.load(Ordering::Relaxed)
}
/// Returns whether compact blocks are supported
pub fn sendcmpct(&self) -> bool {
self.sendcmpct.load(Ordering::Relaxed)
}
/// Gets the version message received during the handshake
pub fn version(&self) -> Result<Version> {
match &*self.version.lock().unwrap() {
Some(ref version) => Ok(version.clone()),
None => Err(Error::IllegalState("Not connected".to_string())),
}
}
fn connect_internal(peer: &Arc<Peer>, version: Version, filter: Arc<dyn PeerFilter>) {
info!("{:?} Connecting to {:?}:{}", peer, peer.ip, peer.port);
let tpeer = peer.clone();
thread::spawn(move || {
let mut tcp_reader = match tpeer.handshake(version, filter) {
Ok(tcp_stream) => tcp_stream,
Err(e) => {
error!("Failed to complete handshake: {:?}", e);
tpeer.disconnect();
return;
}
};
// The peer is considered connected and may be written to now
info!("{:?} Connected to {:?}:{}", tpeer, tpeer.ip, tpeer.port);
tpeer.connected.store(true, Ordering::Relaxed);
tpeer.connected_event.next(&PeerConnected {
peer: tpeer.clone(),
});
let mut partial: Option<MessageHeader> = None;
let magic = tpeer.network.magic();
// Message reads over TCP must be all-or-nothing.
let mut tcp_reader = AtomicReader::new(&mut tcp_reader);
loop {
let message = match &partial {
Some(header) => Message::read_partial(&mut tcp_reader, header),
None => Message::read(&mut tcp_reader, magic),
};
// Always check the connected flag right after the blocking read so we exit right away,
// and also so that we don't mistake errors with the stream shutting down
if !tpeer.connected.load(Ordering::Relaxed) {
return;
}
match message {
Ok(message) => {
if let Message::Partial(header) = message {
partial = Some(header);
} else {
debug!("{:?} Read {:#?}", tpeer, message);
partial = None;
if let Err(e) = tpeer.handle_message(&message) {
error!("{:?} Error handling message: {:?}", tpeer, e);
tpeer.disconnect();
return;
}
tpeer.messages.next(&PeerMessage {
peer: tpeer.clone(),
message,
});
}
}
Err(e) => {
// If timeout, try again later. Otherwise, shutdown
if let Error::IOError(ref e) = e {
// Depending on platform, either TimedOut or WouldBlock may be returned to indicate a non-error timeout
if e.kind() == io::ErrorKind::TimedOut
|| e.kind() == io::ErrorKind::WouldBlock
{
continue;
}
}
error!("{:?} Error reading message {:?}", tpeer, e);
tpeer.disconnect();
return;
}
}
}
});
}
fn handshake(self: &Peer, version: Version, filter: Arc<dyn PeerFilter>) -> Result<TcpStream> {
// Connect over TCP
let tcp_addr = SocketAddr::new(self.ip, self.port);
let mut tcp_stream = TcpStream::connect_timeout(&tcp_addr, CONNECT_TIMEOUT)?;
tcp_stream.set_nodelay(true)?; // Disable buffering
tcp_stream.set_read_timeout(Some(HANDSHAKE_READ_TIMEOUT))?;
tcp_stream.set_nonblocking(false)?;
// Write our version
let our_version = Message::Version(version);
debug!("{:?} Write {:#?}", self, our_version);
let magic = self.network.magic();
our_version.write(&mut tcp_stream, magic)?;
// Read their version
let msg = Message::read(&mut tcp_stream, magic)?;
debug!("{:?} Read {:#?}", self, msg);
let their_version = match msg {
Message::Version(version) => version,
_ => return Err(Error::BadData("Unexpected command".to_string())),
};
if !filter.connectable(&their_version) {
return Err(Error::IllegalState("Peer filtered out".to_string()));
}
let now = secs_since(UNIX_EPOCH) as i64;
*self.time_delta.lock().unwrap() = now - their_version.timestamp;
*self.version.lock().unwrap() = Some(their_version);
// Read their verack
let their_verack = Message::read(&mut tcp_stream, magic)?;
debug!("{:?} Read {:#?}", self, their_verack);
match their_verack {
Message::Verack => {}
_ => return Err(Error::BadData("Unexpected command".to_string())),
};
// Write our verack
debug!("{:?} Write {:#?}", self, Message::Verack);
Message::Verack.write(&mut tcp_stream, magic)?;
// Write a ping message because this seems to help with connection weirdness
// https://bitcoin.stackexchange.com/questions/49487/getaddr-not-returning-connected-node-addresses
let ping = Message::Ping(Ping {
nonce: secs_since(UNIX_EPOCH) as u64,
});
debug!("{:?} Write {:#?}", self, ping);
ping.write(&mut tcp_stream, magic)?;
// After handshake, clone TCP stream and save the write version
*self.tcp_writer.lock().unwrap() = Some(tcp_stream.try_clone()?);
// We don't need a timeout for the read. The peer will shutdown just fine.
// The read timeout doesn't work reliably across platforms anyway.
tcp_stream.set_read_timeout(None)?;
Ok(tcp_stream)
}
fn handle_message(&self, message: &Message) -> Result<()> {
// A subset of messages are handled directly by the peer
match message {
Message::FeeFilter(feefilter) => {
*self.minfee.lock().unwrap() = feefilter.minfee;
}
Message::Ping(ping) => {
let pong = Message::Pong(ping.clone());
self.send(&pong)?;
}
Message::SendHeaders => {
self.sendheaders.store(true, Ordering::Relaxed);
}
Message::SendCmpct(sendcmpct) => {
let enable = sendcmpct.use_cmpctblock();
self.sendcmpct.store(enable, Ordering::Relaxed);
}
_ => {}
}
Ok(())
}
fn strong_self(&self) -> Option<Arc<Peer>> {
match &*self.weak_self.lock().unwrap() {
Some(ref weak_peer) => weak_peer.upgrade(),
None => None,
}
}
}
impl PartialEq for Peer {
fn eq(&self, other: &Peer) -> bool {
self.id == other.id
}
}
impl Eq for Peer {}
impl Hash for Peer {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state)
}
}
impl fmt::Debug for Peer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&format!("[Peer {}]", self.id))
}
}
impl Drop for Peer {
fn drop(&mut self) {
self.disconnect();
}
}
| 34.475638 | 131 | 0.559122 |
481e44142014ee9d924ea316ae7f118532475e08
| 1,412 |
// Copyright 2018 The xi-editor 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.
//! Widget for forwarding key events to a listener.
use druid_shell::keyboard::{KeyCode, KeyEvent};
use crate::widget::Widget;
use crate::{HandlerCtx, Id, Ui};
pub struct KeyListener;
impl KeyListener {
pub fn new() -> Self {
KeyListener
}
pub fn ui(self, child: Id, ctx: &mut Ui) -> Id {
ctx.add(self, &[child])
}
}
impl Widget for KeyListener {
fn key_down(&mut self, event: &KeyEvent, ctx: &mut HandlerCtx) -> bool {
// TODO: maybe some configuration of which keys are handled. Right
// now we handle everything except a few keys.
match event.key_code {
KeyCode::F4 | KeyCode::F10 | KeyCode::Menu => false,
_other => {
ctx.send_event(event.clone());
true
}
}
}
}
| 30.042553 | 76 | 0.646601 |
bf11d6e54045b59c7ac1c2047c3bc7fe8f18bd88
| 4,057 |
//! `DimMap` and layout lowering.
use ir;
use itertools::Itertools;
use search_space::choices::dim_kind;
use search_space::operand;
use search_space::{Action, DimKind, DomainStore, InstFlag, Order};
/// Lowers a layout
pub fn lower_layout(
fun: &mut ir::Function,
mem: ir::mem::InternalId,
st_dims: Vec<ir::DimId>,
ld_dims: Vec<ir::DimId>,
domain: &DomainStore,
) -> Result<Vec<Action>, ()> {
debug!("lower_layout({:?}) triggered", mem);
let mut actions = Vec::new();
// TODO(automate): vectorization disabled -> express as an additional constraint
// We need to manually set every dimension except the innermost as non-vectorizable
// because temporary loads and stores do not restrict vectorization automatically
// since they are not aware of the access pattern. The constraint propagation is not
// aware we just specified the access pattern and so doesn't re-run the constraints.
for (&st_dim, &ld_dim) in st_dims.iter().rev().zip_eq(ld_dims.iter().rev()).skip(1) {
let not_vec = !DimKind::VECTOR;
actions.extend(dim_kind::restrict_delayed(st_dim, fun, domain, not_vec)?);
actions.extend(dim_kind::restrict_delayed(ld_dim, fun, domain, not_vec)?);
}
fun.lower_layout(mem, st_dims, ld_dims);
for &inst_id in fun.mem_block(mem.into()).uses() {
let inst = fun.inst(inst_id);
actions.extend(operand::inst_invariants(fun, inst));
}
Ok(actions)
}
/// Lowers a `DimMap`.
fn lower_dim_map(
fun: &mut ir::Function,
inst: ir::InstId,
operand: usize,
new_objs: &mut ir::NewObjs,
) -> Result<Vec<Action>, ()> {
debug!("lower_dim_map({:?}, {}) triggered", inst, operand);
let lowered_dim_map = fun.lower_dim_map(inst, operand)?;
let mut actions = Vec::new();
// Order the store and load loop nests.
for (src, dst) in lowered_dim_map.mem_dimensions() {
actions.push(Action::Order(
src.into(),
dst.into(),
Order::BEFORE | Order::MERGED,
));
}
// FIXME: allow global memory
actions.push(Action::InstFlag(
lowered_dim_map.store,
InstFlag::MEM_SHARED,
));
actions.push(Action::InstFlag(lowered_dim_map.load, InstFlag::MEM_SHARED));
//actions.push(Action::InstFlag(st, InstFlag::MEM_COHERENT));
//actions.push(Action::InstFlag(ld, InstFlag::MEM_COHERENT));
let store = lowered_dim_map.store;
actions.push(Action::Order(
store.into(),
lowered_dim_map.load.into(),
Order::BEFORE,
));
let operand = fun.inst(inst).operands()[operand];
// The invariants for the load and store instructions, including the ones implied by the
// mapping between dimensions, are enforced by `search_space::process_lowering`.
actions.extend(operand::invariants(fun, operand, inst.into()));
lowered_dim_map.register_new_objs(fun, new_objs);
debug!("lower_dim_map actions: {:?}", actions);
Ok(actions)
}
/// Trigger to call when two dimensions are not mapped.
pub fn dim_not_mapped(
lhs: ir::DimId,
rhs: ir::DimId,
fun: &mut ir::Function,
) -> Result<(ir::NewObjs, Vec<Action>), ()> {
debug!("dim_not_mapped({:?}, {:?}) triggered", lhs, rhs);
let to_lower = fun
.insts()
.flat_map(|inst| {
inst.dim_maps_to_lower(lhs, rhs)
.into_iter()
.map(move |op_id| (inst.id(), op_id))
}).collect_vec();
let mut new_objs = ir::NewObjs::default();
let mut actions = Vec::new();
for (inst, operand) in to_lower {
actions.extend(lower_dim_map(fun, inst, operand, &mut new_objs)?);
}
Ok((new_objs, actions))
}
/// Trigger to call when two dimensions are not merged.
pub fn dim_not_merged(
lhs: ir::DimId,
rhs: ir::DimId,
fun: &mut ir::Function,
) -> Result<(ir::NewObjs, Vec<Action>), ()> {
debug!("dim_not_merged({:?}, {:?}) triggered", lhs, rhs);
fun.dim_not_merged(lhs, rhs);
// TODO(cc_perf): avoid creating a 'NewObjs' object.
Ok(Default::default())
}
| 36.881818 | 92 | 0.640868 |
4834c6ebc86ff27ed8f84293ea01f861c3e1b773
| 7,481 |
// Copyright 2018-2020 argmin developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use crate::core::math::ArgminSub;
use ndarray::{Array1, Array2};
use num_complex::Complex;
macro_rules! make_sub {
($t:ty) => {
impl ArgminSub<$t, Array1<$t>> for Array1<$t> {
#[inline]
fn sub(&self, other: &$t) -> Array1<$t> {
self - *other
}
}
impl ArgminSub<Array1<$t>, Array1<$t>> for $t {
#[inline]
fn sub(&self, other: &Array1<$t>) -> Array1<$t> {
*self - other
}
}
impl ArgminSub<Array1<$t>, Array1<$t>> for Array1<$t> {
#[inline]
fn sub(&self, other: &Array1<$t>) -> Array1<$t> {
self - other
}
}
impl ArgminSub<Array2<$t>, Array2<$t>> for Array2<$t> {
#[inline]
fn sub(&self, other: &Array2<$t>) -> Array2<$t> {
self - other
}
}
impl ArgminSub<$t, Array2<$t>> for Array2<$t> {
#[inline]
fn sub(&self, other: &$t) -> Array2<$t> {
self - *other
}
}
};
}
make_sub!(i8);
make_sub!(i16);
make_sub!(i32);
make_sub!(i64);
make_sub!(u8);
make_sub!(u16);
make_sub!(u32);
make_sub!(u64);
make_sub!(f32);
make_sub!(f64);
make_sub!(Complex<f32>);
make_sub!(Complex<f64>);
#[cfg(test)]
mod tests {
use super::*;
use ndarray::array;
use paste::item;
macro_rules! make_test {
($t:ty) => {
item! {
#[test]
fn [<test_sub_vec_scalar_ $t>]() {
let a = array![36 as $t, 39 as $t, 43 as $t];
let b = 1 as $t;
let target = array![35 as $t, 38 as $t, 42 as $t];
let res = <Array1<$t> as ArgminSub<$t, Array1<$t>>>::sub(&a, &b);
for i in 0..3 {
assert!(((target[i] - res[i]) as f64).abs() < std::f64::EPSILON);
}
}
}
item! {
#[test]
fn [<test_sub_scalar_vec_ $t>]() {
let a = array![1 as $t, 4 as $t, 8 as $t];
let b = 34 as $t;
let target = array![33 as $t, 30 as $t, 26 as $t];
let res = <$t as ArgminSub<Array1<$t>, Array1<$t>>>::sub(&b, &a);
for i in 0..3 {
assert!(((target[i] - res[i]) as f64).abs() < std::f64::EPSILON);
}
}
}
item! {
#[test]
fn [<test_sub_vec_vec_ $t>]() {
let a = array![41 as $t, 38 as $t, 34 as $t];
let b = array![1 as $t, 4 as $t, 8 as $t];
let target = array![40 as $t, 34 as $t, 26 as $t];
let res = <Array1<$t> as ArgminSub<Array1<$t>, Array1<$t>>>::sub(&a, &b);
for i in 0..3 {
assert!(((target[i] - res[i]) as f64).abs() < std::f64::EPSILON);
}
}
}
item! {
#[test]
#[should_panic]
fn [<test_sub_vec_vec_panic_ $t>]() {
let a = array![41 as $t, 38 as $t, 34 as $t];
let b = array![1 as $t, 4 as $t];
<Array1<$t> as ArgminSub<Array1<$t>, Array1<$t>>>::sub(&a, &b);
}
}
item! {
#[test]
#[should_panic]
fn [<test_sub_vec_vec_panic_2_ $t>]() {
let a = array![];
let b = array![41 as $t, 38 as $t, 34 as $t];
<Array1<$t> as ArgminSub<Array1<$t>, Array1<$t>>>::sub(&a, &b);
}
}
item! {
#[test]
#[should_panic]
fn [<test_sub_vec_vec_panic_3_ $t>]() {
let a = array![41 as $t, 38 as $t, 34 as $t];
let b = array![];
<Array1<$t> as ArgminSub<Array1<$t>, Array1<$t>>>::sub(&a, &b);
}
}
item! {
#[test]
fn [<test_sub_mat_mat_ $t>]() {
let a = array![
[43 as $t, 46 as $t, 50 as $t],
[44 as $t, 47 as $t, 51 as $t]
];
let b = array![
[1 as $t, 4 as $t, 8 as $t],
[2 as $t, 5 as $t, 9 as $t]
];
let target = array![
[42 as $t, 42 as $t, 42 as $t],
[42 as $t, 42 as $t, 42 as $t]
];
let res = <Array2<$t> as ArgminSub<Array2<$t>, Array2<$t>>>::sub(&a, &b);
for i in 0..3 {
for j in 0..2 {
assert!(((target[(j, i)] - res[(j, i)]) as f64).abs() < std::f64::EPSILON);
}
}
}
}
item! {
#[test]
fn [<test_sub_mat_scalar_ $t>]() {
let a = array![
[43 as $t, 46 as $t, 50 as $t],
[44 as $t, 47 as $t, 51 as $t]
];
let b = 2 as $t;
let target = array![
[41 as $t, 44 as $t, 48 as $t],
[42 as $t, 45 as $t, 49 as $t]
];
let res = <Array2<$t> as ArgminSub<$t, Array2<$t>>>::sub(&a, &b);
for i in 0..3 {
for j in 0..2 {
assert!(((target[(j, i)] - res[(j, i)]) as f64).abs() < std::f64::EPSILON);
}
}
}
}
item! {
#[test]
#[should_panic]
fn [<test_sub_mat_mat_panic_2_ $t>]() {
let a = array![
[41 as $t, 38 as $t],
];
let b = array![
[1 as $t, 4 as $t, 8 as $t],
[2 as $t, 5 as $t, 9 as $t]
];
<Array2<$t> as ArgminSub<Array2<$t>, Array2<$t>>>::sub(&a, &b);
}
}
item! {
#[test]
#[should_panic]
fn [<test_sub_mat_mat_panic_3_ $t>]() {
let a = array![
[1 as $t, 4 as $t, 8 as $t],
[2 as $t, 5 as $t, 9 as $t]
];
let b = array![[]];
<Array2<$t> as ArgminSub<Array2<$t>, Array2<$t>>>::sub(&a, &b);
}
}
};
}
make_test!(i8);
make_test!(u8);
make_test!(i16);
make_test!(u16);
make_test!(i32);
make_test!(u32);
make_test!(i64);
make_test!(u64);
make_test!(f32);
make_test!(f64);
}
| 32.955947 | 99 | 0.35677 |
f76472cc959db144084446b954bef16962d7279f
| 1,699 |
use super::super::{
monitor::Monitor
};
use std::{
time,
thread,
os::unix::net::{
UnixListener
},
io::{
self,
Read,
BufReader,
Write
},
sync::{
Arc,
Mutex
},
path::Path,
fs
};
use serde::{Serialize, Deserialize};
use bincode;
pub const SOCKET_ADDR: &str = "/tmp/autoplank.sock";
#[derive(Debug, Serialize, Deserialize)]
pub enum SocketMessage {
Ok(Vec<Monitor>),
Err(String),
RefreshMonitors
}
pub fn socket(m: Arc<Mutex<Vec<Monitor>>>) -> Result<(), io::Error> {
if Path::new(SOCKET_ADDR).exists() {
fs::remove_file(SOCKET_ADDR)?;
}
let listener = UnixListener::bind(SOCKET_ADDR)?;
for stream in listener.incoming() {
let mut s = stream?;
thread::sleep(time::Duration::from_millis(10));
let mut buf = BufReader::new(&s);
let mut data = [0u8; 32];
let len = buf.read(&mut data)?;
let msg: SocketMessage = match bincode::deserialize(&data[0..len]) {
Ok(m) => m,
Err(e) => {
eprintln!("{}", e);
continue;
}
};
match msg {
SocketMessage::RefreshMonitors => {
println!("=> Scanning for monitors...");
let monitors = padlock::mutex_lock(&m, |lock| {
*lock = Monitor::get_all();
lock.clone()
});
let data = bincode::serialize(&SocketMessage::Ok(monitors)).unwrap();
s.write(&data[..])?;
},
_ => eprintln!("Received invalid data")
};
}
Ok(())
}
| 19.755814 | 85 | 0.486168 |
fb99dffeddd691a9ba24cffa9a8c8150684e8cfc
| 1,411 |
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let base = super::linux_base::opts();
Ok(Target {
llvm_target: "armv4t-unknown-linux-gnueabi".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
features: "+soft-float,+strict-align".to_string(),
// Atomic operations provided by compiler-builtins
max_atomic_width: Some(32),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
}
| 39.194444 | 83 | 0.653437 |
e866caa29f99d7eec1696927de82893d05972a1d
| 13,112 |
#[doc = "Reader of register OSPEEDR"]
pub type R = crate::R<u32, super::OSPEEDR>;
#[doc = "Writer for register OSPEEDR"]
pub type W = crate::W<u32, super::OSPEEDR>;
#[doc = "Register OSPEEDR `reset()`'s with value 0"]
impl crate::ResetValue for super::OSPEEDR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `OSPEEDR15`"]
pub type OSPEEDR15_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR15`"]
pub struct OSPEEDR15_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR15_W<'a> {
#[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 & !(0x03 << 30)) | (((value as u32) & 0x03) << 30);
self.w
}
}
#[doc = "Reader of field `OSPEEDR14`"]
pub type OSPEEDR14_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR14`"]
pub struct OSPEEDR14_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR14_W<'a> {
#[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 & !(0x03 << 28)) | (((value as u32) & 0x03) << 28);
self.w
}
}
#[doc = "Reader of field `OSPEEDR13`"]
pub type OSPEEDR13_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR13`"]
pub struct OSPEEDR13_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR13_W<'a> {
#[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 & !(0x03 << 26)) | (((value as u32) & 0x03) << 26);
self.w
}
}
#[doc = "Reader of field `OSPEEDR12`"]
pub type OSPEEDR12_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR12`"]
pub struct OSPEEDR12_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR12_W<'a> {
#[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 & !(0x03 << 24)) | (((value as u32) & 0x03) << 24);
self.w
}
}
#[doc = "Reader of field `OSPEEDR11`"]
pub type OSPEEDR11_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR11`"]
pub struct OSPEEDR11_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR11_W<'a> {
#[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 & !(0x03 << 22)) | (((value as u32) & 0x03) << 22);
self.w
}
}
#[doc = "Reader of field `OSPEEDR10`"]
pub type OSPEEDR10_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR10`"]
pub struct OSPEEDR10_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR10_W<'a> {
#[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 & !(0x03 << 20)) | (((value as u32) & 0x03) << 20);
self.w
}
}
#[doc = "Reader of field `OSPEEDR9`"]
pub type OSPEEDR9_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR9`"]
pub struct OSPEEDR9_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR9_W<'a> {
#[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 & !(0x03 << 18)) | (((value as u32) & 0x03) << 18);
self.w
}
}
#[doc = "Reader of field `OSPEEDR8`"]
pub type OSPEEDR8_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR8`"]
pub struct OSPEEDR8_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR8_W<'a> {
#[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 & !(0x03 << 16)) | (((value as u32) & 0x03) << 16);
self.w
}
}
#[doc = "Reader of field `OSPEEDR7`"]
pub type OSPEEDR7_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR7`"]
pub struct OSPEEDR7_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR7_W<'a> {
#[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 & !(0x03 << 14)) | (((value as u32) & 0x03) << 14);
self.w
}
}
#[doc = "Reader of field `OSPEEDR6`"]
pub type OSPEEDR6_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR6`"]
pub struct OSPEEDR6_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR6_W<'a> {
#[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 & !(0x03 << 12)) | (((value as u32) & 0x03) << 12);
self.w
}
}
#[doc = "Reader of field `OSPEEDR5`"]
pub type OSPEEDR5_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR5`"]
pub struct OSPEEDR5_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR5_W<'a> {
#[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 & !(0x03 << 10)) | (((value as u32) & 0x03) << 10);
self.w
}
}
#[doc = "Reader of field `OSPEEDR4`"]
pub type OSPEEDR4_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR4`"]
pub struct OSPEEDR4_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR4_W<'a> {
#[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 & !(0x03 << 8)) | (((value as u32) & 0x03) << 8);
self.w
}
}
#[doc = "Reader of field `OSPEEDR3`"]
pub type OSPEEDR3_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR3`"]
pub struct OSPEEDR3_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR3_W<'a> {
#[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 & !(0x03 << 6)) | (((value as u32) & 0x03) << 6);
self.w
}
}
#[doc = "Reader of field `OSPEEDR2`"]
pub type OSPEEDR2_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR2`"]
pub struct OSPEEDR2_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR2_W<'a> {
#[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 & !(0x03 << 4)) | (((value as u32) & 0x03) << 4);
self.w
}
}
#[doc = "Reader of field `OSPEEDR1`"]
pub type OSPEEDR1_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR1`"]
pub struct OSPEEDR1_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR1_W<'a> {
#[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 & !(0x03 << 2)) | (((value as u32) & 0x03) << 2);
self.w
}
}
#[doc = "Reader of field `OSPEEDR0`"]
pub type OSPEEDR0_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OSPEEDR0`"]
pub struct OSPEEDR0_W<'a> {
w: &'a mut W,
}
impl<'a> OSPEEDR0_W<'a> {
#[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 & !0x03) | ((value as u32) & 0x03);
self.w
}
}
impl R {
#[doc = "Bits 30:31 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr15(&self) -> OSPEEDR15_R {
OSPEEDR15_R::new(((self.bits >> 30) & 0x03) as u8)
}
#[doc = "Bits 28:29 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr14(&self) -> OSPEEDR14_R {
OSPEEDR14_R::new(((self.bits >> 28) & 0x03) as u8)
}
#[doc = "Bits 26:27 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr13(&self) -> OSPEEDR13_R {
OSPEEDR13_R::new(((self.bits >> 26) & 0x03) as u8)
}
#[doc = "Bits 24:25 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr12(&self) -> OSPEEDR12_R {
OSPEEDR12_R::new(((self.bits >> 24) & 0x03) as u8)
}
#[doc = "Bits 22:23 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr11(&self) -> OSPEEDR11_R {
OSPEEDR11_R::new(((self.bits >> 22) & 0x03) as u8)
}
#[doc = "Bits 20:21 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr10(&self) -> OSPEEDR10_R {
OSPEEDR10_R::new(((self.bits >> 20) & 0x03) as u8)
}
#[doc = "Bits 18:19 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr9(&self) -> OSPEEDR9_R {
OSPEEDR9_R::new(((self.bits >> 18) & 0x03) as u8)
}
#[doc = "Bits 16:17 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr8(&self) -> OSPEEDR8_R {
OSPEEDR8_R::new(((self.bits >> 16) & 0x03) as u8)
}
#[doc = "Bits 14:15 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr7(&self) -> OSPEEDR7_R {
OSPEEDR7_R::new(((self.bits >> 14) & 0x03) as u8)
}
#[doc = "Bits 12:13 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr6(&self) -> OSPEEDR6_R {
OSPEEDR6_R::new(((self.bits >> 12) & 0x03) as u8)
}
#[doc = "Bits 10:11 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr5(&self) -> OSPEEDR5_R {
OSPEEDR5_R::new(((self.bits >> 10) & 0x03) as u8)
}
#[doc = "Bits 8:9 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr4(&self) -> OSPEEDR4_R {
OSPEEDR4_R::new(((self.bits >> 8) & 0x03) as u8)
}
#[doc = "Bits 6:7 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr3(&self) -> OSPEEDR3_R {
OSPEEDR3_R::new(((self.bits >> 6) & 0x03) as u8)
}
#[doc = "Bits 4:5 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr2(&self) -> OSPEEDR2_R {
OSPEEDR2_R::new(((self.bits >> 4) & 0x03) as u8)
}
#[doc = "Bits 2:3 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr1(&self) -> OSPEEDR1_R {
OSPEEDR1_R::new(((self.bits >> 2) & 0x03) as u8)
}
#[doc = "Bits 0:1 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr0(&self) -> OSPEEDR0_R {
OSPEEDR0_R::new((self.bits & 0x03) as u8)
}
}
impl W {
#[doc = "Bits 30:31 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr15(&mut self) -> OSPEEDR15_W {
OSPEEDR15_W { w: self }
}
#[doc = "Bits 28:29 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr14(&mut self) -> OSPEEDR14_W {
OSPEEDR14_W { w: self }
}
#[doc = "Bits 26:27 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr13(&mut self) -> OSPEEDR13_W {
OSPEEDR13_W { w: self }
}
#[doc = "Bits 24:25 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr12(&mut self) -> OSPEEDR12_W {
OSPEEDR12_W { w: self }
}
#[doc = "Bits 22:23 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr11(&mut self) -> OSPEEDR11_W {
OSPEEDR11_W { w: self }
}
#[doc = "Bits 20:21 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr10(&mut self) -> OSPEEDR10_W {
OSPEEDR10_W { w: self }
}
#[doc = "Bits 18:19 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr9(&mut self) -> OSPEEDR9_W {
OSPEEDR9_W { w: self }
}
#[doc = "Bits 16:17 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr8(&mut self) -> OSPEEDR8_W {
OSPEEDR8_W { w: self }
}
#[doc = "Bits 14:15 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr7(&mut self) -> OSPEEDR7_W {
OSPEEDR7_W { w: self }
}
#[doc = "Bits 12:13 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr6(&mut self) -> OSPEEDR6_W {
OSPEEDR6_W { w: self }
}
#[doc = "Bits 10:11 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr5(&mut self) -> OSPEEDR5_W {
OSPEEDR5_W { w: self }
}
#[doc = "Bits 8:9 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr4(&mut self) -> OSPEEDR4_W {
OSPEEDR4_W { w: self }
}
#[doc = "Bits 6:7 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr3(&mut self) -> OSPEEDR3_W {
OSPEEDR3_W { w: self }
}
#[doc = "Bits 4:5 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr2(&mut self) -> OSPEEDR2_W {
OSPEEDR2_W { w: self }
}
#[doc = "Bits 2:3 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr1(&mut self) -> OSPEEDR1_W {
OSPEEDR1_W { w: self }
}
#[doc = "Bits 0:1 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeedr0(&mut self) -> OSPEEDR0_W {
OSPEEDR0_W { w: self }
}
}
| 32.698254 | 86 | 0.554454 |
dd00b8002501e0a4590d8919379ce91d08772f78
| 9,921 |
//! Reads psf (console) fonts. Exposes very simple interface for displaying
//! the glyphs.
//!
//! Exposing of the glyph data is simple and easy to use:
//! ```
//! use psf::Font;
//!
//! let the_font = Font::new("<path>");
//! if let Ok(font) = the_font {
//! let c = font.get_char('X');
//! if let Some(c) = c {
//! println!("{:-<1$}", "", c.width() + 2);
//! for h in 0..c.height() {
//! print!("|");
//! for w in 0..c.width() {
//! let what = if c.get(w, h).unwrap() { "X" } else { " " };
//! print!("{}", what);
//! }
//! println!("|");
//! }
//! println!("{:-<1$}", "", c.width() + 2);
//! }
//! }
//! ```
/// Stores information about specific loaded font, including number of
/// available characters, and each character width and height.
pub struct Font {
raw_data: Vec<u8>,
font_data_offset: usize,
count: usize,
width: usize,
height: usize,
byte_width: usize,
}
/// Store information about specific glyph.
// #[derive(Debug)]
pub struct Glyph<'a> {
d: GlyphData<'a>,
h: usize,
w: usize,
bw: usize,
}
enum GlyphData<'a> {
ByCopy(Vec<u8>),
ByRef(&'a [u8]),
}
impl<'a> Glyph<'a> {
/// Returns if specific point is set (`true`) or not (`false`).
///
/// `x` specifies the point from `0..self.width`
///
/// `y` specifies the point from `0..self.height`
pub fn get(&self, x: usize, y: usize) -> Option<bool> {
if x > self.w || y > self.h {
None
} else {
let bit = match &self.d {
GlyphData::ByCopy(d) => d[y * self.bw + x / 8],
GlyphData::ByRef(d) => d[y * self.bw + x / 8],
};
// let bit = self.d[y * self.bw + x / 8];
Some((bit >> (7 - (x % 8)) & 0b1) != 0)
}
}
/// Returns width of the glyph
pub fn width(&self) -> usize {
self.w
}
/// Returns height of the glyph
pub fn height(&self) -> usize {
self.h
}
}
/// Simple error type.
#[derive(Debug, Copy, Clone)]
pub enum Error {
/// Unspecified error for now
Unknown,
/// File doesn't exists
FileNotFound,
/// Failure to open and/or read the file itself
FileIo,
/// Invalid or unsupported file format
InvalidFontFormat,
}
impl std::convert::From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
match e {
_ => Error::FileIo,
}
}
}
impl Font {
/// Creates a new font for specific path.
pub fn new<P: AsRef<std::path::Path>>(path: P) -> Result<Font, Error> {
Font::_new(path.as_ref())
}
fn _new(path: &std::path::Path) -> Result<Font, Error> {
if !path.exists() && !path.is_file() {
return Err(Error::FileNotFound);
}
let filename = path.file_name();
if filename.is_none() {
return Err(Error::Unknown);
}
#[allow(unused_mut)]
let mut data = std::fs::read(path)?;
#[cfg(feature = "unzip")]
{
use std::io::Read;
if data[0] == 0x1f && data[1] == 0x8b {
// gunzip first
let mut gzd = flate2::read::GzDecoder::new(&data[..]);
let mut decoded_data = Vec::new();
gzd.read_to_end(&mut decoded_data)?;
data = decoded_data;
}
}
Font::parse_font_data(data)
}
/// Returns height of every glyph
pub fn height(&self) -> usize {
self.height
}
/// Returns width of every glyph
pub fn width(&self) -> usize {
self.width
}
/// Returns number of available characters in the font
pub fn size(&self) -> usize {
self.count
}
/// Returns [`Glyph`] data for specific character. If it's not present in the
/// font, [`None`] is returned.
pub fn get_char(&self, c: char) -> Option<Glyph> {
let cn = c as usize;
if cn > self.count {
return None;
}
let char_byte_length = self.height * self.byte_width;
let offset = self.font_data_offset + cn * char_byte_length;
Some(Glyph {
d: GlyphData::ByRef(&self.raw_data[offset..offset + char_byte_length]),
h: self.height,
w: self.width,
bw: self.byte_width,
})
}
/// Returns [`Glyph`] data for specific character. If it's not present in the
/// font, [`None`] is returned. Contains copy of the data, so can be used even when
/// [`Font`] is destroyed.
pub fn get_char_owned<'b>(&self, c: char) -> Option<Glyph<'b>> {
let cn = c as usize;
if cn > self.count {
return None;
}
let char_byte_length = self.height * self.byte_width;
let offset = self.font_data_offset + cn * char_byte_length;
Some(Glyph {
d: GlyphData::ByCopy(self.raw_data[offset..offset + char_byte_length].to_vec()),
h: self.height,
w: self.width,
bw: self.byte_width,
})
}
/// Prints specified character to standard output using [`print!`]
pub fn print_char(&self, c: char) {
let c = self.get_char(c).unwrap();
println!("{:-<1$}", "", c.width() + 2);
for h in 0..c.height() {
print!("|");
for w in 0..c.width() {
let what = if c.get(w, h).unwrap() { "X" } else { " " };
print!("{}", what);
}
println!("|");
}
println!("{:-<1$}", "", c.width() + 2);
}
fn parse_font_data(raw_data: Vec<u8>) -> Result<Font, Error> {
if raw_data.is_empty() {
return Err(Error::InvalidFontFormat);
}
let height;
let width;
let byte_width;
let count: u32;
let mut data = raw_data.iter();
let mode = match *data.next().unwrap() {
0x36 => 1,
0x72 => 2,
_ => return Err(Error::InvalidFontFormat),
};
if mode == 1 {
if raw_data.len() < 4 {
return Err(Error::InvalidFontFormat);
}
if *data.next().unwrap() != 0x04 {
return Err(Error::InvalidFontFormat);
}
count = match *data.next().unwrap() {
0 => 256,
1 => 512,
2 => 256,
3 => 512,
_ => return Err(Error::InvalidFontFormat),
};
height = *data.next().unwrap();
width = 8;
byte_width = 1;
} else {
if raw_data.len() < 32 {
return Err(Error::InvalidFontFormat);
}
if *data.next().unwrap() != 0xb5
|| *data.next().unwrap() != 0x4a
|| *data.next().unwrap() != 0x86
{
return Err(Error::InvalidFontFormat);
}
let version = get_data(&mut data, 4);
if version != [0, 0, 0, 0] {
return Err(Error::InvalidFontFormat);
}
let offset = as_le_u32(&mut data);
if offset != 0x20 {
return Err(Error::InvalidFontFormat);
}
let _flags = get_data(&mut data, 4);
count = *data.next().unwrap() as u32 + *data.next().unwrap() as u32 * 256;
let no_chars = as_le_u16(&mut data);
if no_chars as u32 > 64 * 1024 {
return Err(Error::InvalidFontFormat);
}
let _sizeof_char = as_le_u32(&mut data);
height = as_le_u32(&mut data) as u8;
width = as_le_u32(&mut data) as u8;
byte_width = (width + 7) / 8;
assert!(width <= byte_width * 8);
}
let font_data_offset = raw_data.len() - data.as_slice().len();
if mode == 1 {
assert_eq!(font_data_offset, 4);
} else {
assert_eq!(font_data_offset, 32);
}
Ok(Font {
raw_data,
font_data_offset,
count: count as usize,
width: width as usize,
height: height as usize,
byte_width: byte_width as usize,
})
}
}
fn as_le_u32(data: &mut std::slice::Iter<u8>) -> u32 {
(*data.next().unwrap() as u32)
| (*data.next().unwrap() as u32) << 8
| (*data.next().unwrap() as u32) << 16
| (*data.next().unwrap() as u32) << 24
}
fn as_le_u16(data: &mut std::slice::Iter<u8>) -> u16 {
(*data.next().unwrap() as u16) | (*data.next().unwrap() as u16) << 8
}
fn get_data(data: &mut std::slice::Iter<u8>, count: usize) -> Vec<u8> {
let mut v = Vec::with_capacity(count);
for _ in 0..count {
v.push(*data.next().unwrap());
}
v
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_path() {
assert!(Font::new("blah").is_err());
assert!(Font::new(std::path::Path::new("foo")).is_err());
}
#[test]
fn data_convert_u32() {
let data: Vec<u8> = vec![0x22u8, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99];
let mut it = data.iter();
assert_eq!(0x55443322, as_le_u32(&mut it));
assert_eq!(0x99887766, as_le_u32(&mut it));
}
#[test]
fn data_convert_u16() {
let data: Vec<u8> = vec![0x22u8, 0x33, 0x44, 0x55];
let mut it = data.iter();
assert_eq!(0x3322, as_le_u16(&mut it));
assert_eq!(0x5544, as_le_u16(&mut it));
}
#[test]
fn test_get_data() {
let data: Vec<u8> = vec![0x22u8, 0x33, 0x44, 0x55, 0x66, 0x77];
let mut it = data.iter();
assert_eq!(vec![0x22u8, 0x33, 0x44], get_data(&mut it, 3));
assert_eq!(vec![0x55u8], get_data(&mut it, 1));
assert_eq!(vec![0x66u8, 0x77], get_data(&mut it, 2));
}
}
| 29.614925 | 92 | 0.494003 |
f5304e106ac980bb66035571e0be0c04f9ef924c
| 127 |
pub mod guild_member;
pub mod guild_object;
pub mod integration;
pub mod role;
pub mod stage_instance;
pub mod welcome_screen;
| 18.142857 | 23 | 0.811024 |
5b0f6bd7fc069b70feaaa73d8fc80bf931f7a655
| 4,765 |
// Rust Bitcoin Library
// Written by
// The Rust Bitcoin developers
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
use std::error;
use core::fmt;
use blockdata::transaction::Transaction;
use consensus::encode;
use util::psbt::raw;
use hashes;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
/// Enum for marking psbt hash error
pub enum PsbtHash {
Ripemd,
Sha256,
Hash160,
Hash256,
}
/// Ways that a Partially Signed Transaction might fail.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Error {
/// Magic bytes for a PSBT must be the ASCII for "psbt" serialized in most
/// significant byte order.
InvalidMagic,
/// The separator for a PSBT must be `0xff`.
InvalidSeparator,
/// Known keys must be according to spec.
InvalidKey(raw::Key),
/// Non-proprietary key type found when proprietary key was expected
InvalidProprietaryKey,
/// Keys within key-value map should never be duplicated.
DuplicateKey(raw::Key),
/// The scriptSigs for the unsigned transaction must be empty.
UnsignedTxHasScriptSigs,
/// The scriptWitnesses for the unsigned transaction must be empty.
UnsignedTxHasScriptWitnesses,
/// A PSBT must have an unsigned transaction.
MustHaveUnsignedTx,
/// Signals that there are no more key-value pairs in a key-value map.
NoMorePairs,
/// Attempting to merge with a PSBT describing a different unsigned
/// transaction.
UnexpectedUnsignedTx {
/// Expected
expected: Box<Transaction>,
/// Actual
actual: Box<Transaction>,
},
/// Unable to parse as a standard SigHash type.
NonStandardSigHashType(u32),
/// Parsing errors from bitcoin_hashes
HashParseError(hashes::Error),
/// The pre-image must hash to the correponding psbt hash
InvalidPreimageHashPair {
/// Hash-type
hash_type: PsbtHash,
/// Pre-image
preimage: Box<[u8]>,
/// Hash value
hash: Box<[u8]>,
},
/// Data inconsistency/conflicting data during merge procedure
MergeConflict(String),
/// Serialization error in bitcoin consensus-encoded structures
ConsensusEncoding,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::InvalidKey(ref rkey) => write!(f, "invalid key: {}", rkey),
Error::InvalidProprietaryKey => write!(f, "non-proprietary key type found when proprietary key was expected"),
Error::DuplicateKey(ref rkey) => write!(f, "duplicate key: {}", rkey),
Error::UnexpectedUnsignedTx { expected: ref e, actual: ref a } => write!(f, "different unsigned transaction: expected {}, actual {}", e.txid(), a.txid()),
Error::NonStandardSigHashType(ref sht) => write!(f, "non-standard sighash type: {}", sht),
Error::InvalidMagic => f.write_str("invalid magic"),
Error::InvalidSeparator => f.write_str("invalid separator"),
Error::UnsignedTxHasScriptSigs => f.write_str("the unsigned transaction has script sigs"),
Error::UnsignedTxHasScriptWitnesses => f.write_str("the unsigned transaction has script witnesses"),
Error::MustHaveUnsignedTx => {
f.write_str("partially signed transactions must have an unsigned transaction")
}
Error::NoMorePairs => f.write_str("no more key-value pairs for this psbt map"),
Error::HashParseError(e) => write!(f, "Hash Parse Error: {}", e),
Error::InvalidPreimageHashPair{ref preimage, ref hash, ref hash_type} => {
// directly using debug forms of psbthash enums
write!(f, "Preimage {:?} does not match {:?} hash {:?}", preimage, hash_type, hash )
}
Error::MergeConflict(ref s) => { write!(f, "Merge conflict: {}", s) }
Error::ConsensusEncoding => f.write_str("bitcoin consensus or BIP-174 encoding error"),
}
}
}
impl error::Error for Error {}
#[doc(hidden)]
impl From<hashes::Error> for Error {
fn from(e: hashes::Error) -> Error {
Error::HashParseError(e)
}
}
impl From<encode::Error> for Error {
fn from(err: encode::Error) -> Self {
match err {
encode::Error::Psbt(err) => err,
_ => Error::ConsensusEncoding,
}
}
}
| 38.12 | 166 | 0.64638 |
11ad27b54fc770433e4cc6989b81bcce101bc9ef
| 5,286 |
// Copyright (c) Microsoft. All rights reserved.
use anyhow::{anyhow, Context};
use serde::Serialize;
use crate::internal::check::{CheckResult, Checker, CheckerCache, CheckerMeta, CheckerShared};
pub fn daemons_running() -> impl Iterator<Item = Box<dyn Checker>> {
let v: Vec<Box<dyn Checker>> = vec![
Box::new(DaemonRunningKeyd {}),
Box::new(DaemonRunningCertd {}),
Box::new(DaemonRunningTpmd {}),
Box::new(DaemonRunningIdentityd {}),
];
v.into_iter()
}
#[derive(Serialize)]
struct DaemonRunningKeyd {}
#[async_trait::async_trait]
impl Checker for DaemonRunningKeyd {
fn meta(&self) -> CheckerMeta {
CheckerMeta {
id: "keyd-running",
description: "keyd is running",
}
}
async fn execute(&mut self, _shared: &CheckerShared, cache: &mut CheckerCache) -> CheckResult {
use hyper::service::Service;
let mut connector = aziot_identityd_config::Endpoints::default().aziot_keyd;
let res = connector
.call("keyd.sock".parse().unwrap())
.await
.with_context(|| anyhow!("Could not connect to keyd on {}", connector));
match res {
Ok(_) => {
cache.daemons_running.keyd = true;
CheckResult::Ok
}
Err(e) => CheckResult::Failed(e),
}
}
}
#[derive(Serialize)]
struct DaemonRunningCertd {}
#[async_trait::async_trait]
impl Checker for DaemonRunningCertd {
fn meta(&self) -> CheckerMeta {
CheckerMeta {
id: "certd-running",
description: "certd is running",
}
}
async fn execute(&mut self, _shared: &CheckerShared, cache: &mut CheckerCache) -> CheckResult {
use hyper::service::Service;
let mut connector = aziot_identityd_config::Endpoints::default().aziot_certd;
let res = connector
.call("certd.sock".parse().unwrap())
.await
.with_context(|| anyhow!("Could not connect to certd on {}", connector));
match res {
Ok(_) => {
cache.daemons_running.certd = true;
CheckResult::Ok
}
Err(e) => CheckResult::Failed(e),
}
}
}
#[derive(Serialize)]
struct DaemonRunningTpmd {}
#[async_trait::async_trait]
impl Checker for DaemonRunningTpmd {
fn meta(&self) -> CheckerMeta {
CheckerMeta {
id: "tpmd-running",
description: "tpmd is running",
}
}
async fn execute(&mut self, _shared: &CheckerShared, cache: &mut CheckerCache) -> CheckResult {
use hyper::service::Service;
use aziot_identityd_config::{DpsAttestationMethod, ProvisioningType};
// Only try to connect to the tpmd when using DPS-TPM provisioning
let using_tpmd = match &cache.cfg.identityd {
Some(config) => matches!(
&config.provisioning.provisioning,
ProvisioningType::Dps {
attestation: DpsAttestationMethod::Tpm { .. },
..
}
),
None => {
// Check if the prev config happens to use DPS-TPM provisioning
match &cache.cfg.identityd_prev {
Some(cfg) => matches!(
&cfg.provisioning.provisioning,
ProvisioningType::Dps {
attestation: DpsAttestationMethod::Tpm { .. },
..
}
),
// there's no way to tell whether or not the user is using tpmd
// in this case, let's play it safe and try to connect to tpmd
None => true,
}
}
};
if !using_tpmd {
return CheckResult::Ignored;
}
let mut connector = aziot_identityd_config::Endpoints::default().aziot_tpmd;
let res = connector
.call("tpmd.sock".parse().unwrap())
.await
.with_context(|| anyhow!("Could not connect to tpmd on {}", connector));
match res {
Ok(_) => {
cache.daemons_running.tpmd = true;
CheckResult::Ok
}
Err(e) => CheckResult::Failed(e),
}
}
}
#[derive(Serialize)]
struct DaemonRunningIdentityd {}
#[async_trait::async_trait]
impl Checker for DaemonRunningIdentityd {
fn meta(&self) -> CheckerMeta {
CheckerMeta {
id: "identityd-running",
description: "identityd is running",
}
}
async fn execute(&mut self, _shared: &CheckerShared, cache: &mut CheckerCache) -> CheckResult {
use hyper::service::Service;
let mut connector = aziot_identityd_config::Endpoints::default().aziot_identityd;
let res = connector
.call("identityd.sock".parse().unwrap())
.await
.with_context(|| anyhow!("Could not connect to identityd on {}", connector));
match res {
Ok(_) => {
cache.daemons_running.identityd = true;
CheckResult::Ok
}
Err(e) => CheckResult::Failed(e),
}
}
}
| 30.554913 | 99 | 0.543511 |
1a772e322824afb251be1d9d5762efc47b637c6c
| 3,622 |
use core::ops::{Deref, DerefMut};
use rhai::INT;
use rand::Rng;
use pokedex::{moves::MoveCategory, types::PokemonType};
use pokedex::{item::Item, moves::Move, pokemon::owned::OwnedPokemon, pokemon::Pokemon};
use crate::{
engine::pokemon::{crit, throw_move, BattlePokemon},
pokemon::{Indexed, PokemonIdentifier},
};
use super::{moves::ScriptMove, ScriptDamage, ScriptRandom};
#[derive(Debug)]
pub struct DerefPtr<T>(*const T);
impl<T> DerefPtr<T> {
pub fn of(t: &T) -> Self {
Self(t as *const T)
}
}
impl<T> Deref for DerefPtr<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.0 }
}
}
impl<T> From<&T> for DerefPtr<T> {
fn from(t: &T) -> Self {
Self(t as _)
}
}
impl<T> Clone for DerefPtr<T> {
fn clone(&self) -> Self {
Self(self.0)
}
}
impl<T> Copy for DerefPtr<T> {}
type Pkmn = BattlePokemon<DerefPtr<Pokemon>, DerefPtr<Move>, DerefPtr<Item>>;
#[derive(Debug, Clone)]
pub struct ScriptPokemon<ID: Clone>(PokemonIdentifier<ID>, pub Pkmn);
impl<ID: Clone> ScriptPokemon<ID> {
// pub fn from_player<'d, const AS: usize>(
// (id, p): (PokemonIdentifier<ID>, Ref<BattlePlayer<'d, ID, AS>>),
// ) -> Option<Self> {
// p.party
// .active(id.index())
// .map(|p| Self::new(Indexed(id, p)))
// }
pub fn new<P: Deref<Target = Pokemon> + Clone, M: Deref<Target = Move> + Clone, I: Deref<Target = Item> + Clone>(
pokemon: Indexed<ID, &BattlePokemon<P, M, I>>,
) -> Self {
let Indexed(id, pokemon) = pokemon;
let p = BattlePokemon {
p: OwnedPokemon {
pokemon: DerefPtr(pokemon.pokemon.deref() as _),
level: pokemon.level,
gender: pokemon.gender,
nature: pokemon.nature,
hp: pokemon.hp,
ivs: pokemon.ivs,
evs: pokemon.evs,
friendship: pokemon.friendship,
ailment: pokemon.ailment,
nickname: None,
moves: Default::default(),
item: pokemon.item.as_ref().map(|i| DerefPtr::of(i.deref())),
experience: pokemon.experience,
},
stages: pokemon.stages.clone(),
};
// let p = pokemon.1 as *const BattlePokemon<'d>;
// let p = unsafe {
// core::mem::transmute::<*const BattlePokemon<'d>, *const BattlePokemon<'static>>(p)
// };
Self(id, p)
}
pub fn throw_move<R: Rng + Clone + 'static>(
&mut self,
mut random: ScriptRandom<R>,
m: ScriptMove,
) -> bool {
throw_move(random.deref_mut(), m.accuracy)
}
pub fn get_damage<R: Rng + Clone + 'static>(
&mut self,
random: ScriptRandom<R>,
target: Self,
power: INT,
category: MoveCategory,
move_type: PokemonType,
crit_rate: INT,
) -> ScriptDamage {
let mut random = random;
let crit = crit(random.deref_mut(), crit_rate as _);
ScriptDamage::from(self.move_power_damage_random(
random.deref_mut(),
&target,
power as _,
category,
move_type,
crit,
))
}
pub fn hp(&mut self) -> INT {
self.hp as _
}
}
impl<ID: Clone> Deref for ScriptPokemon<ID> {
type Target = Pkmn;
fn deref(&self) -> &Self::Target {
&self.1
}
}
impl<ID: Clone> Into<PokemonIdentifier<ID>> for ScriptPokemon<ID> {
fn into(self) -> PokemonIdentifier<ID> {
self.0
}
}
| 26.246377 | 117 | 0.54169 |
ab7dbf4389fd6272b1204168c040b3dfb747354e
| 2,442 |
/*MIT License
Copyright (c) 2020 Akshay Naik
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.
*/
mod config;
mod internal;
mod cli;
use std::process;
use std::path::Path;
use clap::App;
use log::{error};
use internal::server;
use cli::app;
use config::Config;
use config::logger;
pub fn start() {
let app = app::get_app();
let config_file = get_config_file(app);
// if configuration file exist then pass configuration file else send None
let config:Config = if Path::new(&config_file).exists() {
config::parse_config(Some(&config_file))
} else {
println!("configuration file {} not found on disk ",&config_file);
config::parse_config(None)
};
if let Some(log_file) = config.log_file {
logger::create_logger(Some(log_file));
} else {
logger::create_logger(None);
}
if let Err(e) = server::start_server(&config) {
error!("Error occured while starting server {}", e);
process::exit(1);
}
}
// Read configuration flle from cli, if not present then use default configuratoin file i.e. feline.toml
fn get_config_file(app: App) -> String {
let matches = app.get_matches();
match matches.value_of("config") {
Some(config_file) => {
String::from(config_file)
},
None => {
println!("No config file given using default config file, feline.toml");
String::from("feline.toml")
},
}
}
| 31.307692 | 104 | 0.699017 |
0edcd1b9be70e59f4201be6937e1a43b68a4e120
| 314 |
use crate::models::Hnt;
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct PaymentV1 {
pub hash: String,
#[serde(deserialize_with = "Hnt::deserialize")]
pub amount: Hnt,
pub fee: u64,
pub nonce: u64,
pub payer: String,
pub payee: String,
}
| 22.428571 | 51 | 0.659236 |
e2e7817bd6b48c7010b7f140e5a44d20cd4eb33b
| 14,973 |
#[doc = "Reader of register INTEN"]
pub type R = crate::R<u32, super::INTEN>;
#[doc = "Writer for register INTEN"]
pub type W = crate::W<u32, super::INTEN>;
#[doc = "Register INTEN `reset()`'s with value 0"]
impl crate::ResetValue for super::INTEN {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Enable or disable interrupt for STOPPED event\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum STOPPED_A {
#[doc = "0: Disable"]
DISABLED = 0,
#[doc = "1: Enable"]
ENABLED = 1,
}
impl From<STOPPED_A> for bool {
#[inline(always)]
fn from(variant: STOPPED_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `STOPPED`"]
pub type STOPPED_R = crate::R<bool, STOPPED_A>;
impl STOPPED_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> STOPPED_A {
match self.bits {
false => STOPPED_A::DISABLED,
true => STOPPED_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == STOPPED_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == STOPPED_A::ENABLED
}
}
#[doc = "Write proxy for field `STOPPED`"]
pub struct STOPPED_W<'a> {
w: &'a mut W,
}
impl<'a> STOPPED_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: STOPPED_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(STOPPED_A::DISABLED)
}
#[doc = "Enable"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(STOPPED_A::ENABLED)
}
#[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 = "Enable or disable interrupt for ERROR event\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ERROR_A {
#[doc = "0: Disable"]
DISABLED = 0,
#[doc = "1: Enable"]
ENABLED = 1,
}
impl From<ERROR_A> for bool {
#[inline(always)]
fn from(variant: ERROR_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `ERROR`"]
pub type ERROR_R = crate::R<bool, ERROR_A>;
impl ERROR_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ERROR_A {
match self.bits {
false => ERROR_A::DISABLED,
true => ERROR_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ERROR_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ERROR_A::ENABLED
}
}
#[doc = "Write proxy for field `ERROR`"]
pub struct ERROR_W<'a> {
w: &'a mut W,
}
impl<'a> ERROR_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ERROR_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(ERROR_A::DISABLED)
}
#[doc = "Enable"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(ERROR_A::ENABLED)
}
#[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 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Enable or disable interrupt for RXSTARTED event\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RXSTARTED_A {
#[doc = "0: Disable"]
DISABLED = 0,
#[doc = "1: Enable"]
ENABLED = 1,
}
impl From<RXSTARTED_A> for bool {
#[inline(always)]
fn from(variant: RXSTARTED_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `RXSTARTED`"]
pub type RXSTARTED_R = crate::R<bool, RXSTARTED_A>;
impl RXSTARTED_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RXSTARTED_A {
match self.bits {
false => RXSTARTED_A::DISABLED,
true => RXSTARTED_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == RXSTARTED_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == RXSTARTED_A::ENABLED
}
}
#[doc = "Write proxy for field `RXSTARTED`"]
pub struct RXSTARTED_W<'a> {
w: &'a mut W,
}
impl<'a> RXSTARTED_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RXSTARTED_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(RXSTARTED_A::DISABLED)
}
#[doc = "Enable"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(RXSTARTED_A::ENABLED)
}
#[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 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Enable or disable interrupt for TXSTARTED event\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TXSTARTED_A {
#[doc = "0: Disable"]
DISABLED = 0,
#[doc = "1: Enable"]
ENABLED = 1,
}
impl From<TXSTARTED_A> for bool {
#[inline(always)]
fn from(variant: TXSTARTED_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TXSTARTED`"]
pub type TXSTARTED_R = crate::R<bool, TXSTARTED_A>;
impl TXSTARTED_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TXSTARTED_A {
match self.bits {
false => TXSTARTED_A::DISABLED,
true => TXSTARTED_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == TXSTARTED_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == TXSTARTED_A::ENABLED
}
}
#[doc = "Write proxy for field `TXSTARTED`"]
pub struct TXSTARTED_W<'a> {
w: &'a mut W,
}
impl<'a> TXSTARTED_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TXSTARTED_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(TXSTARTED_A::DISABLED)
}
#[doc = "Enable"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(TXSTARTED_A::ENABLED)
}
#[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 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Enable or disable interrupt for WRITE event\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WRITE_A {
#[doc = "0: Disable"]
DISABLED = 0,
#[doc = "1: Enable"]
ENABLED = 1,
}
impl From<WRITE_A> for bool {
#[inline(always)]
fn from(variant: WRITE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `WRITE`"]
pub type WRITE_R = crate::R<bool, WRITE_A>;
impl WRITE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> WRITE_A {
match self.bits {
false => WRITE_A::DISABLED,
true => WRITE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == WRITE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == WRITE_A::ENABLED
}
}
#[doc = "Write proxy for field `WRITE`"]
pub struct WRITE_W<'a> {
w: &'a mut W,
}
impl<'a> WRITE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: WRITE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(WRITE_A::DISABLED)
}
#[doc = "Enable"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(WRITE_A::ENABLED)
}
#[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 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Enable or disable interrupt for READ event\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum READ_A {
#[doc = "0: Disable"]
DISABLED = 0,
#[doc = "1: Enable"]
ENABLED = 1,
}
impl From<READ_A> for bool {
#[inline(always)]
fn from(variant: READ_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `READ`"]
pub type READ_R = crate::R<bool, READ_A>;
impl READ_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> READ_A {
match self.bits {
false => READ_A::DISABLED,
true => READ_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == READ_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == READ_A::ENABLED
}
}
#[doc = "Write proxy for field `READ`"]
pub struct READ_W<'a> {
w: &'a mut W,
}
impl<'a> READ_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: READ_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(READ_A::DISABLED)
}
#[doc = "Enable"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(READ_A::ENABLED)
}
#[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 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
impl R {
#[doc = "Bit 1 - Enable or disable interrupt for STOPPED event"]
#[inline(always)]
pub fn stopped(&self) -> STOPPED_R {
STOPPED_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 9 - Enable or disable interrupt for ERROR event"]
#[inline(always)]
pub fn error(&self) -> ERROR_R {
ERROR_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 19 - Enable or disable interrupt for RXSTARTED event"]
#[inline(always)]
pub fn rxstarted(&self) -> RXSTARTED_R {
RXSTARTED_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - Enable or disable interrupt for TXSTARTED event"]
#[inline(always)]
pub fn txstarted(&self) -> TXSTARTED_R {
TXSTARTED_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 25 - Enable or disable interrupt for WRITE event"]
#[inline(always)]
pub fn write(&self) -> WRITE_R {
WRITE_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - Enable or disable interrupt for READ event"]
#[inline(always)]
pub fn read(&self) -> READ_R {
READ_R::new(((self.bits >> 26) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 1 - Enable or disable interrupt for STOPPED event"]
#[inline(always)]
pub fn stopped(&mut self) -> STOPPED_W {
STOPPED_W { w: self }
}
#[doc = "Bit 9 - Enable or disable interrupt for ERROR event"]
#[inline(always)]
pub fn error(&mut self) -> ERROR_W {
ERROR_W { w: self }
}
#[doc = "Bit 19 - Enable or disable interrupt for RXSTARTED event"]
#[inline(always)]
pub fn rxstarted(&mut self) -> RXSTARTED_W {
RXSTARTED_W { w: self }
}
#[doc = "Bit 20 - Enable or disable interrupt for TXSTARTED event"]
#[inline(always)]
pub fn txstarted(&mut self) -> TXSTARTED_W {
TXSTARTED_W { w: self }
}
#[doc = "Bit 25 - Enable or disable interrupt for WRITE event"]
#[inline(always)]
pub fn write(&mut self) -> WRITE_W {
WRITE_W { w: self }
}
#[doc = "Bit 26 - Enable or disable interrupt for READ event"]
#[inline(always)]
pub fn read(&mut self) -> READ_W {
READ_W { w: self }
}
}
| 28.411765 | 86 | 0.550524 |
721610f2e567caf9e5a3a038846cfa6b1f02bb7b
| 155 |
// machine-mode cycle counter
#[inline]
pub unsafe fn read() -> usize {
let ret:usize;
llvm_asm!("csrr $0, time":"=r"(ret):::"volatile");
ret
}
| 22.142857 | 54 | 0.593548 |
010455ff04c9501d6a858b88c997fddc77da5af5
| 435 |
use microtype_core::Microtype;
microtype_macro::microtype! {
#[derive(Clone)]
String {
Email,
Username,
}
}
fn main() {
let mut email = Email::new("hello".into());
assert_eq!(email.inner(), "hello");
assert_eq!(email.inner_mut(), "hello");
assert_eq!(email.clone().into_inner(), "hello");
let username: Username = email.transmute();
assert_eq!(username.into_inner(), "hello");
}
| 20.714286 | 52 | 0.609195 |
3804874a650f6c065e23c78043bbfc8b1c35a168
| 22,075 |
// Copyright 2013-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.
//! A priority queue implemented with a binary heap.
//!
//! Insertion and popping the largest element have `O(log n)` time complexity. Checking the largest
//! element is `O(1)`. Converting a vector to a binary heap can be done in-place, and has `O(n)`
//! complexity. A binary heap can also be converted to a sorted vector in-place, allowing it to
//! be used for an `O(n log n)` in-place heapsort.
//!
//! # Examples
//!
//! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
//! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
//! It shows how to use `BinaryHeap` with custom types.
//!
//! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
//! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem
//! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph
//!
//! ```
//! use std::cmp::Ordering;
//! use std::collections::BinaryHeap;
//! use std::usize;
//!
//! #[derive(Copy, Clone, Eq, PartialEq)]
//! struct State {
//! cost: usize,
//! position: usize,
//! }
//!
//! // The priority queue depends on `Ord`.
//! // Explicitly implement the trait so the queue becomes a min-heap
//! // instead of a max-heap.
//! impl Ord for State {
//! fn cmp(&self, other: &State) -> Ordering {
//! // Notice that the we flip the ordering here
//! other.cost.cmp(&self.cost)
//! }
//! }
//!
//! // `PartialOrd` needs to be implemented as well.
//! impl PartialOrd for State {
//! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
//! Some(self.cmp(other))
//! }
//! }
//!
//! // Each node is represented as an `usize`, for a shorter implementation.
//! struct Edge {
//! node: usize,
//! cost: usize,
//! }
//!
//! // Dijkstra's shortest path algorithm.
//!
//! // Start at `start` and use `dist` to track the current shortest distance
//! // to each node. This implementation isn't memory-efficient as it may leave duplicate
//! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
//! // for a simpler implementation.
//! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> usize {
//! // dist[node] = current shortest distance from `start` to `node`
//! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
//!
//! let mut heap = BinaryHeap::new();
//!
//! // We're at `start`, with a zero cost
//! dist[start] = 0;
//! heap.push(State { cost: 0, position: start });
//!
//! // Examine the frontier with lower cost nodes first (min-heap)
//! while let Some(State { cost, position }) = heap.pop() {
//! // Alternatively we could have continued to find all shortest paths
//! if position == goal { return cost; }
//!
//! // Important as we may have already found a better way
//! if cost > dist[position] { continue; }
//!
//! // For each node we can reach, see if we can find a way with
//! // a lower cost going through this node
//! for edge in adj_list[position].iter() {
//! let next = State { cost: cost + edge.cost, position: edge.node };
//!
//! // If so, add it to the frontier and continue
//! if next.cost < dist[next.position] {
//! heap.push(next);
//! // Relaxation, we have now found a better way
//! dist[next.position] = next.cost;
//! }
//! }
//! }
//!
//! // Goal not reachable
//! usize::MAX
//! }
//!
//! fn main() {
//! // This is the directed graph we're going to use.
//! // The node numbers correspond to the different states,
//! // and the edge weights symbolize the cost of moving
//! // from one node to another.
//! // Note that the edges are one-way.
//! //
//! // 7
//! // +-----------------+
//! // | |
//! // v 1 2 |
//! // 0 -----> 1 -----> 3 ---> 4
//! // | ^ ^ ^
//! // | | 1 | |
//! // | | | 3 | 1
//! // +------> 2 -------+ |
//! // 10 | |
//! // +---------------+
//! //
//! // The graph is represented as an adjacency list where each index,
//! // corresponding to a node value, has a list of outgoing edges.
//! // Chosen for its efficiency.
//! let graph = vec![
//! // Node 0
//! vec![Edge { node: 2, cost: 10 },
//! Edge { node: 1, cost: 1 }],
//! // Node 1
//! vec![Edge { node: 3, cost: 2 }],
//! // Node 2
//! vec![Edge { node: 1, cost: 1 },
//! Edge { node: 3, cost: 3 },
//! Edge { node: 4, cost: 1 }],
//! // Node 3
//! vec![Edge { node: 0, cost: 7 },
//! Edge { node: 4, cost: 2 }],
//! // Node 4
//! vec![]];
//!
//! assert_eq!(shortest_path(&graph, 0, 1), 1);
//! assert_eq!(shortest_path(&graph, 0, 3), 3);
//! assert_eq!(shortest_path(&graph, 3, 0), 7);
//! assert_eq!(shortest_path(&graph, 0, 4), 5);
//! assert_eq!(shortest_path(&graph, 4, 0), usize::MAX);
//! }
//! ```
#![allow(missing_docs)]
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::default::Default;
use core::iter::{FromIterator, IntoIterator};
use core::mem::{zeroed, replace, swap};
use core::ptr;
use slice;
use vec::{self, Vec};
/// A priority queue implemented with a binary heap.
///
/// This will be a max-heap.
///
/// It is a logic error for an item to be modified in such a way that the
/// item's ordering relative to any other item, as determined by the `Ord`
/// trait, changes while it is in the heap. This is normally only possible
/// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct BinaryHeap<T> {
data: Vec<T>,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Default for BinaryHeap<T> {
#[inline]
fn default() -> BinaryHeap<T> { BinaryHeap::new() }
}
impl<T: Ord> BinaryHeap<T> {
/// Creates an empty `BinaryHeap` as a max-heap.
///
/// # Examples
///
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// heap.push(4);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> BinaryHeap<T> { BinaryHeap { data: vec![] } }
/// Creates an empty `BinaryHeap` with a specific capacity.
/// This preallocates enough memory for `capacity` elements,
/// so that the `BinaryHeap` does not have to be reallocated
/// until it contains at least that many values.
///
/// # Examples
///
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::with_capacity(10);
/// heap.push(4);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
BinaryHeap { data: Vec::with_capacity(capacity) }
}
/// Creates a `BinaryHeap` from a vector. This is sometimes called
/// `heapifying` the vector.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![9, 1, 2, 7, 3, 2]);
/// ```
pub fn from_vec(vec: Vec<T>) -> BinaryHeap<T> {
let mut heap = BinaryHeap { data: vec };
let mut n = heap.len() / 2;
while n > 0 {
n -= 1;
heap.sift_down(n);
}
heap
}
/// Returns an iterator visiting all values in the underlying vector, in
/// arbitrary order.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
///
/// // Print 1, 2, 3, 4 in arbitrary order
/// for x in heap.iter() {
/// println!("{}", x);
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn iter(&self) -> Iter<T> {
Iter { iter: self.data.iter() }
}
/// Creates a consuming iterator, that is, one that moves each value out of
/// the binary heap in arbitrary order. The binary heap cannot be used
/// after calling this.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
///
/// // Print 1, 2, 3, 4 in arbitrary order
/// for x in heap.into_iter() {
/// // x has type i32, not &i32
/// println!("{}", x);
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_iter(self) -> IntoIter<T> {
IntoIter { iter: self.data.into_iter() }
}
/// Returns the greatest item in the binary heap, or `None` if it is empty.
///
/// # Examples
///
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// assert_eq!(heap.peek(), None);
///
/// heap.push(1);
/// heap.push(5);
/// heap.push(2);
/// assert_eq!(heap.peek(), Some(&5));
///
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn peek(&self) -> Option<&T> {
self.data.get(0)
}
/// Returns the number of elements the binary heap can hold without reallocating.
///
/// # Examples
///
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::with_capacity(100);
/// assert!(heap.capacity() >= 100);
/// heap.push(4);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn capacity(&self) -> usize { self.data.capacity() }
/// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
/// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
///
/// Note that the allocator may give the collection more space than it requests. Therefore
/// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
/// insertions are expected.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// heap.reserve_exact(100);
/// assert!(heap.capacity() >= 100);
/// heap.push(4);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve_exact(&mut self, additional: usize) {
self.data.reserve_exact(additional);
}
/// Reserves capacity for at least `additional` more elements to be inserted in the
/// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// heap.reserve(100);
/// assert!(heap.capacity() >= 100);
/// heap.push(4);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve(&mut self, additional: usize) {
self.data.reserve(additional);
}
/// Discards as much additional capacity as possible.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn shrink_to_fit(&mut self) {
self.data.shrink_to_fit();
}
/// Removes the greatest item from the binary heap and returns it, or `None` if it
/// is empty.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::from_vec(vec![1, 3]);
///
/// assert_eq!(heap.pop(), Some(3));
/// assert_eq!(heap.pop(), Some(1));
/// assert_eq!(heap.pop(), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop(&mut self) -> Option<T> {
self.data.pop().map(|mut item| {
if !self.is_empty() {
swap(&mut item, &mut self.data[0]);
self.sift_down(0);
}
item
})
}
/// Pushes an item onto the binary heap.
///
/// # Examples
///
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// heap.push(3);
/// heap.push(5);
/// heap.push(1);
///
/// assert_eq!(heap.len(), 3);
/// assert_eq!(heap.peek(), Some(&5));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push(&mut self, item: T) {
let old_len = self.len();
self.data.push(item);
self.sift_up(0, old_len);
}
/// Pushes an item onto the binary heap, then pops the greatest item off the queue in
/// an optimized fashion.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// heap.push(1);
/// heap.push(5);
///
/// assert_eq!(heap.push_pop(3), 5);
/// assert_eq!(heap.push_pop(9), 9);
/// assert_eq!(heap.len(), 2);
/// assert_eq!(heap.peek(), Some(&3));
/// ```
pub fn push_pop(&mut self, mut item: T) -> T {
match self.data.get_mut(0) {
None => return item,
Some(top) => if *top > item {
swap(&mut item, top);
} else {
return item;
},
}
self.sift_down(0);
item
}
/// Pops the greatest item off the binary heap, then pushes an item onto the queue in
/// an optimized fashion. The push is done regardless of whether the binary heap
/// was empty.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
///
/// assert_eq!(heap.replace(1), None);
/// assert_eq!(heap.replace(3), Some(1));
/// assert_eq!(heap.len(), 1);
/// assert_eq!(heap.peek(), Some(&3));
/// ```
pub fn replace(&mut self, mut item: T) -> Option<T> {
if !self.is_empty() {
swap(&mut item, &mut self.data[0]);
self.sift_down(0);
Some(item)
} else {
self.push(item);
None
}
}
/// Consumes the `BinaryHeap` and returns the underlying vector
/// in arbitrary order.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4, 5, 6, 7]);
/// let vec = heap.into_vec();
///
/// // Will print in some order
/// for x in vec.iter() {
/// println!("{}", x);
/// }
/// ```
pub fn into_vec(self) -> Vec<T> { self.data }
/// Consumes the `BinaryHeap` and returns a vector in sorted
/// (ascending) order.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BinaryHeap;
///
/// let mut heap = BinaryHeap::from_vec(vec![1, 2, 4, 5, 7]);
/// heap.push(6);
/// heap.push(3);
///
/// let vec = heap.into_sorted_vec();
/// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
/// ```
pub fn into_sorted_vec(mut self) -> Vec<T> {
let mut end = self.len();
while end > 1 {
end -= 1;
self.data.swap(0, end);
self.sift_down_range(0, end);
}
self.into_vec()
}
// The implementations of sift_up and sift_down use unsafe blocks in
// order to move an element out of the vector (leaving behind a
// zeroed element), shift along the others and move it back into the
// vector over the junk element. This reduces the constant factor
// compared to using swaps, which involves twice as many moves.
fn sift_up(&mut self, start: usize, mut pos: usize) {
unsafe {
let new = replace(&mut self.data[pos], zeroed());
while pos > start {
let parent = (pos - 1) >> 1;
if new <= self.data[parent] { break; }
let x = replace(&mut self.data[parent], zeroed());
ptr::write(&mut self.data[pos], x);
pos = parent;
}
ptr::write(&mut self.data[pos], new);
}
}
fn sift_down_range(&mut self, mut pos: usize, end: usize) {
unsafe {
let start = pos;
let new = replace(&mut self.data[pos], zeroed());
let mut child = 2 * pos + 1;
while child < end {
let right = child + 1;
if right < end && !(self.data[child] > self.data[right]) {
child = right;
}
let x = replace(&mut self.data[child], zeroed());
ptr::write(&mut self.data[pos], x);
pos = child;
child = 2 * pos + 1;
}
ptr::write(&mut self.data[pos], new);
self.sift_up(start, pos);
}
}
fn sift_down(&mut self, pos: usize) {
let len = self.len();
self.sift_down_range(pos, len);
}
/// Returns the length of the binary heap.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn len(&self) -> usize { self.data.len() }
/// Checks if the binary heap is empty.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Clears the binary heap, returning an iterator over the removed elements.
///
/// The elements are removed in arbitrary order.
#[inline]
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn drain(&mut self) -> Drain<T> {
Drain { iter: self.data.drain() }
}
/// Drops all items from the binary heap.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn clear(&mut self) { self.drain(); }
}
/// `BinaryHeap` iterator.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Iter <'a, T: 'a> {
iter: slice::Iter<'a, T>,
}
// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Clone for Iter<'a, T> {
fn clone(&self) -> Iter<'a, T> {
Iter { iter: self.iter.clone() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<&'a T> { self.iter.next() }
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
/// An iterator that moves out of a `BinaryHeap`.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct IntoIter<T> {
iter: vec::IntoIter<T>,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Iterator for IntoIter<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> { self.iter.next() }
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> DoubleEndedIterator for IntoIter<T> {
#[inline]
fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ExactSizeIterator for IntoIter<T> {}
/// An iterator that drains a `BinaryHeap`.
#[unstable(feature = "collections", reason = "recent addition")]
pub struct Drain<'a, T: 'a> {
iter: vec::Drain<'a, T>,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: 'a> Iterator for Drain<'a, T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> { self.iter.next() }
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> BinaryHeap<T> {
BinaryHeap::from_vec(iter.into_iter().collect())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> IntoIterator for BinaryHeap<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
self.into_iter()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Extend<T> for BinaryHeap<T> {
fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
let iter = iterable.into_iter();
let (lower, _) = iter.size_hint();
self.reserve(lower);
for elem in iter {
self.push(elem);
}
}
}
| 31.267705 | 99 | 0.53504 |
ac7d51c1ad2b6dd03745fc6200411b9532143823
| 3,528 |
extern crate walkdir;
use std::{env, path::Path, process::Command};
use walkdir::WalkDir;
fn rerun_if_changed(files: &[&str], directories: &[&str], excludes: &[&str]) {
let mut all_files: Vec<_> = files.iter().map(|f| f.to_string()).collect();
for directory in directories {
let files_in_directory: Vec<_> = WalkDir::new(directory)
.into_iter()
.map(|entry| entry.unwrap())
.filter(|entry| {
if !entry.file_type().is_file() {
return false;
}
for exclude in excludes.iter() {
if entry.path().to_str().unwrap().contains(exclude) {
return false;
}
}
true
})
.map(|f| f.path().to_str().unwrap().to_owned())
.collect();
all_files.extend_from_slice(&files_in_directory[..]);
}
for file in all_files {
if !Path::new(&file).is_file() {
panic!("{} is not a file", file);
}
println!("cargo:rerun-if-changed={}", file);
}
}
fn main() {
let bpf_c = env::var("CARGO_FEATURE_BPF_C").is_ok();
if bpf_c {
let install_dir =
"OUT_DIR=../target/".to_string() + &env::var("PROFILE").unwrap() + &"/bpf".to_string();
println!("cargo:warning=(not a warning) Building C-based BPF programs");
assert!(Command::new("make")
.current_dir("c")
.arg("programs")
.arg(&install_dir)
.status()
.expect("Failed to build C-based BPF programs")
.success());
rerun_if_changed(&["c/makefile"], &["c/src", "../../sdk"], &["/target/"]);
}
let bpf_rust = env::var("CARGO_FEATURE_BPF_RUST").is_ok();
if bpf_rust {
let install_dir =
"target/".to_string() + &env::var("PROFILE").unwrap() + &"/bpf".to_string();
assert!(Command::new("mkdir")
.arg("-p")
.arg(&install_dir)
.status()
.expect("Unable to create BPF install directory")
.success());
let rust_programs = [
"128bit",
"alloc",
"dep_crate",
"deprecated_loader",
"dup_accounts",
"error_handling",
"external_spend",
"invoke",
"invoked",
"iter",
"many_args",
"noop",
"panic",
"param_passing",
"sanity",
"sysval",
];
for program in rust_programs.iter() {
println!(
"cargo:warning=(not a warning) Building Rust-based BPF programs: solana_bpf_rust_{}",
program
);
assert!(Command::new("bash")
.current_dir("rust")
.args(&["./do.sh", "build", program])
.status()
.expect("Error calling do.sh from build.rs")
.success());
let src = format!(
"target/bpfel-unknown-unknown/release/solana_bpf_rust_{}.so",
program,
);
assert!(Command::new("cp")
.arg(&src)
.arg(&install_dir)
.status()
.unwrap_or_else(|_| panic!("Failed to cp {} to {}", src, install_dir))
.success());
}
rerun_if_changed(&[], &["rust", "../../sdk", &install_dir], &["/target/"]);
}
}
| 31.783784 | 101 | 0.465986 |
e49cf0352a4c1a7d4d811888ee97d4f7262626c3
| 18,281 |
use tempfile;
use testutil;
use crate::{
local::USER_EXECUTABLE_MODE, CacheDest, CacheName, CommandRunner as CommandRunnerTrait, Context,
FallibleProcessResultWithPlatform, NamedCaches, Platform, Process, RelativePath,
};
use hashing::EMPTY_DIGEST;
use shell_quote::bash;
use spectral::{assert_that, string::StrAssertions};
use std;
use std::collections::BTreeMap;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::str;
use std::time::Duration;
use store::Store;
use tempfile::TempDir;
use testutil::data::{TestData, TestDirectory};
use testutil::path::find_bash;
use testutil::{owned_string_vec, relative_paths};
use workunit_store::WorkunitStore;
#[derive(PartialEq, Debug)]
struct LocalTestResult {
original: FallibleProcessResultWithPlatform,
stdout_bytes: Vec<u8>,
stderr_bytes: Vec<u8>,
}
#[tokio::test]
#[cfg(unix)]
async fn stdout() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(Process::new(owned_string_vec(&["/bin/echo", "-n", "foo"])))
.await
.unwrap();
assert_eq!(result.stdout_bytes, "foo".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(result.original.output_directory, EMPTY_DIGEST);
}
#[tokio::test]
#[cfg(unix)]
async fn stdout_and_stderr_and_exit_code() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(Process::new(owned_string_vec(&[
"/bin/bash",
"-c",
"echo -n foo ; echo >&2 -n bar ; exit 1",
])))
.await
.unwrap();
assert_eq!(result.stdout_bytes, "foo".as_bytes());
assert_eq!(result.stderr_bytes, "bar".as_bytes());
assert_eq!(result.original.exit_code, 1);
assert_eq!(result.original.output_directory, EMPTY_DIGEST);
}
#[tokio::test]
#[cfg(unix)]
async fn capture_exit_code_signal() {
WorkunitStore::setup_for_tests();
// Launch a process that kills itself with a signal.
let result = run_command_locally(Process::new(owned_string_vec(&[
"/bin/bash",
"-c",
"kill $$",
])))
.await
.unwrap();
assert_eq!(result.stdout_bytes, "".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, -15);
assert_eq!(result.original.output_directory, EMPTY_DIGEST);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
#[cfg(unix)]
async fn env() {
WorkunitStore::setup_for_tests();
let mut env: BTreeMap<String, String> = BTreeMap::new();
env.insert("FOO".to_string(), "foo".to_string());
env.insert("BAR".to_string(), "not foo".to_string());
let result =
run_command_locally(Process::new(owned_string_vec(&["/usr/bin/env"])).env(env.clone()))
.await
.unwrap();
let stdout = String::from_utf8(result.stdout_bytes.to_vec()).unwrap();
let got_env: BTreeMap<String, String> = stdout
.split("\n")
.filter(|line| !line.is_empty())
.map(|line| line.splitn(2, "="))
.map(|mut parts| {
(
parts.next().unwrap().to_string(),
parts.next().unwrap_or("").to_string(),
)
})
.filter(|x| x.0 != "PATH")
.collect();
assert_eq!(env, got_env);
}
#[tokio::test]
#[cfg(unix)]
async fn env_is_deterministic() {
WorkunitStore::setup_for_tests();
fn make_request() -> Process {
let mut env = BTreeMap::new();
env.insert("FOO".to_string(), "foo".to_string());
env.insert("BAR".to_string(), "not foo".to_string());
Process::new(owned_string_vec(&["/usr/bin/env"])).env(env)
}
let result1 = run_command_locally(make_request()).await;
let result2 = run_command_locally(make_request()).await;
assert_eq!(result1.unwrap(), result2.unwrap());
}
#[tokio::test]
async fn binary_not_found() {
WorkunitStore::setup_for_tests();
let err_string = run_command_locally(Process::new(owned_string_vec(&["echo", "-n", "foo"])))
.await
.expect_err("Want Err");
assert!(err_string.contains("Failed to execute"));
assert!(err_string.contains("echo"));
}
#[tokio::test]
async fn output_files_none() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(Process::new(owned_string_vec(&[
&find_bash(),
"-c",
"exit 0",
])))
.await
.unwrap();
assert_eq!(result.stdout_bytes, "".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(result.original.output_directory, EMPTY_DIGEST);
}
#[tokio::test]
async fn output_files_one() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(
Process::new(vec![
find_bash(),
"-c".to_owned(),
format!("echo -n {} > {}", TestData::roland().string(), "roland"),
])
.output_files(relative_paths(&["roland"]).collect()),
)
.await
.unwrap();
assert_eq!(result.stdout_bytes, "".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(
result.original.output_directory,
TestDirectory::containing_roland().digest()
);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
async fn output_dirs() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(
Process::new(vec![
find_bash(),
"-c".to_owned(),
format!(
"/bin/mkdir cats && echo -n {} > {} ; echo -n {} > treats",
TestData::roland().string(),
"cats/roland",
TestData::catnip().string()
),
])
.output_files(relative_paths(&["treats"]).collect())
.output_directories(relative_paths(&["cats"]).collect()),
)
.await
.unwrap();
assert_eq!(result.stdout_bytes, "".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(
result.original.output_directory,
TestDirectory::recursive().digest()
);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
async fn output_files_many() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(
Process::new(vec![
find_bash(),
"-c".to_owned(),
format!(
"echo -n {} > cats/roland ; echo -n {} > treats",
TestData::roland().string(),
TestData::catnip().string()
),
])
.output_files(relative_paths(&["cats/roland", "treats"]).collect()),
)
.await
.unwrap();
assert_eq!(result.stdout_bytes, "".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(
result.original.output_directory,
TestDirectory::recursive().digest()
);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
async fn output_files_execution_failure() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(
Process::new(vec![
find_bash(),
"-c".to_owned(),
format!(
"echo -n {} > {} ; exit 1",
TestData::roland().string(),
"roland"
),
])
.output_files(relative_paths(&["roland"]).collect()),
)
.await
.unwrap();
assert_eq!(result.stdout_bytes, "".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 1);
assert_eq!(
result.original.output_directory,
TestDirectory::containing_roland().digest()
);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
async fn output_files_partial_output() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(
Process::new(vec![
find_bash(),
"-c".to_owned(),
format!("echo -n {} > {}", TestData::roland().string(), "roland"),
])
.output_files(
relative_paths(&["roland", "susannah"])
.into_iter()
.collect(),
),
)
.await
.unwrap();
assert_eq!(result.stdout_bytes, "".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(
result.original.output_directory,
TestDirectory::containing_roland().digest()
);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
async fn output_overlapping_file_and_dir() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(
Process::new(vec![
find_bash(),
"-c".to_owned(),
format!("echo -n {} > cats/roland", TestData::roland().string()),
])
.output_files(relative_paths(&["cats/roland"]).collect())
.output_directories(relative_paths(&["cats"]).collect()),
)
.await
.unwrap();
assert_eq!(result.stdout_bytes, "".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(
result.original.output_directory,
TestDirectory::nested().digest()
);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
async fn append_only_cache_created() {
WorkunitStore::setup_for_tests();
let name = "geo";
let dest = format!(".cache/{}", name);
let cache_name = CacheName::new(name.to_owned()).unwrap();
let cache_dest = CacheDest::new(dest.clone()).unwrap();
let result = run_command_locally(
Process::new(vec!["/bin/ls".to_owned(), dest.clone()])
.append_only_caches(vec![(cache_name, cache_dest)].into_iter().collect()),
)
.await
.unwrap();
assert_eq!(result.stdout_bytes, format!("{}\n", dest).as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(result.original.output_directory, EMPTY_DIGEST);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
async fn jdk_symlink() {
WorkunitStore::setup_for_tests();
let preserved_work_tmpdir = TempDir::new().unwrap();
let roland = TestData::roland().bytes();
std::fs::write(preserved_work_tmpdir.path().join("roland"), roland.clone())
.expect("Writing temporary file");
let mut process = Process::new(vec!["/bin/cat".to_owned(), ".jdk/roland".to_owned()]);
process.timeout = one_second();
process.description = "cat roland".to_string();
process.jdk_home = Some(preserved_work_tmpdir.path().to_path_buf());
let result = run_command_locally(process).await.unwrap();
assert_eq!(result.stdout_bytes, roland);
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(result.original.output_directory, EMPTY_DIGEST);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
async fn test_directory_preservation() {
WorkunitStore::setup_for_tests();
let preserved_work_tmpdir = TempDir::new().unwrap();
let preserved_work_root = preserved_work_tmpdir.path().to_owned();
let bash_contents = format!("echo -n {} > {}", TestData::roland().string(), "roland");
let argv = vec![find_bash(), "-c".to_owned(), bash_contents.clone()];
let result = run_command_locally_in_dir(
Process::new(argv.clone()).output_files(relative_paths(&["roland"]).collect()),
preserved_work_root.clone(),
false,
None,
None,
)
.await;
result.unwrap();
assert!(preserved_work_root.exists());
// Collect all of the top level sub-dirs under our test workdir.
let subdirs = testutil::file::list_dir(&preserved_work_root);
assert_eq!(subdirs.len(), 1);
// Then look for a file like e.g. `/tmp/abc1234/process-execution7zt4pH/roland`
let rolands_path = preserved_work_root.join(&subdirs[0]).join("roland");
assert!(rolands_path.exists());
// Ensure that when a directory is preserved, a __run.sh file is created with the process's
// command line and environment variables.
let run_script_path = preserved_work_root.join(&subdirs[0]).join("__run.sh");
assert!(run_script_path.exists());
let script_metadata = std::fs::metadata(&run_script_path).unwrap();
// Ensure the script is executable.
assert!(USER_EXECUTABLE_MODE & script_metadata.permissions().mode() != 0);
// Ensure the bash command line is provided.
let bytes_quoted_command_line = bash::escape(&bash_contents);
let quoted_command_line = str::from_utf8(&bytes_quoted_command_line).unwrap();
assert!(std::fs::read_to_string(&run_script_path)
.unwrap()
.contains(quoted_command_line));
}
#[tokio::test]
async fn test_directory_preservation_error() {
WorkunitStore::setup_for_tests();
let preserved_work_tmpdir = TempDir::new().unwrap();
let preserved_work_root = preserved_work_tmpdir.path().to_owned();
assert!(preserved_work_root.exists());
assert_eq!(testutil::file::list_dir(&preserved_work_root).len(), 0);
run_command_locally_in_dir(
Process::new(vec!["doesnotexist".to_owned()]),
preserved_work_root.clone(),
false,
None,
None,
)
.await
.expect_err("Want process to fail");
assert!(preserved_work_root.exists());
// Collect all of the top level sub-dirs under our test workdir.
assert_eq!(testutil::file::list_dir(&preserved_work_root).len(), 1);
}
#[tokio::test]
async fn all_containing_directories_for_outputs_are_created() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(
Process::new(vec![
find_bash(),
"-c".to_owned(),
format!(
// mkdir would normally fail, since birds/ doesn't yet exist, as would echo, since cats/
// does not exist, but we create the containing directories for all outputs before the
// process executes.
"/bin/mkdir birds/falcons && echo -n {} > cats/roland",
TestData::roland().string()
),
])
.output_files(relative_paths(&["cats/roland"]).collect())
.output_directories(relative_paths(&["birds/falcons"]).collect()),
)
.await
.unwrap();
assert_eq!(result.stdout_bytes, "".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(
result.original.output_directory,
TestDirectory::nested_dir_and_file().digest()
);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
async fn output_empty_dir() {
WorkunitStore::setup_for_tests();
let result = run_command_locally(
Process::new(vec![
find_bash(),
"-c".to_owned(),
"/bin/mkdir falcons".to_string(),
])
.output_directories(relative_paths(&["falcons"]).collect()),
)
.await
.unwrap();
assert_eq!(result.stdout_bytes, "".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(
result.original.output_directory,
TestDirectory::containing_falcons_dir().digest()
);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
#[tokio::test]
async fn timeout() {
WorkunitStore::setup_for_tests();
let argv = vec![
find_bash(),
"-c".to_owned(),
"/bin/sleep 0.2; /bin/echo -n 'European Burmese'".to_string(),
];
let mut process = Process::new(argv);
process.timeout = Some(Duration::from_millis(100));
process.description = "sleepy-cat".to_string();
let result = run_command_locally(process).await.unwrap();
assert_eq!(result.original.exit_code, -15);
let error_msg = String::from_utf8(result.stdout_bytes.to_vec()).unwrap();
assert_that(&error_msg).contains("Exceeded timeout");
assert_that(&error_msg).contains("sleepy-cat");
}
#[tokio::test]
async fn working_directory() {
WorkunitStore::setup_for_tests();
let store_dir = TempDir::new().unwrap();
let executor = task_executor::Executor::new();
let store = Store::local_only(executor.clone(), store_dir.path()).unwrap();
// Prepare the store to contain /cats/roland, because the EPR needs to materialize it and then run
// from the ./cats directory.
store
.store_file_bytes(TestData::roland().bytes(), false)
.await
.expect("Error saving file bytes");
store
.record_directory(&TestDirectory::containing_roland().directory(), true)
.await
.expect("Error saving directory");
store
.record_directory(&TestDirectory::nested().directory(), true)
.await
.expect("Error saving directory");
let work_dir = TempDir::new().unwrap();
let mut process = Process::new(vec![find_bash(), "-c".to_owned(), "/bin/ls".to_string()]);
process.working_directory = Some(RelativePath::new("cats").unwrap());
process.input_files = TestDirectory::nested().digest();
process.timeout = one_second();
process.description = "confused-cat".to_string();
let result = run_command_locally_in_dir(
process,
work_dir.path().to_owned(),
true,
Some(store),
Some(executor),
)
.await
.unwrap();
assert_eq!(result.stdout_bytes, "roland\n".as_bytes());
assert_eq!(result.stderr_bytes, "".as_bytes());
assert_eq!(result.original.exit_code, 0);
assert_eq!(result.original.output_directory, EMPTY_DIGEST);
assert_eq!(result.original.platform, Platform::current().unwrap());
}
async fn run_command_locally(req: Process) -> Result<LocalTestResult, String> {
let work_dir = TempDir::new().unwrap();
let work_dir_path = work_dir.path().to_owned();
run_command_locally_in_dir(req, work_dir_path, true, None, None).await
}
async fn run_command_locally_in_dir(
req: Process,
dir: PathBuf,
cleanup: bool,
store: Option<Store>,
executor: Option<task_executor::Executor>,
) -> Result<LocalTestResult, String> {
let store_dir = TempDir::new().unwrap();
let named_cache_dir = TempDir::new().unwrap();
let executor = executor.unwrap_or_else(|| task_executor::Executor::new());
let store =
store.unwrap_or_else(|| Store::local_only(executor.clone(), store_dir.path()).unwrap());
let runner = crate::local::CommandRunner::new(
store.clone(),
executor.clone(),
dir,
NamedCaches::new(named_cache_dir.path().to_owned()),
cleanup,
);
let original = runner.run(req.into(), Context::default()).await?;
let stdout_bytes: Vec<u8> = store
.load_file_bytes_with(original.stdout_digest, |bytes| bytes.into())
.await?
.unwrap()
.0;
let stderr_bytes: Vec<u8> = store
.load_file_bytes_with(original.stderr_digest, |bytes| bytes.into())
.await?
.unwrap()
.0;
Ok(LocalTestResult {
original,
stdout_bytes,
stderr_bytes,
})
}
fn one_second() -> Option<Duration> {
Some(Duration::from_millis(1000))
}
| 29.343499 | 100 | 0.67819 |
08869e42babfaf7379818436f53c33ab5aba1a05
| 19,197 |
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use anyhow::{bail, Context, Result};
use bytes::Bytes;
use futures_util::future::FutureExt;
use reqwest::{
header::{HeaderMap, HeaderValue},
StatusCode,
};
use serde::de::DeserializeOwned;
use serde::Serialize;
use tokio::{
sync::{oneshot, RwLock},
time,
};
use tracing::{debug, error, info, warn};
use webdav_handler::fs::{DavDirEntry, DavMetaData, FsFuture, FsResult};
mod model;
use model::*;
pub use model::{AliyunFile, DateTime, FileType};
const API_BASE_URL: &str = "https://api.aliyundrive.com";
const ORIGIN: &str = "https://www.aliyundrive.com";
const REFERER: &str = "https://www.aliyundrive.com/";
const UA: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36";
#[derive(Debug, Clone)]
struct Credentials {
refresh_token: String,
access_token: Option<String>,
}
#[derive(Debug, Clone)]
pub struct AliyunDrive {
client: reqwest::Client,
credentials: Arc<RwLock<Credentials>>,
drive_id: Option<String>,
workdir: Option<PathBuf>,
}
impl AliyunDrive {
pub async fn new(refresh_token: String, workdir: Option<PathBuf>) -> Result<Self> {
let credentials = Credentials {
refresh_token,
access_token: None,
};
let mut headers = HeaderMap::new();
headers.insert("Origin", HeaderValue::from_static(ORIGIN));
headers.insert("Referer", HeaderValue::from_static(REFERER));
let client = reqwest::Client::builder()
.user_agent(UA)
.default_headers(headers)
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(30))
.build()?;
let mut drive = Self {
client,
credentials: Arc::new(RwLock::new(credentials)),
drive_id: None,
workdir,
};
let (tx, rx) = oneshot::channel();
// schedule update token task
let client = drive.clone();
let refresh_token_from_file = if let Some(dir) = drive.workdir.as_ref() {
tokio::fs::read_to_string(dir.join("refresh_token"))
.await
.ok()
} else {
None
};
tokio::spawn(async move {
let mut delay_seconds = 7000;
match client
.do_refresh_token_with_retry(refresh_token_from_file)
.await
{
Ok(res) => {
// token usually expires in 7200s, refresh earlier
delay_seconds = res.expires_in - 200;
if tx.send(res.default_drive_id).is_err() {
error!("send default drive id failed");
}
}
Err(err) => {
error!("refresh token failed: {}", err);
tx.send(String::new()).unwrap();
}
}
loop {
time::sleep(time::Duration::from_secs(delay_seconds)).await;
if let Err(err) = client.do_refresh_token_with_retry(None).await {
error!("refresh token failed: {}", err);
}
}
});
let drive_id = rx.await?;
if drive_id.is_empty() {
bail!("get default drive id failed");
}
info!(drive_id = %drive_id, "found default drive");
drive.drive_id = Some(drive_id);
Ok(drive)
}
async fn save_refresh_token(&self, refresh_token: &str) -> Result<()> {
if let Some(dir) = self.workdir.as_ref() {
tokio::fs::create_dir_all(dir).await?;
let refresh_token_file = dir.join("refresh_token");
tokio::fs::write(refresh_token_file, refresh_token).await?;
}
Ok(())
}
async fn do_refresh_token(&self, refresh_token: &str) -> Result<RefreshTokenResponse> {
let mut data = HashMap::new();
data.insert("refresh_token", refresh_token);
let res = self
.client
.post("https://websv.aliyundrive.com/token/refresh")
.json(&data)
.send()
.await?;
match res.error_for_status_ref() {
Ok(_) => {
let res = res.json::<RefreshTokenResponse>().await?;
let mut cred = self.credentials.write().await;
cred.refresh_token = res.refresh_token.clone();
cred.access_token = Some(res.access_token.clone());
info!(
refresh_token = %res.refresh_token,
nick_name = %res.nick_name,
"refresh token succeed"
);
if let Err(err) = self.save_refresh_token(&res.refresh_token).await {
error!(error = %err, "save refresh token failed");
}
Ok(res)
}
Err(err) => {
let msg = res.text().await?;
let context = format!("{}: {}", err, msg);
Err(err).context(context)
}
}
}
async fn do_refresh_token_with_retry(
&self,
refresh_token_from_file: Option<String>,
) -> Result<RefreshTokenResponse> {
let mut last_err = None;
let mut refresh_token = self.refresh_token().await;
for _ in 0..10 {
match self.do_refresh_token(&refresh_token).await {
Ok(res) => return Ok(res),
Err(err) => {
let mut should_retry = match err.downcast_ref::<reqwest::Error>() {
Some(e) => e.is_connect() || e.is_timeout(),
None => false,
};
// retry if command line refresh_token is invalid but we also have
// refresh_token from file
if let Some(refresh_token_from_file) = refresh_token_from_file.as_ref() {
if !should_retry && &refresh_token != refresh_token_from_file {
refresh_token = refresh_token_from_file.trim().to_string();
should_retry = true;
}
}
if should_retry {
warn!(error = %err, "refresh token failed, will wait and retry");
last_err = Some(err);
time::sleep(Duration::from_secs(1)).await;
continue;
} else {
last_err = Some(err);
}
}
}
}
Err(last_err.unwrap())
}
async fn refresh_token(&self) -> String {
let cred = self.credentials.read().await;
cred.refresh_token.clone()
}
async fn access_token(&self) -> Result<String> {
let cred = self.credentials.read().await;
Ok(cred.access_token.clone().context("missing access_token")?)
}
fn drive_id(&self) -> Result<&str> {
self.drive_id.as_deref().context("missing drive_id")
}
async fn request<T, U>(&self, url: String, req: &T) -> Result<Option<U>>
where
T: Serialize + ?Sized,
U: DeserializeOwned,
{
let mut access_token = self.access_token().await?;
let url = reqwest::Url::parse(&url)?;
let res = self
.client
.post(url.clone())
.bearer_auth(&access_token)
.json(&req)
.send()
.await?
.error_for_status();
match res {
Ok(res) => {
if res.status() == StatusCode::NO_CONTENT {
return Ok(None);
}
let res = res.json::<U>().await?;
Ok(Some(res))
}
Err(err) => {
match err.status() {
Some(
status_code
@
(StatusCode::UNAUTHORIZED
| StatusCode::INTERNAL_SERVER_ERROR
| StatusCode::BAD_GATEWAY
| StatusCode::SERVICE_UNAVAILABLE
| StatusCode::GATEWAY_TIMEOUT),
) => {
if status_code == StatusCode::UNAUTHORIZED {
// refresh token and retry
let token_res = self.do_refresh_token_with_retry(None).await?;
access_token = token_res.access_token;
} else {
// wait for a while and retry
time::sleep(Duration::from_secs(1)).await;
}
let res = self
.client
.post(url)
.bearer_auth(&access_token)
.json(&req)
.send()
.await?
.error_for_status()?;
if res.status() == StatusCode::NO_CONTENT {
return Ok(None);
}
let res = res.json::<U>().await?;
Ok(Some(res))
}
_ => Err(err.into()),
}
}
}
}
pub async fn get_by_path(&self, path: &str) -> Result<Option<AliyunFile>> {
let drive_id = self.drive_id()?;
debug!(drive_id = %drive_id, path = %path, "get file by path");
if path == "/" || path.is_empty() {
return Ok(Some(AliyunFile::new_root()));
}
let req = GetFileByPathRequest {
drive_id,
file_path: path,
};
let res: Result<AliyunFile> = self
.request(format!("{}/v2/file/get_by_path", API_BASE_URL), &req)
.await
.and_then(|res| res.context("expect response"));
match res {
Ok(file) => Ok(Some(file)),
Err(err) => {
if let Some(req_err) = err.downcast_ref::<reqwest::Error>() {
if matches!(req_err.status(), Some(StatusCode::NOT_FOUND)) {
Ok(None)
} else {
Err(err)
}
} else {
Err(err)
}
}
}
}
pub async fn list_all(&self, parent_file_id: &str) -> Result<Vec<AliyunFile>> {
let mut files = Vec::new();
let mut marker = None;
loop {
let res = self.list(parent_file_id, marker.as_deref()).await?;
files.extend(res.items.into_iter());
if res.next_marker.is_empty() {
break;
}
marker = Some(res.next_marker);
}
Ok(files)
}
pub async fn list(
&self,
parent_file_id: &str,
marker: Option<&str>,
) -> Result<ListFileResponse> {
let drive_id = self.drive_id()?;
debug!(drive_id = %drive_id, parent_file_id = %parent_file_id, marker = ?marker, "list file");
let req = ListFileRequest {
drive_id,
parent_file_id,
limit: 200,
all: false,
image_thumbnail_process: "image/resize,w_400/format,jpeg",
image_url_process: "image/resize,w_1920/format,jpeg",
video_thumbnail_process: "video/snapshot,t_0,f_jpg,ar_auto,w_300",
fields: "*",
order_by: "updated_at",
order_direction: "DESC",
marker,
};
self.request(format!("{}/adrive/v3/file/list", API_BASE_URL), &req)
.await
.and_then(|res| res.context("expect response"))
}
pub async fn download(&self, url: &str, start_pos: u64, size: usize) -> Result<Bytes> {
use reqwest::header::RANGE;
let end_pos = start_pos + size as u64 - 1;
debug!(url = %url, start = start_pos, end = end_pos, "download file");
let range = format!("bytes={}-{}", start_pos, end_pos);
let res = self
.client
.get(url)
.header(RANGE, range)
.send()
.await?
.error_for_status()?;
Ok(res.bytes().await?)
}
pub async fn get_download_url(&self, file_id: &str) -> Result<String> {
debug!(file_id = %file_id, "get download url");
let req = GetFileDownloadUrlRequest {
drive_id: self.drive_id()?,
file_id,
};
let res: GetFileDownloadUrlResponse = self
.request(format!("{}/v2/file/get_download_url", API_BASE_URL), &req)
.await?
.context("expect response")?;
Ok(res.url)
}
async fn trash(&self, file_id: &str) -> Result<()> {
debug!(file_id = %file_id, "trash file");
let req = TrashRequest {
drive_id: self.drive_id()?,
file_id,
};
let _res: Option<serde::de::IgnoredAny> = self
.request(format!("{}/v2/recyclebin/trash", API_BASE_URL), &req)
.await?;
Ok(())
}
async fn delete_file(&self, file_id: &str) -> Result<()> {
debug!(file_id = %file_id, "delete file");
let req = TrashRequest {
drive_id: self.drive_id()?,
file_id,
};
let _res: Option<serde::de::IgnoredAny> = self
.request(format!("{}/v2/file/delete", API_BASE_URL), &req)
.await?;
Ok(())
}
pub async fn remove_file(&self, file_id: &str, trash: bool) -> Result<()> {
if trash {
self.trash(file_id).await?;
} else {
self.delete_file(file_id).await?;
}
Ok(())
}
pub async fn create_folder(&self, parent_file_id: &str, name: &str) -> Result<()> {
debug!(parent_file_id = %parent_file_id, name = %name, "create folder");
let req = CreateFolderRequest {
check_name_mode: "refuse",
drive_id: self.drive_id()?,
name,
parent_file_id,
r#type: "folder",
};
let _res: Option<serde::de::IgnoredAny> = self
.request(
format!("{}/adrive/v2/file/createWithFolders", API_BASE_URL),
&req,
)
.await?;
Ok(())
}
pub async fn rename_file(&self, file_id: &str, name: &str) -> Result<()> {
debug!(file_id = %file_id, name = %name, "rename file");
let req = RenameFileRequest {
check_name_mode: "refuse",
drive_id: self.drive_id()?,
file_id,
name,
};
let _res: Option<serde::de::IgnoredAny> = self
.request(format!("{}/v3/file/update", API_BASE_URL), &req)
.await?;
Ok(())
}
pub async fn move_file(
&self,
file_id: &str,
to_parent_file_id: &str,
new_name: Option<&str>,
) -> Result<()> {
debug!(file_id = %file_id, to_parent_file_id = %to_parent_file_id, "move file");
let drive_id = self.drive_id()?;
let req = MoveFileRequest {
drive_id,
file_id,
to_drive_id: drive_id,
to_parent_file_id,
new_name,
};
let _res: Option<serde::de::IgnoredAny> = self
.request(format!("{}/v3/file/move", API_BASE_URL), &req)
.await?;
Ok(())
}
pub async fn copy_file(
&self,
file_id: &str,
to_parent_file_id: &str,
new_name: Option<&str>,
) -> Result<()> {
debug!(file_id = %file_id, to_parent_file_id = %to_parent_file_id, "copy file");
let drive_id = self.drive_id()?;
let req = CopyFileRequest {
drive_id,
file_id,
to_parent_file_id,
new_name,
};
let _res: Option<serde::de::IgnoredAny> = self
.request(format!("{}/v2/file/copy", API_BASE_URL), &req)
.await?;
Ok(())
}
pub async fn create_file_with_proof(
&self,
name: &str,
parent_file_id: &str,
size: u64,
chunk_count: u64,
) -> Result<CreateFileWithProofResponse> {
debug!(name = %name, parent_file_id = %parent_file_id, size = size, "create file with proof");
let drive_id = self.drive_id()?;
let part_info_list = (1..=chunk_count)
.map(|part_number| PartInfo {
part_number,
upload_url: String::new(),
})
.collect();
let req = CreateFileWithProofRequest {
check_name_mode: "refuse",
content_hash: "",
content_hash_name: "none",
drive_id,
name,
parent_file_id,
proof_code: "",
proof_version: "v1",
size,
part_info_list,
r#type: "file",
};
let res: CreateFileWithProofResponse = self
.request(format!("{}/v2/file/create_with_proof", API_BASE_URL), &req)
.await?
.context("expect response")?;
Ok(res)
}
pub async fn complete_file_upload(&self, file_id: &str, upload_id: &str) -> Result<()> {
debug!(file_id = %file_id, upload_id = %upload_id, "complete file upload");
let drive_id = self.drive_id()?;
let req = CompleteUploadRequest {
drive_id,
file_id,
upload_id,
};
let _res: Option<serde::de::IgnoredAny> = self
.request(format!("{}/v2/file/complete", API_BASE_URL), &req)
.await?;
Ok(())
}
pub async fn upload(&self, url: &str, body: Bytes) -> Result<()> {
self.client
.put(url)
.body(body)
.send()
.await?
.error_for_status()?;
Ok(())
}
pub async fn get_quota(&self) -> Result<(u64, u64)> {
let drive_id = self.drive_id()?;
let mut data = HashMap::new();
data.insert("drive_id", drive_id);
let res: GetDriveResponse = self
.request(format!("{}/v2/drive/get", API_BASE_URL), &data)
.await?
.context("expect response")?;
Ok((res.used_size, res.total_size))
}
}
impl DavMetaData for AliyunFile {
fn len(&self) -> u64 {
self.size
}
fn modified(&self) -> FsResult<SystemTime> {
Ok(*self.updated_at)
}
fn is_dir(&self) -> bool {
matches!(self.r#type, FileType::Folder)
}
fn created(&self) -> FsResult<SystemTime> {
Ok(*self.created_at)
}
}
impl DavDirEntry for AliyunFile {
fn name(&self) -> Vec<u8> {
self.name.as_bytes().to_vec()
}
fn metadata(&self) -> FsFuture<Box<dyn DavMetaData>> {
async move { Ok(Box::new(self.clone()) as Box<dyn DavMetaData>) }.boxed()
}
}
| 33.678947 | 141 | 0.49763 |
89b0f3fb9c77e5d7dfea122d3750a10514b67186
| 301 |
pub mod keys;
pub mod pok_sig;
pub mod signature;
pub mod prelude {
pub use super::keys::{generate, PublicKey, SecretKey};
pub use super::pok_sig::{
PoKOfSignature, PoKOfSignatureProof, ProofG1, ProverCommittedG1, ProverCommittingG1,
};
pub use super::signature::Signature;
}
| 25.083333 | 92 | 0.710963 |
f8c4dc895dec55e8e2eb13d6057d6755fcd5b397
| 4,180 |
//! Shadowsocks SOCKS4/4a Local Server
use std::{
io::{self, ErrorKind},
net::SocketAddr,
sync::Arc,
};
use log::{debug, error, trace, warn};
use shadowsocks::config::Mode;
use tokio::{
io::{AsyncWriteExt, BufReader},
net::TcpStream,
};
use crate::local::{
context::ServiceContext,
loadbalancing::PingBalancer,
net::AutoProxyClientStream,
utils::establish_tcp_tunnel,
};
use crate::local::socks::socks4::{
Address,
Command,
Error as Socks4Error,
HandshakeRequest,
HandshakeResponse,
ResultCode,
};
pub struct Socks4TcpHandler {
context: Arc<ServiceContext>,
balancer: PingBalancer,
mode: Mode,
}
impl Socks4TcpHandler {
pub fn new(context: Arc<ServiceContext>, balancer: PingBalancer, mode: Mode) -> Socks4TcpHandler {
Socks4TcpHandler {
context,
balancer,
mode,
}
}
pub async fn handle_socks4_client(self, stream: TcpStream, peer_addr: SocketAddr) -> io::Result<()> {
// 1. Handshake
// NOTE: Wraps it with BufReader for reading NULL terminated information in HandshakeRequest
let mut s = BufReader::new(stream);
let handshake_req = match HandshakeRequest::read_from(&mut s).await {
Ok(r) => r,
Err(Socks4Error::IoError(ref err)) if err.kind() == ErrorKind::UnexpectedEof => {
trace!("socks4 handshake early eof. peer: {}", peer_addr);
return Ok(());
}
Err(err) => {
error!("socks4 handshake error: {}", err);
return Err(err.into());
}
};
trace!("socks4 {:?} peer: {}", handshake_req, peer_addr);
match handshake_req.cd {
Command::Connect => {
debug!("CONNECT {}", handshake_req.dst);
self.handle_socks4_connect(s, peer_addr, handshake_req.dst).await
}
Command::Bind => {
warn!("BIND is not supported");
let handshake_rsp = HandshakeResponse::new(ResultCode::RequestRejectedOrFailed);
handshake_rsp.write_to(&mut s).await?;
Ok(())
}
}
}
async fn handle_socks4_connect(
self,
mut stream: BufReader<TcpStream>,
peer_addr: SocketAddr,
target_addr: Address,
) -> io::Result<()> {
if !self.mode.enable_tcp() {
warn!("TCP CONNECT is disabled");
let handshake_rsp = HandshakeResponse::new(ResultCode::RequestRejectedOrFailed);
handshake_rsp.write_to(&mut stream).await?;
return Ok(());
}
let server = self.balancer.best_tcp_server();
let svr_cfg = server.server_config();
let target_addr = target_addr.into();
let mut remote = match AutoProxyClientStream::connect(self.context, &server, &target_addr).await {
Ok(remote) => {
// Tell the client that we are ready
let handshake_rsp = HandshakeResponse::new(ResultCode::RequestGranted);
handshake_rsp.write_to(&mut stream).await?;
trace!("sent header: {:?}", handshake_rsp);
remote
}
Err(err) => {
let result_code = match err.kind() {
ErrorKind::ConnectionRefused => ResultCode::RequestRejectedCannotConnect,
ErrorKind::ConnectionAborted => ResultCode::RequestRejectedCannotConnect,
_ => ResultCode::RequestRejectedOrFailed,
};
let handshake_rsp = HandshakeResponse::new(result_code);
handshake_rsp.write_to(&mut stream).await?;
return Err(err);
}
};
// NOTE: Transfer all buffered data before unwrap, or these data will be lost
let buffer = stream.buffer();
if !buffer.is_empty() {
remote.write_all(buffer).await?;
}
// UNWRAP.
let mut stream = stream.into_inner();
establish_tcp_tunnel(svr_cfg, &mut stream, &mut remote, peer_addr, &target_addr).await
}
}
| 30.289855 | 106 | 0.570096 |
4bd2663607637ddee48e1f1b543b8069b4fedb04
| 4,400 |
use crate::babelify::{extract_class_body_span, Babelify, Context};
use copyless::BoxHelper;
use swc_estree_ast::{
ClassBody, ClassDeclaration, Declaration, FunctionDeclaration, VariableDeclaration,
VariableDeclarationKind, VariableDeclarator,
};
use swc_ecma_ast::{ClassDecl, Decl, FnDecl, VarDecl, VarDeclKind, VarDeclarator};
impl Babelify for Decl {
type Output = Declaration;
fn babelify(self, ctx: &Context) -> Self::Output {
match self {
Decl::Class(d) => Declaration::ClassDecl(d.babelify(ctx)),
Decl::Fn(d) => Declaration::FuncDecl(d.babelify(ctx)),
Decl::Var(d) => Declaration::VarDecl(d.babelify(ctx)),
Decl::TsInterface(d) => Declaration::TSInterfaceDecl(d.babelify(ctx)),
Decl::TsTypeAlias(d) => Declaration::TSTypeAliasDecl(d.babelify(ctx)),
Decl::TsEnum(d) => Declaration::TSEnumDecl(d.babelify(ctx)),
Decl::TsModule(d) => Declaration::TSModuleDecl(d.babelify(ctx)),
}
}
}
impl Babelify for FnDecl {
type Output = FunctionDeclaration;
fn babelify(self, ctx: &Context) -> Self::Output {
let func = self.function.babelify(ctx);
FunctionDeclaration {
base: func.base,
id: Some(self.ident.babelify(ctx)),
params: func.params,
body: func.body,
generator: func.generator,
is_async: func.is_async,
expression: false,
return_type: func.return_type,
type_parameters: func.type_parameters,
}
}
}
impl Babelify for ClassDecl {
type Output = ClassDeclaration;
fn babelify(self, ctx: &Context) -> Self::Output {
let is_abstract = self.class.is_abstract;
// NOTE: The body field needs a bit of special handling because babel
// represents the body as a node, whereas swc represents it as a vector of
// statements. This means that swc does not have a span corresponding the the
// class body base node for babel. To solve this, we generate a new span
// starting from the end of the identifier to the end of the body.
// For example,
//
// babel ClassBody node starts here
// v
// class MyClass {
// a = 0;
// }
// ^
// and ends here
//
// TODO: Verify that this implementation of class body span is correct.
// It may need to be modified to take into account implements, super classes,
// etc.
let body_span = extract_class_body_span(&self.class, &ctx);
let class = self.class.babelify(ctx);
ClassDeclaration {
base: class.base,
id: self.ident.babelify(ctx),
super_class: class.super_class.map(|s| Box::alloc().init(*s)),
body: ClassBody {
base: ctx.base(body_span),
..class.body
},
decorators: class.decorators,
is_abstract: Some(is_abstract),
declare: Some(self.declare),
implements: class.implements,
mixins: class.mixins,
super_type_parameters: class.super_type_parameters,
type_parameters: class.type_parameters,
}
}
}
impl Babelify for VarDecl {
type Output = VariableDeclaration;
fn babelify(self, ctx: &Context) -> Self::Output {
VariableDeclaration {
base: ctx.base(self.span),
kind: self.kind.babelify(ctx),
declare: Some(self.declare),
declarations: self.decls.babelify(ctx),
}
}
}
impl Babelify for VarDeclKind {
type Output = VariableDeclarationKind;
fn babelify(self, _ctx: &Context) -> Self::Output {
match self {
VarDeclKind::Var => VariableDeclarationKind::Var,
VarDeclKind::Let => VariableDeclarationKind::Let,
VarDeclKind::Const => VariableDeclarationKind::Const,
}
}
}
impl Babelify for VarDeclarator {
type Output = VariableDeclarator;
fn babelify(self, ctx: &Context) -> Self::Output {
VariableDeclarator {
base: ctx.base(self.span),
id: self.name.babelify(ctx).into(),
init: self.init.map(|i| Box::alloc().init(i.babelify(ctx).into())),
definite: Some(self.definite),
}
}
}
| 34.920635 | 87 | 0.595682 |
16cee944ddae90e0bb360de3e3ab5c49e45d68c8
| 79,275 |
// This file is generated by rust-protobuf 2.0.4. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(trivial_casts)]
#![allow(unsafe_code)]
#![allow(unused_imports)]
#![allow(unused_results)]
use protobuf::Message as Message_imported_for_functions;
use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions;
#[derive(PartialEq,Clone,Default)]
pub struct NotLeader {
// message fields
pub region_id: u64,
pub leader: ::protobuf::SingularPtrField<super::metapb::Peer>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl NotLeader {
pub fn new() -> NotLeader {
::std::default::Default::default()
}
// uint64 region_id = 1;
pub fn clear_region_id(&mut self) {
self.region_id = 0;
}
// Param is passed by value, moved
pub fn set_region_id(&mut self, v: u64) {
self.region_id = v;
}
pub fn get_region_id(&self) -> u64 {
self.region_id
}
// .metapb.Peer leader = 2;
pub fn clear_leader(&mut self) {
self.leader.clear();
}
pub fn has_leader(&self) -> bool {
self.leader.is_some()
}
// Param is passed by value, moved
pub fn set_leader(&mut self, v: super::metapb::Peer) {
self.leader = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_leader(&mut self) -> &mut super::metapb::Peer {
if self.leader.is_none() {
self.leader.set_default();
}
self.leader.as_mut().unwrap()
}
// Take field
pub fn take_leader(&mut self) -> super::metapb::Peer {
self.leader.take().unwrap_or_else(|| super::metapb::Peer::new())
}
pub fn get_leader(&self) -> &super::metapb::Peer {
self.leader.as_ref().unwrap_or_else(|| super::metapb::Peer::default_instance())
}
}
impl ::protobuf::Message for NotLeader {
fn is_initialized(&self) -> bool {
for v in &self.leader {
if !v.is_initialized() {
return false;
}
};
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
if wire_type != ::protobuf::wire_format::WireTypeVarint {
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
}
let tmp = is.read_uint64()?;
self.region_id = tmp;
},
2 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.leader)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if self.region_id != 0 {
my_size += ::protobuf::rt::value_size(1, self.region_id, ::protobuf::wire_format::WireTypeVarint);
}
if let Some(ref v) = self.leader.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if self.region_id != 0 {
os.write_uint64(1, self.region_id)?;
}
if let Some(ref v) = self.leader.as_ref() {
os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> NotLeader {
NotLeader::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint64>(
"region_id",
|m: &NotLeader| { &m.region_id },
|m: &mut NotLeader| { &mut m.region_id },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<super::metapb::Peer>>(
"leader",
|m: &NotLeader| { &m.leader },
|m: &mut NotLeader| { &mut m.leader },
));
::protobuf::reflect::MessageDescriptor::new::<NotLeader>(
"NotLeader",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static NotLeader {
static mut instance: ::protobuf::lazy::Lazy<NotLeader> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const NotLeader,
};
unsafe {
instance.get(NotLeader::new)
}
}
}
impl ::protobuf::Clear for NotLeader {
fn clear(&mut self) {
self.clear_region_id();
self.clear_leader();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for NotLeader {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for NotLeader {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default)]
pub struct StoreNotMatch {
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl StoreNotMatch {
pub fn new() -> StoreNotMatch {
::std::default::Default::default()
}
}
impl ::protobuf::Message for StoreNotMatch {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> StoreNotMatch {
StoreNotMatch::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let fields = ::std::vec::Vec::new();
::protobuf::reflect::MessageDescriptor::new::<StoreNotMatch>(
"StoreNotMatch",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static StoreNotMatch {
static mut instance: ::protobuf::lazy::Lazy<StoreNotMatch> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const StoreNotMatch,
};
unsafe {
instance.get(StoreNotMatch::new)
}
}
}
impl ::protobuf::Clear for StoreNotMatch {
fn clear(&mut self) {
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for StoreNotMatch {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for StoreNotMatch {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default)]
pub struct RegionNotFound {
// message fields
pub region_id: u64,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl RegionNotFound {
pub fn new() -> RegionNotFound {
::std::default::Default::default()
}
// uint64 region_id = 1;
pub fn clear_region_id(&mut self) {
self.region_id = 0;
}
// Param is passed by value, moved
pub fn set_region_id(&mut self, v: u64) {
self.region_id = v;
}
pub fn get_region_id(&self) -> u64 {
self.region_id
}
}
impl ::protobuf::Message for RegionNotFound {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
if wire_type != ::protobuf::wire_format::WireTypeVarint {
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
}
let tmp = is.read_uint64()?;
self.region_id = tmp;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if self.region_id != 0 {
my_size += ::protobuf::rt::value_size(1, self.region_id, ::protobuf::wire_format::WireTypeVarint);
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if self.region_id != 0 {
os.write_uint64(1, self.region_id)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> RegionNotFound {
RegionNotFound::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint64>(
"region_id",
|m: &RegionNotFound| { &m.region_id },
|m: &mut RegionNotFound| { &mut m.region_id },
));
::protobuf::reflect::MessageDescriptor::new::<RegionNotFound>(
"RegionNotFound",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static RegionNotFound {
static mut instance: ::protobuf::lazy::Lazy<RegionNotFound> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const RegionNotFound,
};
unsafe {
instance.get(RegionNotFound::new)
}
}
}
impl ::protobuf::Clear for RegionNotFound {
fn clear(&mut self) {
self.clear_region_id();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for RegionNotFound {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for RegionNotFound {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default)]
pub struct KeyNotInRegion {
// message fields
pub key: ::std::vec::Vec<u8>,
pub region_id: u64,
pub start_key: ::std::vec::Vec<u8>,
pub end_key: ::std::vec::Vec<u8>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl KeyNotInRegion {
pub fn new() -> KeyNotInRegion {
::std::default::Default::default()
}
// bytes key = 1;
pub fn clear_key(&mut self) {
self.key.clear();
}
// Param is passed by value, moved
pub fn set_key(&mut self, v: ::std::vec::Vec<u8>) {
self.key = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_key(&mut self) -> &mut ::std::vec::Vec<u8> {
&mut self.key
}
// Take field
pub fn take_key(&mut self) -> ::std::vec::Vec<u8> {
::std::mem::replace(&mut self.key, ::std::vec::Vec::new())
}
pub fn get_key(&self) -> &[u8] {
&self.key
}
// uint64 region_id = 2;
pub fn clear_region_id(&mut self) {
self.region_id = 0;
}
// Param is passed by value, moved
pub fn set_region_id(&mut self, v: u64) {
self.region_id = v;
}
pub fn get_region_id(&self) -> u64 {
self.region_id
}
// bytes start_key = 3;
pub fn clear_start_key(&mut self) {
self.start_key.clear();
}
// Param is passed by value, moved
pub fn set_start_key(&mut self, v: ::std::vec::Vec<u8>) {
self.start_key = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_start_key(&mut self) -> &mut ::std::vec::Vec<u8> {
&mut self.start_key
}
// Take field
pub fn take_start_key(&mut self) -> ::std::vec::Vec<u8> {
::std::mem::replace(&mut self.start_key, ::std::vec::Vec::new())
}
pub fn get_start_key(&self) -> &[u8] {
&self.start_key
}
// bytes end_key = 4;
pub fn clear_end_key(&mut self) {
self.end_key.clear();
}
// Param is passed by value, moved
pub fn set_end_key(&mut self, v: ::std::vec::Vec<u8>) {
self.end_key = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_end_key(&mut self) -> &mut ::std::vec::Vec<u8> {
&mut self.end_key
}
// Take field
pub fn take_end_key(&mut self) -> ::std::vec::Vec<u8> {
::std::mem::replace(&mut self.end_key, ::std::vec::Vec::new())
}
pub fn get_end_key(&self) -> &[u8] {
&self.end_key
}
}
impl ::protobuf::Message for KeyNotInRegion {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.key)?;
},
2 => {
if wire_type != ::protobuf::wire_format::WireTypeVarint {
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
}
let tmp = is.read_uint64()?;
self.region_id = tmp;
},
3 => {
::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.start_key)?;
},
4 => {
::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.end_key)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if !self.key.is_empty() {
my_size += ::protobuf::rt::bytes_size(1, &self.key);
}
if self.region_id != 0 {
my_size += ::protobuf::rt::value_size(2, self.region_id, ::protobuf::wire_format::WireTypeVarint);
}
if !self.start_key.is_empty() {
my_size += ::protobuf::rt::bytes_size(3, &self.start_key);
}
if !self.end_key.is_empty() {
my_size += ::protobuf::rt::bytes_size(4, &self.end_key);
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if !self.key.is_empty() {
os.write_bytes(1, &self.key)?;
}
if self.region_id != 0 {
os.write_uint64(2, self.region_id)?;
}
if !self.start_key.is_empty() {
os.write_bytes(3, &self.start_key)?;
}
if !self.end_key.is_empty() {
os.write_bytes(4, &self.end_key)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> KeyNotInRegion {
KeyNotInRegion::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"key",
|m: &KeyNotInRegion| { &m.key },
|m: &mut KeyNotInRegion| { &mut m.key },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint64>(
"region_id",
|m: &KeyNotInRegion| { &m.region_id },
|m: &mut KeyNotInRegion| { &mut m.region_id },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"start_key",
|m: &KeyNotInRegion| { &m.start_key },
|m: &mut KeyNotInRegion| { &mut m.start_key },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"end_key",
|m: &KeyNotInRegion| { &m.end_key },
|m: &mut KeyNotInRegion| { &mut m.end_key },
));
::protobuf::reflect::MessageDescriptor::new::<KeyNotInRegion>(
"KeyNotInRegion",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static KeyNotInRegion {
static mut instance: ::protobuf::lazy::Lazy<KeyNotInRegion> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const KeyNotInRegion,
};
unsafe {
instance.get(KeyNotInRegion::new)
}
}
}
impl ::protobuf::Clear for KeyNotInRegion {
fn clear(&mut self) {
self.clear_key();
self.clear_region_id();
self.clear_start_key();
self.clear_end_key();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for KeyNotInRegion {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for KeyNotInRegion {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default)]
pub struct StaleEpoch {
// message fields
pub new_regions: ::protobuf::RepeatedField<super::metapb::Region>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl StaleEpoch {
pub fn new() -> StaleEpoch {
::std::default::Default::default()
}
// repeated .metapb.Region new_regions = 1;
pub fn clear_new_regions(&mut self) {
self.new_regions.clear();
}
// Param is passed by value, moved
pub fn set_new_regions(&mut self, v: ::protobuf::RepeatedField<super::metapb::Region>) {
self.new_regions = v;
}
// Mutable pointer to the field.
pub fn mut_new_regions(&mut self) -> &mut ::protobuf::RepeatedField<super::metapb::Region> {
&mut self.new_regions
}
// Take field
pub fn take_new_regions(&mut self) -> ::protobuf::RepeatedField<super::metapb::Region> {
::std::mem::replace(&mut self.new_regions, ::protobuf::RepeatedField::new())
}
pub fn get_new_regions(&self) -> &[super::metapb::Region] {
&self.new_regions
}
}
impl ::protobuf::Message for StaleEpoch {
fn is_initialized(&self) -> bool {
for v in &self.new_regions {
if !v.is_initialized() {
return false;
}
};
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.new_regions)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
for value in &self.new_regions {
let len = value.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
};
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
for v in &self.new_regions {
os.write_tag(1, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
};
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> StaleEpoch {
StaleEpoch::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<super::metapb::Region>>(
"new_regions",
|m: &StaleEpoch| { &m.new_regions },
|m: &mut StaleEpoch| { &mut m.new_regions },
));
::protobuf::reflect::MessageDescriptor::new::<StaleEpoch>(
"StaleEpoch",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static StaleEpoch {
static mut instance: ::protobuf::lazy::Lazy<StaleEpoch> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const StaleEpoch,
};
unsafe {
instance.get(StaleEpoch::new)
}
}
}
impl ::protobuf::Clear for StaleEpoch {
fn clear(&mut self) {
self.clear_new_regions();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for StaleEpoch {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for StaleEpoch {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default)]
pub struct ServerIsBusy {
// message fields
pub reason: ::std::string::String,
pub backoff_ms: u64,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl ServerIsBusy {
pub fn new() -> ServerIsBusy {
::std::default::Default::default()
}
// string reason = 1;
pub fn clear_reason(&mut self) {
self.reason.clear();
}
// Param is passed by value, moved
pub fn set_reason(&mut self, v: ::std::string::String) {
self.reason = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_reason(&mut self) -> &mut ::std::string::String {
&mut self.reason
}
// Take field
pub fn take_reason(&mut self) -> ::std::string::String {
::std::mem::replace(&mut self.reason, ::std::string::String::new())
}
pub fn get_reason(&self) -> &str {
&self.reason
}
// uint64 backoff_ms = 2;
pub fn clear_backoff_ms(&mut self) {
self.backoff_ms = 0;
}
// Param is passed by value, moved
pub fn set_backoff_ms(&mut self, v: u64) {
self.backoff_ms = v;
}
pub fn get_backoff_ms(&self) -> u64 {
self.backoff_ms
}
}
impl ::protobuf::Message for ServerIsBusy {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.reason)?;
},
2 => {
if wire_type != ::protobuf::wire_format::WireTypeVarint {
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
}
let tmp = is.read_uint64()?;
self.backoff_ms = tmp;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if !self.reason.is_empty() {
my_size += ::protobuf::rt::string_size(1, &self.reason);
}
if self.backoff_ms != 0 {
my_size += ::protobuf::rt::value_size(2, self.backoff_ms, ::protobuf::wire_format::WireTypeVarint);
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if !self.reason.is_empty() {
os.write_string(1, &self.reason)?;
}
if self.backoff_ms != 0 {
os.write_uint64(2, self.backoff_ms)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> ServerIsBusy {
ServerIsBusy::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"reason",
|m: &ServerIsBusy| { &m.reason },
|m: &mut ServerIsBusy| { &mut m.reason },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint64>(
"backoff_ms",
|m: &ServerIsBusy| { &m.backoff_ms },
|m: &mut ServerIsBusy| { &mut m.backoff_ms },
));
::protobuf::reflect::MessageDescriptor::new::<ServerIsBusy>(
"ServerIsBusy",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static ServerIsBusy {
static mut instance: ::protobuf::lazy::Lazy<ServerIsBusy> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ServerIsBusy,
};
unsafe {
instance.get(ServerIsBusy::new)
}
}
}
impl ::protobuf::Clear for ServerIsBusy {
fn clear(&mut self) {
self.clear_reason();
self.clear_backoff_ms();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for ServerIsBusy {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for ServerIsBusy {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default)]
pub struct StaleCommand {
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl StaleCommand {
pub fn new() -> StaleCommand {
::std::default::Default::default()
}
}
impl ::protobuf::Message for StaleCommand {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> StaleCommand {
StaleCommand::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let fields = ::std::vec::Vec::new();
::protobuf::reflect::MessageDescriptor::new::<StaleCommand>(
"StaleCommand",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static StaleCommand {
static mut instance: ::protobuf::lazy::Lazy<StaleCommand> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const StaleCommand,
};
unsafe {
instance.get(StaleCommand::new)
}
}
}
impl ::protobuf::Clear for StaleCommand {
fn clear(&mut self) {
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for StaleCommand {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for StaleCommand {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default)]
pub struct RaftEntryTooLarge {
// message fields
pub region_id: u64,
pub entry_size: u64,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl RaftEntryTooLarge {
pub fn new() -> RaftEntryTooLarge {
::std::default::Default::default()
}
// uint64 region_id = 1;
pub fn clear_region_id(&mut self) {
self.region_id = 0;
}
// Param is passed by value, moved
pub fn set_region_id(&mut self, v: u64) {
self.region_id = v;
}
pub fn get_region_id(&self) -> u64 {
self.region_id
}
// uint64 entry_size = 2;
pub fn clear_entry_size(&mut self) {
self.entry_size = 0;
}
// Param is passed by value, moved
pub fn set_entry_size(&mut self, v: u64) {
self.entry_size = v;
}
pub fn get_entry_size(&self) -> u64 {
self.entry_size
}
}
impl ::protobuf::Message for RaftEntryTooLarge {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
if wire_type != ::protobuf::wire_format::WireTypeVarint {
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
}
let tmp = is.read_uint64()?;
self.region_id = tmp;
},
2 => {
if wire_type != ::protobuf::wire_format::WireTypeVarint {
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
}
let tmp = is.read_uint64()?;
self.entry_size = tmp;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if self.region_id != 0 {
my_size += ::protobuf::rt::value_size(1, self.region_id, ::protobuf::wire_format::WireTypeVarint);
}
if self.entry_size != 0 {
my_size += ::protobuf::rt::value_size(2, self.entry_size, ::protobuf::wire_format::WireTypeVarint);
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if self.region_id != 0 {
os.write_uint64(1, self.region_id)?;
}
if self.entry_size != 0 {
os.write_uint64(2, self.entry_size)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> RaftEntryTooLarge {
RaftEntryTooLarge::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint64>(
"region_id",
|m: &RaftEntryTooLarge| { &m.region_id },
|m: &mut RaftEntryTooLarge| { &mut m.region_id },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint64>(
"entry_size",
|m: &RaftEntryTooLarge| { &m.entry_size },
|m: &mut RaftEntryTooLarge| { &mut m.entry_size },
));
::protobuf::reflect::MessageDescriptor::new::<RaftEntryTooLarge>(
"RaftEntryTooLarge",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static RaftEntryTooLarge {
static mut instance: ::protobuf::lazy::Lazy<RaftEntryTooLarge> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const RaftEntryTooLarge,
};
unsafe {
instance.get(RaftEntryTooLarge::new)
}
}
}
impl ::protobuf::Clear for RaftEntryTooLarge {
fn clear(&mut self) {
self.clear_region_id();
self.clear_entry_size();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for RaftEntryTooLarge {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for RaftEntryTooLarge {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default)]
pub struct Error {
// message fields
pub message: ::std::string::String,
pub not_leader: ::protobuf::SingularPtrField<NotLeader>,
pub region_not_found: ::protobuf::SingularPtrField<RegionNotFound>,
pub key_not_in_region: ::protobuf::SingularPtrField<KeyNotInRegion>,
pub stale_epoch: ::protobuf::SingularPtrField<StaleEpoch>,
pub server_is_busy: ::protobuf::SingularPtrField<ServerIsBusy>,
pub stale_command: ::protobuf::SingularPtrField<StaleCommand>,
pub store_not_match: ::protobuf::SingularPtrField<StoreNotMatch>,
pub raft_entry_too_large: ::protobuf::SingularPtrField<RaftEntryTooLarge>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl Error {
pub fn new() -> Error {
::std::default::Default::default()
}
// string message = 1;
pub fn clear_message(&mut self) {
self.message.clear();
}
// Param is passed by value, moved
pub fn set_message(&mut self, v: ::std::string::String) {
self.message = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_message(&mut self) -> &mut ::std::string::String {
&mut self.message
}
// Take field
pub fn take_message(&mut self) -> ::std::string::String {
::std::mem::replace(&mut self.message, ::std::string::String::new())
}
pub fn get_message(&self) -> &str {
&self.message
}
// .errorpb.NotLeader not_leader = 2;
pub fn clear_not_leader(&mut self) {
self.not_leader.clear();
}
pub fn has_not_leader(&self) -> bool {
self.not_leader.is_some()
}
// Param is passed by value, moved
pub fn set_not_leader(&mut self, v: NotLeader) {
self.not_leader = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_not_leader(&mut self) -> &mut NotLeader {
if self.not_leader.is_none() {
self.not_leader.set_default();
}
self.not_leader.as_mut().unwrap()
}
// Take field
pub fn take_not_leader(&mut self) -> NotLeader {
self.not_leader.take().unwrap_or_else(|| NotLeader::new())
}
pub fn get_not_leader(&self) -> &NotLeader {
self.not_leader.as_ref().unwrap_or_else(|| NotLeader::default_instance())
}
// .errorpb.RegionNotFound region_not_found = 3;
pub fn clear_region_not_found(&mut self) {
self.region_not_found.clear();
}
pub fn has_region_not_found(&self) -> bool {
self.region_not_found.is_some()
}
// Param is passed by value, moved
pub fn set_region_not_found(&mut self, v: RegionNotFound) {
self.region_not_found = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_region_not_found(&mut self) -> &mut RegionNotFound {
if self.region_not_found.is_none() {
self.region_not_found.set_default();
}
self.region_not_found.as_mut().unwrap()
}
// Take field
pub fn take_region_not_found(&mut self) -> RegionNotFound {
self.region_not_found.take().unwrap_or_else(|| RegionNotFound::new())
}
pub fn get_region_not_found(&self) -> &RegionNotFound {
self.region_not_found.as_ref().unwrap_or_else(|| RegionNotFound::default_instance())
}
// .errorpb.KeyNotInRegion key_not_in_region = 4;
pub fn clear_key_not_in_region(&mut self) {
self.key_not_in_region.clear();
}
pub fn has_key_not_in_region(&self) -> bool {
self.key_not_in_region.is_some()
}
// Param is passed by value, moved
pub fn set_key_not_in_region(&mut self, v: KeyNotInRegion) {
self.key_not_in_region = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_key_not_in_region(&mut self) -> &mut KeyNotInRegion {
if self.key_not_in_region.is_none() {
self.key_not_in_region.set_default();
}
self.key_not_in_region.as_mut().unwrap()
}
// Take field
pub fn take_key_not_in_region(&mut self) -> KeyNotInRegion {
self.key_not_in_region.take().unwrap_or_else(|| KeyNotInRegion::new())
}
pub fn get_key_not_in_region(&self) -> &KeyNotInRegion {
self.key_not_in_region.as_ref().unwrap_or_else(|| KeyNotInRegion::default_instance())
}
// .errorpb.StaleEpoch stale_epoch = 5;
pub fn clear_stale_epoch(&mut self) {
self.stale_epoch.clear();
}
pub fn has_stale_epoch(&self) -> bool {
self.stale_epoch.is_some()
}
// Param is passed by value, moved
pub fn set_stale_epoch(&mut self, v: StaleEpoch) {
self.stale_epoch = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_stale_epoch(&mut self) -> &mut StaleEpoch {
if self.stale_epoch.is_none() {
self.stale_epoch.set_default();
}
self.stale_epoch.as_mut().unwrap()
}
// Take field
pub fn take_stale_epoch(&mut self) -> StaleEpoch {
self.stale_epoch.take().unwrap_or_else(|| StaleEpoch::new())
}
pub fn get_stale_epoch(&self) -> &StaleEpoch {
self.stale_epoch.as_ref().unwrap_or_else(|| StaleEpoch::default_instance())
}
// .errorpb.ServerIsBusy server_is_busy = 6;
pub fn clear_server_is_busy(&mut self) {
self.server_is_busy.clear();
}
pub fn has_server_is_busy(&self) -> bool {
self.server_is_busy.is_some()
}
// Param is passed by value, moved
pub fn set_server_is_busy(&mut self, v: ServerIsBusy) {
self.server_is_busy = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_server_is_busy(&mut self) -> &mut ServerIsBusy {
if self.server_is_busy.is_none() {
self.server_is_busy.set_default();
}
self.server_is_busy.as_mut().unwrap()
}
// Take field
pub fn take_server_is_busy(&mut self) -> ServerIsBusy {
self.server_is_busy.take().unwrap_or_else(|| ServerIsBusy::new())
}
pub fn get_server_is_busy(&self) -> &ServerIsBusy {
self.server_is_busy.as_ref().unwrap_or_else(|| ServerIsBusy::default_instance())
}
// .errorpb.StaleCommand stale_command = 7;
pub fn clear_stale_command(&mut self) {
self.stale_command.clear();
}
pub fn has_stale_command(&self) -> bool {
self.stale_command.is_some()
}
// Param is passed by value, moved
pub fn set_stale_command(&mut self, v: StaleCommand) {
self.stale_command = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_stale_command(&mut self) -> &mut StaleCommand {
if self.stale_command.is_none() {
self.stale_command.set_default();
}
self.stale_command.as_mut().unwrap()
}
// Take field
pub fn take_stale_command(&mut self) -> StaleCommand {
self.stale_command.take().unwrap_or_else(|| StaleCommand::new())
}
pub fn get_stale_command(&self) -> &StaleCommand {
self.stale_command.as_ref().unwrap_or_else(|| StaleCommand::default_instance())
}
// .errorpb.StoreNotMatch store_not_match = 8;
pub fn clear_store_not_match(&mut self) {
self.store_not_match.clear();
}
pub fn has_store_not_match(&self) -> bool {
self.store_not_match.is_some()
}
// Param is passed by value, moved
pub fn set_store_not_match(&mut self, v: StoreNotMatch) {
self.store_not_match = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_store_not_match(&mut self) -> &mut StoreNotMatch {
if self.store_not_match.is_none() {
self.store_not_match.set_default();
}
self.store_not_match.as_mut().unwrap()
}
// Take field
pub fn take_store_not_match(&mut self) -> StoreNotMatch {
self.store_not_match.take().unwrap_or_else(|| StoreNotMatch::new())
}
pub fn get_store_not_match(&self) -> &StoreNotMatch {
self.store_not_match.as_ref().unwrap_or_else(|| StoreNotMatch::default_instance())
}
// .errorpb.RaftEntryTooLarge raft_entry_too_large = 9;
pub fn clear_raft_entry_too_large(&mut self) {
self.raft_entry_too_large.clear();
}
pub fn has_raft_entry_too_large(&self) -> bool {
self.raft_entry_too_large.is_some()
}
// Param is passed by value, moved
pub fn set_raft_entry_too_large(&mut self, v: RaftEntryTooLarge) {
self.raft_entry_too_large = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_raft_entry_too_large(&mut self) -> &mut RaftEntryTooLarge {
if self.raft_entry_too_large.is_none() {
self.raft_entry_too_large.set_default();
}
self.raft_entry_too_large.as_mut().unwrap()
}
// Take field
pub fn take_raft_entry_too_large(&mut self) -> RaftEntryTooLarge {
self.raft_entry_too_large.take().unwrap_or_else(|| RaftEntryTooLarge::new())
}
pub fn get_raft_entry_too_large(&self) -> &RaftEntryTooLarge {
self.raft_entry_too_large.as_ref().unwrap_or_else(|| RaftEntryTooLarge::default_instance())
}
}
impl ::protobuf::Message for Error {
fn is_initialized(&self) -> bool {
for v in &self.not_leader {
if !v.is_initialized() {
return false;
}
};
for v in &self.region_not_found {
if !v.is_initialized() {
return false;
}
};
for v in &self.key_not_in_region {
if !v.is_initialized() {
return false;
}
};
for v in &self.stale_epoch {
if !v.is_initialized() {
return false;
}
};
for v in &self.server_is_busy {
if !v.is_initialized() {
return false;
}
};
for v in &self.stale_command {
if !v.is_initialized() {
return false;
}
};
for v in &self.store_not_match {
if !v.is_initialized() {
return false;
}
};
for v in &self.raft_entry_too_large {
if !v.is_initialized() {
return false;
}
};
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.message)?;
},
2 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.not_leader)?;
},
3 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.region_not_found)?;
},
4 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.key_not_in_region)?;
},
5 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.stale_epoch)?;
},
6 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.server_is_busy)?;
},
7 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.stale_command)?;
},
8 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.store_not_match)?;
},
9 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.raft_entry_too_large)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if !self.message.is_empty() {
my_size += ::protobuf::rt::string_size(1, &self.message);
}
if let Some(ref v) = self.not_leader.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if let Some(ref v) = self.region_not_found.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if let Some(ref v) = self.key_not_in_region.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if let Some(ref v) = self.stale_epoch.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if let Some(ref v) = self.server_is_busy.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if let Some(ref v) = self.stale_command.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if let Some(ref v) = self.store_not_match.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if let Some(ref v) = self.raft_entry_too_large.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if !self.message.is_empty() {
os.write_string(1, &self.message)?;
}
if let Some(ref v) = self.not_leader.as_ref() {
os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
if let Some(ref v) = self.region_not_found.as_ref() {
os.write_tag(3, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
if let Some(ref v) = self.key_not_in_region.as_ref() {
os.write_tag(4, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
if let Some(ref v) = self.stale_epoch.as_ref() {
os.write_tag(5, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
if let Some(ref v) = self.server_is_busy.as_ref() {
os.write_tag(6, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
if let Some(ref v) = self.stale_command.as_ref() {
os.write_tag(7, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
if let Some(ref v) = self.store_not_match.as_ref() {
os.write_tag(8, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
if let Some(ref v) = self.raft_entry_too_large.as_ref() {
os.write_tag(9, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> Error {
Error::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"message",
|m: &Error| { &m.message },
|m: &mut Error| { &mut m.message },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<NotLeader>>(
"not_leader",
|m: &Error| { &m.not_leader },
|m: &mut Error| { &mut m.not_leader },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<RegionNotFound>>(
"region_not_found",
|m: &Error| { &m.region_not_found },
|m: &mut Error| { &mut m.region_not_found },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<KeyNotInRegion>>(
"key_not_in_region",
|m: &Error| { &m.key_not_in_region },
|m: &mut Error| { &mut m.key_not_in_region },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<StaleEpoch>>(
"stale_epoch",
|m: &Error| { &m.stale_epoch },
|m: &mut Error| { &mut m.stale_epoch },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<ServerIsBusy>>(
"server_is_busy",
|m: &Error| { &m.server_is_busy },
|m: &mut Error| { &mut m.server_is_busy },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<StaleCommand>>(
"stale_command",
|m: &Error| { &m.stale_command },
|m: &mut Error| { &mut m.stale_command },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<StoreNotMatch>>(
"store_not_match",
|m: &Error| { &m.store_not_match },
|m: &mut Error| { &mut m.store_not_match },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<RaftEntryTooLarge>>(
"raft_entry_too_large",
|m: &Error| { &m.raft_entry_too_large },
|m: &mut Error| { &mut m.raft_entry_too_large },
));
::protobuf::reflect::MessageDescriptor::new::<Error>(
"Error",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static Error {
static mut instance: ::protobuf::lazy::Lazy<Error> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const Error,
};
unsafe {
instance.get(Error::new)
}
}
}
impl ::protobuf::Clear for Error {
fn clear(&mut self) {
self.clear_message();
self.clear_not_leader();
self.clear_region_not_found();
self.clear_key_not_in_region();
self.clear_stale_epoch();
self.clear_server_is_busy();
self.clear_stale_command();
self.clear_store_not_match();
self.clear_raft_entry_too_large();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for Error {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for Error {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
static file_descriptor_proto_data: &'static [u8] = b"\
\n\rerrorpb.proto\x12\x07errorpb\x1a\x0cmetapb.proto\x1a\x14gogoproto/go\
go.proto\"N\n\tNotLeader\x12\x1b\n\tregion_id\x18\x01\x20\x01(\x04R\x08r\
egionId\x12$\n\x06leader\x18\x02\x20\x01(\x0b2\x0c.metapb.PeerR\x06leade\
r\"\x0f\n\rStoreNotMatch\"-\n\x0eRegionNotFound\x12\x1b\n\tregion_id\x18\
\x01\x20\x01(\x04R\x08regionId\"u\n\x0eKeyNotInRegion\x12\x10\n\x03key\
\x18\x01\x20\x01(\x0cR\x03key\x12\x1b\n\tregion_id\x18\x02\x20\x01(\x04R\
\x08regionId\x12\x1b\n\tstart_key\x18\x03\x20\x01(\x0cR\x08startKey\x12\
\x17\n\x07end_key\x18\x04\x20\x01(\x0cR\x06endKey\"=\n\nStaleEpoch\x12/\
\n\x0bnew_regions\x18\x01\x20\x03(\x0b2\x0e.metapb.RegionR\nnewRegions\"\
E\n\x0cServerIsBusy\x12\x16\n\x06reason\x18\x01\x20\x01(\tR\x06reason\
\x12\x1d\n\nbackoff_ms\x18\x02\x20\x01(\x04R\tbackoffMs\"\x0e\n\x0cStale\
Command\"O\n\x11RaftEntryTooLarge\x12\x1b\n\tregion_id\x18\x01\x20\x01(\
\x04R\x08regionId\x12\x1d\n\nentry_size\x18\x02\x20\x01(\x04R\tentrySize\
\"\x97\x04\n\x05Error\x12\x18\n\x07message\x18\x01\x20\x01(\tR\x07messag\
e\x121\n\nnot_leader\x18\x02\x20\x01(\x0b2\x12.errorpb.NotLeaderR\tnotLe\
ader\x12A\n\x10region_not_found\x18\x03\x20\x01(\x0b2\x17.errorpb.Region\
NotFoundR\x0eregionNotFound\x12B\n\x11key_not_in_region\x18\x04\x20\x01(\
\x0b2\x17.errorpb.KeyNotInRegionR\x0ekeyNotInRegion\x124\n\x0bstale_epoc\
h\x18\x05\x20\x01(\x0b2\x13.errorpb.StaleEpochR\nstaleEpoch\x12;\n\x0ese\
rver_is_busy\x18\x06\x20\x01(\x0b2\x15.errorpb.ServerIsBusyR\x0cserverIs\
Busy\x12:\n\rstale_command\x18\x07\x20\x01(\x0b2\x15.errorpb.StaleComman\
dR\x0cstaleCommand\x12>\n\x0fstore_not_match\x18\x08\x20\x01(\x0b2\x16.e\
rrorpb.StoreNotMatchR\rstoreNotMatch\x12K\n\x14raft_entry_too_large\x18\
\t\x20\x01(\x0b2\x1a.errorpb.RaftEntryTooLargeR\x11raftEntryTooLargeB\
\x1e\n\x10org.tikv.kvproto\xe0\xe2\x1e\x01\xc8\xe2\x1e\x01\xd0\xe2\x1e\
\x01J\x8f\x10\n\x06\x12\x04\0\0:\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\
\x08\n\x01\x02\x12\x03\x01\x08\x0f\n\t\n\x02\x03\0\x12\x03\x03\x07\x15\n\
\t\n\x02\x03\x01\x12\x03\x04\x07\x1d\n\x08\n\x01\x08\x12\x03\x06\0(\n\
\x0b\n\x04\x08\xe7\x07\0\x12\x03\x06\0(\n\x0c\n\x05\x08\xe7\x07\0\x02\
\x12\x03\x06\x07\x20\n\r\n\x06\x08\xe7\x07\0\x02\0\x12\x03\x06\x07\x20\n\
\x0e\n\x07\x08\xe7\x07\0\x02\0\x01\x12\x03\x06\x08\x1f\n\x0c\n\x05\x08\
\xe7\x07\0\x03\x12\x03\x06#'\n\x08\n\x01\x08\x12\x03\x07\0$\n\x0b\n\x04\
\x08\xe7\x07\x01\x12\x03\x07\0$\n\x0c\n\x05\x08\xe7\x07\x01\x02\x12\x03\
\x07\x07\x1c\n\r\n\x06\x08\xe7\x07\x01\x02\0\x12\x03\x07\x07\x1c\n\x0e\n\
\x07\x08\xe7\x07\x01\x02\0\x01\x12\x03\x07\x08\x1b\n\x0c\n\x05\x08\xe7\
\x07\x01\x03\x12\x03\x07\x1f#\n\x08\n\x01\x08\x12\x03\x08\0*\n\x0b\n\x04\
\x08\xe7\x07\x02\x12\x03\x08\0*\n\x0c\n\x05\x08\xe7\x07\x02\x02\x12\x03\
\x08\x07\"\n\r\n\x06\x08\xe7\x07\x02\x02\0\x12\x03\x08\x07\"\n\x0e\n\x07\
\x08\xe7\x07\x02\x02\0\x01\x12\x03\x08\x08!\n\x0c\n\x05\x08\xe7\x07\x02\
\x03\x12\x03\x08%)\n\x08\n\x01\x08\x12\x03\n\0)\n\x0b\n\x04\x08\xe7\x07\
\x03\x12\x03\n\0)\n\x0c\n\x05\x08\xe7\x07\x03\x02\x12\x03\n\x07\x13\n\r\
\n\x06\x08\xe7\x07\x03\x02\0\x12\x03\n\x07\x13\n\x0e\n\x07\x08\xe7\x07\
\x03\x02\0\x01\x12\x03\n\x07\x13\n\x0c\n\x05\x08\xe7\x07\x03\x07\x12\x03\
\n\x16(\n\n\n\x02\x04\0\x12\x04\x0c\0\x0f\x01\n\n\n\x03\x04\0\x01\x12\
\x03\x0c\x08\x11\n\x0b\n\x04\x04\0\x02\0\x12\x03\r\x04\x19\n\r\n\x05\x04\
\0\x02\0\x04\x12\x04\r\x04\x0c\x13\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\r\
\x04\n\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\r\x0b\x14\n\x0c\n\x05\x04\0\
\x02\0\x03\x12\x03\r\x17\x18\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x0e\x04\
\x1b\n\r\n\x05\x04\0\x02\x01\x04\x12\x04\x0e\x04\r\x19\n\x0c\n\x05\x04\0\
\x02\x01\x06\x12\x03\x0e\x04\x0f\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\
\x0e\x10\x16\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x0e\x19\x1a\n\n\n\x02\
\x04\x01\x12\x04\x11\0\x12\x01\n\n\n\x03\x04\x01\x01\x12\x03\x11\x08\x15\
\n\n\n\x02\x04\x02\x12\x04\x14\0\x16\x01\n\n\n\x03\x04\x02\x01\x12\x03\
\x14\x08\x16\n\x0b\n\x04\x04\x02\x02\0\x12\x03\x15\x04\x19\n\r\n\x05\x04\
\x02\x02\0\x04\x12\x04\x15\x04\x14\x18\n\x0c\n\x05\x04\x02\x02\0\x05\x12\
\x03\x15\x04\n\n\x0c\n\x05\x04\x02\x02\0\x01\x12\x03\x15\x0b\x14\n\x0c\n\
\x05\x04\x02\x02\0\x03\x12\x03\x15\x17\x18\n\n\n\x02\x04\x03\x12\x04\x18\
\0\x1d\x01\n\n\n\x03\x04\x03\x01\x12\x03\x18\x08\x16\n\x0b\n\x04\x04\x03\
\x02\0\x12\x03\x19\x04\x12\n\r\n\x05\x04\x03\x02\0\x04\x12\x04\x19\x04\
\x18\x18\n\x0c\n\x05\x04\x03\x02\0\x05\x12\x03\x19\x04\t\n\x0c\n\x05\x04\
\x03\x02\0\x01\x12\x03\x19\n\r\n\x0c\n\x05\x04\x03\x02\0\x03\x12\x03\x19\
\x10\x11\n\x0b\n\x04\x04\x03\x02\x01\x12\x03\x1a\x04\x19\n\r\n\x05\x04\
\x03\x02\x01\x04\x12\x04\x1a\x04\x19\x12\n\x0c\n\x05\x04\x03\x02\x01\x05\
\x12\x03\x1a\x04\n\n\x0c\n\x05\x04\x03\x02\x01\x01\x12\x03\x1a\x0b\x14\n\
\x0c\n\x05\x04\x03\x02\x01\x03\x12\x03\x1a\x17\x18\n\x0b\n\x04\x04\x03\
\x02\x02\x12\x03\x1b\x04\x18\n\r\n\x05\x04\x03\x02\x02\x04\x12\x04\x1b\
\x04\x1a\x19\n\x0c\n\x05\x04\x03\x02\x02\x05\x12\x03\x1b\x04\t\n\x0c\n\
\x05\x04\x03\x02\x02\x01\x12\x03\x1b\n\x13\n\x0c\n\x05\x04\x03\x02\x02\
\x03\x12\x03\x1b\x16\x17\n\x0b\n\x04\x04\x03\x02\x03\x12\x03\x1c\x04\x16\
\n\r\n\x05\x04\x03\x02\x03\x04\x12\x04\x1c\x04\x1b\x18\n\x0c\n\x05\x04\
\x03\x02\x03\x05\x12\x03\x1c\x04\t\n\x0c\n\x05\x04\x03\x02\x03\x01\x12\
\x03\x1c\n\x11\n\x0c\n\x05\x04\x03\x02\x03\x03\x12\x03\x1c\x14\x15\n\n\n\
\x02\x04\x04\x12\x04\x1f\0!\x01\n\n\n\x03\x04\x04\x01\x12\x03\x1f\x08\
\x12\n\x0b\n\x04\x04\x04\x02\0\x12\x03\x20\x04+\n\x0c\n\x05\x04\x04\x02\
\0\x04\x12\x03\x20\x04\x0c\n\x0c\n\x05\x04\x04\x02\0\x06\x12\x03\x20\r\
\x1a\n\x0c\n\x05\x04\x04\x02\0\x01\x12\x03\x20\x1b&\n\x0c\n\x05\x04\x04\
\x02\0\x03\x12\x03\x20)*\n\n\n\x02\x04\x05\x12\x04#\0&\x01\n\n\n\x03\x04\
\x05\x01\x12\x03#\x08\x14\n\x0b\n\x04\x04\x05\x02\0\x12\x03$\x04\x16\n\r\
\n\x05\x04\x05\x02\0\x04\x12\x04$\x04#\x16\n\x0c\n\x05\x04\x05\x02\0\x05\
\x12\x03$\x04\n\n\x0c\n\x05\x04\x05\x02\0\x01\x12\x03$\x0b\x11\n\x0c\n\
\x05\x04\x05\x02\0\x03\x12\x03$\x14\x15\n\x0b\n\x04\x04\x05\x02\x01\x12\
\x03%\x04\x1a\n\r\n\x05\x04\x05\x02\x01\x04\x12\x04%\x04$\x16\n\x0c\n\
\x05\x04\x05\x02\x01\x05\x12\x03%\x04\n\n\x0c\n\x05\x04\x05\x02\x01\x01\
\x12\x03%\x0b\x15\n\x0c\n\x05\x04\x05\x02\x01\x03\x12\x03%\x18\x19\n\n\n\
\x02\x04\x06\x12\x04(\0)\x01\n\n\n\x03\x04\x06\x01\x12\x03(\x08\x14\n\n\
\n\x02\x04\x07\x12\x04+\0.\x01\n\n\n\x03\x04\x07\x01\x12\x03+\x08\x19\n\
\x0b\n\x04\x04\x07\x02\0\x12\x03,\x04\x19\n\r\n\x05\x04\x07\x02\0\x04\
\x12\x04,\x04+\x1b\n\x0c\n\x05\x04\x07\x02\0\x05\x12\x03,\x04\n\n\x0c\n\
\x05\x04\x07\x02\0\x01\x12\x03,\x0b\x14\n\x0c\n\x05\x04\x07\x02\0\x03\
\x12\x03,\x17\x18\n\x0b\n\x04\x04\x07\x02\x01\x12\x03-\x04\x1a\n\r\n\x05\
\x04\x07\x02\x01\x04\x12\x04-\x04,\x19\n\x0c\n\x05\x04\x07\x02\x01\x05\
\x12\x03-\x04\n\n\x0c\n\x05\x04\x07\x02\x01\x01\x12\x03-\x0b\x15\n\x0c\n\
\x05\x04\x07\x02\x01\x03\x12\x03-\x18\x19\n\n\n\x02\x04\x08\x12\x040\0:\
\x01\n\n\n\x03\x04\x08\x01\x12\x030\x08\r\n\x0b\n\x04\x04\x08\x02\0\x12\
\x031\x04\x17\n\r\n\x05\x04\x08\x02\0\x04\x12\x041\x040\x0f\n\x0c\n\x05\
\x04\x08\x02\0\x05\x12\x031\x04\n\n\x0c\n\x05\x04\x08\x02\0\x01\x12\x031\
\x0b\x12\n\x0c\n\x05\x04\x08\x02\0\x03\x12\x031\x15\x16\n\x0b\n\x04\x04\
\x08\x02\x01\x12\x032\x04\x1d\n\r\n\x05\x04\x08\x02\x01\x04\x12\x042\x04\
1\x17\n\x0c\n\x05\x04\x08\x02\x01\x06\x12\x032\x04\r\n\x0c\n\x05\x04\x08\
\x02\x01\x01\x12\x032\x0e\x18\n\x0c\n\x05\x04\x08\x02\x01\x03\x12\x032\
\x1b\x1c\n\x0b\n\x04\x04\x08\x02\x02\x12\x033\x04(\n\r\n\x05\x04\x08\x02\
\x02\x04\x12\x043\x042\x1d\n\x0c\n\x05\x04\x08\x02\x02\x06\x12\x033\x04\
\x12\n\x0c\n\x05\x04\x08\x02\x02\x01\x12\x033\x13#\n\x0c\n\x05\x04\x08\
\x02\x02\x03\x12\x033&'\n\x0b\n\x04\x04\x08\x02\x03\x12\x034\x04)\n\r\n\
\x05\x04\x08\x02\x03\x04\x12\x044\x043(\n\x0c\n\x05\x04\x08\x02\x03\x06\
\x12\x034\x04\x12\n\x0c\n\x05\x04\x08\x02\x03\x01\x12\x034\x13$\n\x0c\n\
\x05\x04\x08\x02\x03\x03\x12\x034'(\n\x0b\n\x04\x04\x08\x02\x04\x12\x035\
\x04\x1f\n\r\n\x05\x04\x08\x02\x04\x04\x12\x045\x044)\n\x0c\n\x05\x04\
\x08\x02\x04\x06\x12\x035\x04\x0e\n\x0c\n\x05\x04\x08\x02\x04\x01\x12\
\x035\x0f\x1a\n\x0c\n\x05\x04\x08\x02\x04\x03\x12\x035\x1d\x1e\n\x0b\n\
\x04\x04\x08\x02\x05\x12\x036\x04$\n\r\n\x05\x04\x08\x02\x05\x04\x12\x04\
6\x045\x1f\n\x0c\n\x05\x04\x08\x02\x05\x06\x12\x036\x04\x10\n\x0c\n\x05\
\x04\x08\x02\x05\x01\x12\x036\x11\x1f\n\x0c\n\x05\x04\x08\x02\x05\x03\
\x12\x036\"#\n\x0b\n\x04\x04\x08\x02\x06\x12\x037\x04#\n\r\n\x05\x04\x08\
\x02\x06\x04\x12\x047\x046$\n\x0c\n\x05\x04\x08\x02\x06\x06\x12\x037\x04\
\x10\n\x0c\n\x05\x04\x08\x02\x06\x01\x12\x037\x11\x1e\n\x0c\n\x05\x04\
\x08\x02\x06\x03\x12\x037!\"\n\x0b\n\x04\x04\x08\x02\x07\x12\x038\x04&\n\
\r\n\x05\x04\x08\x02\x07\x04\x12\x048\x047#\n\x0c\n\x05\x04\x08\x02\x07\
\x06\x12\x038\x04\x11\n\x0c\n\x05\x04\x08\x02\x07\x01\x12\x038\x12!\n\
\x0c\n\x05\x04\x08\x02\x07\x03\x12\x038$%\n\x0b\n\x04\x04\x08\x02\x08\
\x12\x039\x04/\n\r\n\x05\x04\x08\x02\x08\x04\x12\x049\x048&\n\x0c\n\x05\
\x04\x08\x02\x08\x06\x12\x039\x04\x15\n\x0c\n\x05\x04\x08\x02\x08\x01\
\x12\x039\x16*\n\x0c\n\x05\x04\x08\x02\x08\x03\x12\x039-.b\x06proto3\
";
static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto,
};
fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {
::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap()
}
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
unsafe {
file_descriptor_proto_lazy.get(|| {
parse_descriptor_proto()
})
}
}
| 35.469799 | 158 | 0.579678 |
ffd53890261e17ff0cfb7438569bc326b1cebb7e
| 15,056 |
// Copyright 2017 The Chromium OS 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 super::Error as DeviceError;
use super::{
ActivateError, ActivateResult, DeviceEventT, Queue, VirtioDevice, VirtioDeviceType,
VIRTIO_F_IOMMU_PLATFORM, VIRTIO_F_VERSION_1,
};
use crate::{VirtioInterrupt, VirtioInterruptType};
use anyhow::anyhow;
use libc::EFD_NONBLOCK;
use std::fs::File;
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::result;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use vm_memory::{Bytes, GuestAddressSpace, GuestMemoryAtomic, GuestMemoryMmap};
use vm_migration::{
Migratable, MigratableError, Pausable, Snapshot, SnapshotDataSection, Snapshottable,
Transportable,
};
use vmm_sys_util::eventfd::EventFd;
const QUEUE_SIZE: u16 = 256;
const NUM_QUEUES: usize = 1;
const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE];
// New descriptors are pending on the virtio queue.
const QUEUE_AVAIL_EVENT: DeviceEventT = 0;
// The device has been dropped.
const KILL_EVENT: DeviceEventT = 1;
// The device should be paused.
const PAUSE_EVENT: DeviceEventT = 2;
struct RngEpollHandler {
queues: Vec<Queue>,
mem: GuestMemoryAtomic<GuestMemoryMmap>,
random_file: File,
interrupt_cb: Arc<dyn VirtioInterrupt>,
queue_evt: EventFd,
kill_evt: EventFd,
pause_evt: EventFd,
}
impl RngEpollHandler {
fn process_queue(&mut self) -> bool {
let queue = &mut self.queues[0];
let mut used_desc_heads = [(0, 0); QUEUE_SIZE as usize];
let mut used_count = 0;
let mem = self.mem.memory();
for avail_desc in queue.iter(&mem) {
let mut len = 0;
// Drivers can only read from the random device.
if avail_desc.is_write_only() {
// Fill the read with data from the random device on the host.
if mem
.read_from(
avail_desc.addr,
&mut self.random_file,
avail_desc.len as usize,
)
.is_ok()
{
len = avail_desc.len;
}
}
used_desc_heads[used_count] = (avail_desc.index, len);
used_count += 1;
}
for &(desc_index, len) in &used_desc_heads[..used_count] {
queue.add_used(&mem, desc_index, len);
}
used_count > 0
}
fn signal_used_queue(&self) -> result::Result<(), DeviceError> {
self.interrupt_cb
.trigger(&VirtioInterruptType::Queue, Some(&self.queues[0]))
.map_err(|e| {
error!("Failed to signal used queue: {:?}", e);
DeviceError::FailedSignalingUsedQueue(e)
})
}
fn run(&mut self, paused: Arc<AtomicBool>) -> result::Result<(), DeviceError> {
// Create the epoll file descriptor
let epoll_fd = epoll::create(true).map_err(DeviceError::EpollCreateFd)?;
// Use 'File' to enforce closing on 'epoll_fd'
let epoll_file = unsafe { File::from_raw_fd(epoll_fd) };
// Add events
epoll::ctl(
epoll_file.as_raw_fd(),
epoll::ControlOptions::EPOLL_CTL_ADD,
self.queue_evt.as_raw_fd(),
epoll::Event::new(epoll::Events::EPOLLIN, u64::from(QUEUE_AVAIL_EVENT)),
)
.map_err(DeviceError::EpollCtl)?;
epoll::ctl(
epoll_file.as_raw_fd(),
epoll::ControlOptions::EPOLL_CTL_ADD,
self.kill_evt.as_raw_fd(),
epoll::Event::new(epoll::Events::EPOLLIN, u64::from(KILL_EVENT)),
)
.map_err(DeviceError::EpollCtl)?;
epoll::ctl(
epoll_file.as_raw_fd(),
epoll::ControlOptions::EPOLL_CTL_ADD,
self.pause_evt.as_raw_fd(),
epoll::Event::new(epoll::Events::EPOLLIN, u64::from(PAUSE_EVENT)),
)
.map_err(DeviceError::EpollCtl)?;
const EPOLL_EVENTS_LEN: usize = 100;
let mut events = vec![epoll::Event::new(epoll::Events::empty(), 0); EPOLL_EVENTS_LEN];
// Before jumping into the epoll loop, check if the device is expected
// to be in a paused state. This is helpful for the restore code path
// as the device thread should not start processing anything before the
// device has been resumed.
while paused.load(Ordering::SeqCst) {
thread::park();
}
'epoll: loop {
let num_events = match epoll::wait(epoll_file.as_raw_fd(), -1, &mut events[..]) {
Ok(res) => res,
Err(e) => {
if e.kind() == io::ErrorKind::Interrupted {
// It's well defined from the epoll_wait() syscall
// documentation that the epoll loop can be interrupted
// before any of the requested events occurred or the
// timeout expired. In both those cases, epoll_wait()
// returns an error of type EINTR, but this should not
// be considered as a regular error. Instead it is more
// appropriate to retry, by calling into epoll_wait().
continue;
}
return Err(DeviceError::EpollWait(e));
}
};
for event in events.iter().take(num_events) {
let ev_type = event.data as u16;
match ev_type {
QUEUE_AVAIL_EVENT => {
if let Err(e) = self.queue_evt.read() {
error!("Failed to get queue event: {:?}", e);
break 'epoll;
} else if self.process_queue() {
if let Err(e) = self.signal_used_queue() {
error!("Failed to signal used queue: {:?}", e);
break 'epoll;
}
}
}
KILL_EVENT => {
debug!("KILL_EVENT received, stopping epoll loop");
break 'epoll;
}
PAUSE_EVENT => {
debug!("PAUSE_EVENT received, pausing virtio-rng epoll loop");
// We loop here to handle spurious park() returns.
// Until we have not resumed, the paused boolean will
// be true.
while paused.load(Ordering::SeqCst) {
thread::park();
}
// Drain pause event after the device has been resumed.
// This ensures the pause event has been seen by each
// and every thread related to this virtio device.
let _ = self.pause_evt.read();
}
_ => {
error!("Unknown event for virtio-block");
}
}
}
}
Ok(())
}
}
/// Virtio device for exposing entropy to the guest OS through virtio.
pub struct Rng {
id: String,
kill_evt: Option<EventFd>,
pause_evt: Option<EventFd>,
random_file: Option<File>,
avail_features: u64,
acked_features: u64,
queue_evts: Option<Vec<EventFd>>,
interrupt_cb: Option<Arc<dyn VirtioInterrupt>>,
epoll_threads: Option<Vec<thread::JoinHandle<result::Result<(), DeviceError>>>>,
paused: Arc<AtomicBool>,
}
#[derive(Serialize, Deserialize)]
pub struct RngState {
pub avail_features: u64,
pub acked_features: u64,
pub paused: Arc<AtomicBool>,
}
impl Rng {
/// Create a new virtio rng device that gets random data from /dev/urandom.
pub fn new(id: String, path: &str, iommu: bool) -> io::Result<Rng> {
let random_file = File::open(path)?;
let mut avail_features = 1u64 << VIRTIO_F_VERSION_1;
if iommu {
avail_features |= 1u64 << VIRTIO_F_IOMMU_PLATFORM;
}
Ok(Rng {
id,
kill_evt: None,
pause_evt: None,
random_file: Some(random_file),
avail_features,
acked_features: 0u64,
queue_evts: None,
interrupt_cb: None,
epoll_threads: None,
paused: Arc::new(AtomicBool::new(false)),
})
}
fn state(&self) -> RngState {
RngState {
avail_features: self.avail_features,
acked_features: self.acked_features,
paused: self.paused.clone(),
}
}
fn set_state(&mut self, state: &RngState) -> io::Result<()> {
self.avail_features = state.avail_features;
self.acked_features = state.acked_features;
self.paused = state.paused.clone();
Ok(())
}
}
impl Drop for Rng {
fn drop(&mut self) {
if let Some(kill_evt) = self.kill_evt.take() {
// Ignore the result because there is nothing we can do about it.
let _ = kill_evt.write(1);
}
}
}
impl VirtioDevice for Rng {
fn device_type(&self) -> u32 {
VirtioDeviceType::TYPE_RNG as u32
}
fn queue_max_sizes(&self) -> &[u16] {
QUEUE_SIZES
}
fn features(&self) -> u64 {
self.avail_features
}
fn ack_features(&mut self, value: u64) {
let mut v = value;
// Check if the guest is ACK'ing a feature that we didn't claim to have.
let unrequested_features = v & !self.avail_features;
if unrequested_features != 0 {
warn!("Received acknowledge request for unknown feature.");
// Don't count these features as acked.
v &= !unrequested_features;
}
self.acked_features |= v;
}
fn activate(
&mut self,
mem: GuestMemoryAtomic<GuestMemoryMmap>,
interrupt_cb: Arc<dyn VirtioInterrupt>,
queues: Vec<Queue>,
mut queue_evts: Vec<EventFd>,
) -> ActivateResult {
if queues.len() != NUM_QUEUES || queue_evts.len() != NUM_QUEUES {
error!(
"Cannot perform activate. Expected {} queue(s), got {}",
NUM_QUEUES,
queues.len()
);
return Err(ActivateError::BadActivate);
}
let (self_kill_evt, kill_evt) = EventFd::new(EFD_NONBLOCK)
.and_then(|e| Ok((e.try_clone()?, e)))
.map_err(|e| {
error!("failed creating kill EventFd pair: {}", e);
ActivateError::BadActivate
})?;
self.kill_evt = Some(self_kill_evt);
let (self_pause_evt, pause_evt) = EventFd::new(EFD_NONBLOCK)
.and_then(|e| Ok((e.try_clone()?, e)))
.map_err(|e| {
error!("failed creating pause EventFd pair: {}", e);
ActivateError::BadActivate
})?;
self.pause_evt = Some(self_pause_evt);
// Save the interrupt EventFD as we need to return it on reset
// but clone it to pass into the thread.
self.interrupt_cb = Some(interrupt_cb.clone());
let mut tmp_queue_evts: Vec<EventFd> = Vec::new();
for queue_evt in queue_evts.iter() {
// Save the queue EventFD as we need to return it on reset
// but clone it to pass into the thread.
tmp_queue_evts.push(queue_evt.try_clone().map_err(|e| {
error!("failed to clone queue EventFd: {}", e);
ActivateError::BadActivate
})?);
}
self.queue_evts = Some(tmp_queue_evts);
if let Some(file) = self.random_file.as_ref() {
let random_file = file.try_clone().map_err(|e| {
error!("failed cloning rng source: {}", e);
ActivateError::BadActivate
})?;
let mut handler = RngEpollHandler {
queues,
mem,
random_file,
interrupt_cb,
queue_evt: queue_evts.remove(0),
kill_evt,
pause_evt,
};
let paused = self.paused.clone();
let mut epoll_threads = Vec::new();
thread::Builder::new()
.name("virtio_rng".to_string())
.spawn(move || handler.run(paused))
.map(|thread| epoll_threads.push(thread))
.map_err(|e| {
error!("failed to clone the virtio-rng epoll thread: {}", e);
ActivateError::BadActivate
})?;
self.epoll_threads = Some(epoll_threads);
return Ok(());
}
Err(ActivateError::BadActivate)
}
fn reset(&mut self) -> Option<(Arc<dyn VirtioInterrupt>, Vec<EventFd>)> {
// We first must resume the virtio thread if it was paused.
if self.pause_evt.take().is_some() {
self.resume().ok()?;
}
// Then kill it.
if let Some(kill_evt) = self.kill_evt.take() {
// Ignore the result because there is nothing we can do about it.
let _ = kill_evt.write(1);
}
// Return the interrupt and queue EventFDs
Some((
self.interrupt_cb.take().unwrap(),
self.queue_evts.take().unwrap(),
))
}
}
virtio_pausable!(Rng);
impl Snapshottable for Rng {
fn id(&self) -> String {
self.id.clone()
}
fn snapshot(&self) -> std::result::Result<Snapshot, MigratableError> {
let snapshot =
serde_json::to_vec(&self.state()).map_err(|e| MigratableError::Snapshot(e.into()))?;
let mut rng_snapshot = Snapshot::new(self.id.as_str());
rng_snapshot.add_data_section(SnapshotDataSection {
id: format!("{}-section", self.id),
snapshot,
});
Ok(rng_snapshot)
}
fn restore(&mut self, snapshot: Snapshot) -> std::result::Result<(), MigratableError> {
if let Some(rng_section) = snapshot.snapshot_data.get(&format!("{}-section", self.id)) {
let rng_state = match serde_json::from_slice(&rng_section.snapshot) {
Ok(state) => state,
Err(error) => {
return Err(MigratableError::Restore(anyhow!(
"Could not deserialize RNG {}",
error
)))
}
};
return self.set_state(&rng_state).map_err(|e| {
MigratableError::Restore(anyhow!("Could not restore RNG state {:?}", e))
});
}
Err(MigratableError::Restore(anyhow!(
"Could not find RNG snapshot section"
)))
}
}
impl Transportable for Rng {}
impl Migratable for Rng {}
| 34.611494 | 96 | 0.538191 |
1449181cc6fde6a078ec04f5a8ef656f008c6c43
| 284 |
/*
cargo run -p error --bin iter_result2
*/
fn main() {
let strings = vec!["tofu", "93", "18"];
let numbers: Vec<_> = strings
.into_iter()
.map(|s| s.parse::<i32>())
.filter_map(Result::ok)
.collect();
println!("Results: {:?}", numbers);
}
| 21.846154 | 43 | 0.510563 |
f4bddede5f00d5ee2d9e59972269ff65c4455c96
| 254 |
pub mod part1;
pub mod part2;
#[macro_use]
#[cfg(test)]
mod tests {
use crate::aoc_test_suite;
aoc_test_suite!(super::part1::run, (part1_main, 99919692496939, ""),);
aoc_test_suite!(super::part2::run, (part2_main, 81914111161714, ""),);
}
| 19.538462 | 74 | 0.669291 |
dd73ddefcadbe22ed4bccc74e4167f99951d4fee
| 4,031 |
use std::fmt;
use std::option::Option;
pub trait ComputeNorm {
fn compute_norm(&self) -> f64;
}
pub struct LinkedList<T> {
head: Option<Box<Node<T>>>,
size: usize,
}
struct Node<T> {
value: T,
next: Option<Box<Node<T>>>,
}
impl<T> Node<T> {
pub fn new(value: T, next: Option<Box<Node<T>>>) -> Node<T> {
Node {
value: value,
next: next,
}
}
}
// Box implements Clone where T: Clone (it will allocate new heap memory and put the result of cloning T into that memory),
// Option also implements Clone where T: Clone, So we just have to implement Clone for Node, self.head.clone() will clone
// the Whole LinkedList for us. So does the PartialEq trait.
impl<T: Clone> Clone for Node<T> {
fn clone(&self) -> Node<T> {
Node::new(self.value.clone(), self.next.clone())
}
}
impl<T: PartialEq> PartialEq for Node<T> {
fn eq(&self, other: &Self) -> bool {
self.value == other.value && self.next == other.next
}
}
impl<T> LinkedList<T> {
pub fn new() -> LinkedList<T> {
LinkedList {
head: None,
size: 0,
}
}
pub fn get_size(&self) -> usize {
self.size
}
pub fn is_empty(&self) -> bool {
self.get_size() == 0
}
pub fn push_front(&mut self, value: T) {
let new_node: Box<Node<T>> = Box::new(Node::new(value, self.head.take()));
self.head = Some(new_node);
self.size += 1;
}
pub fn pop_front(&mut self) -> Option<T> {
let node: Box<Node<T>> = self.head.take()?;
self.head = node.next;
self.size -= 1;
Some(node.value)
}
}
impl<T: fmt::Display> fmt::Display for LinkedList<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut current: &Option<Box<Node<T>>> = &self.head;
let mut result = String::new();
loop {
match current {
Some(node) => {
result = format!("{} {}", result, node.value);
current = &node.next;
}
None => break,
}
}
write!(f, "{}", result)
}
}
impl<T> Drop for LinkedList<T> {
fn drop(&mut self) {
let mut current = self.head.take();
while let Some(mut node) = current {
current = node.next.take();
}
}
}
impl<T: Clone> Clone for LinkedList<T> {
fn clone(&self) -> LinkedList<T> {
LinkedList {
head: self.head.clone(),
size: self.size,
}
}
}
impl<T: PartialEq> PartialEq for LinkedList<T> {
fn eq(&self, other: &Self) -> bool {
self.size == other.size && self.head == other.head
}
}
// In order to implement `IntoIterator` for `LinkedList<T>` (as in, an iterator that will take ownership of
// the `LinkedList<T>` it is iterating over), you can simply implement the `Iterator` trait for `LinkedList<T>`
impl<T> Iterator for LinkedList<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.pop_front()
}
}
// This is a little more complicated
pub struct LinkedListIter<'a, T> {
current: &'a Option<Box<Node<T>>>,
}
impl<T: Clone> Iterator for LinkedListIter<'_, T> {
type Item = T;
fn next(&mut self) -> Option<T> {
match self.current {
Some(node) => {
self.current = &node.next;
Some(node.value.clone())
}
None => None,
}
}
}
impl<'a, T: Clone> IntoIterator for &'a LinkedList<T> {
type Item = T;
type IntoIter = LinkedListIter<'a, T>;
fn into_iter(self) -> LinkedListIter<'a, T> {
LinkedListIter {
current: &self.head,
}
}
}
impl ComputeNorm for LinkedList<f64> {
fn compute_norm(&self) -> f64 {
// let mut sum: f64 = 0.0;
// for ele in self {
// sum += ele * ele;
// }
// sum.sqrt()
self.into_iter().map(|x| x * x).sum::<f64>().sqrt()
}
}
| 25.037267 | 123 | 0.530638 |
87111e237b85df97e1452ab6faef37c67e21b2c5
| 5,254 |
extern crate alloc;
use alloc::sync::Arc;
#[derive(Debug)]
enum ListImpl<T> {
Nil,
Cons(T, Arc<ListImpl<T>>)
}
#[derive(Debug)]
pub struct List<T>(Arc<ListImpl<T>>);
impl<T: Copy> List<T> {
pub fn add(&self, t: T) -> List<T> {
List(Arc::new(ListImpl::Cons(t, self.0.clone())))
}
pub fn empty() -> List<T> {
List(Arc::new(ListImpl::Nil))
}
pub fn fold<R, F>(&self, init: &R, f: F) -> R
where
R: Copy,
F: FnOnce(&R, &T) -> R + Copy
{
let mut sum = *init;
let mut arc = &self.0;
loop {
match arc.as_ref() {
ListImpl::Cons(h, t) => {
arc = t;
sum = f(&sum, h);
},
ListImpl::Nil => break
}
}
sum
}
pub fn head(&self) -> Option<T> {
match self.0.as_ref() {
ListImpl::Cons(h, _t) => Some(*h),
ListImpl::Nil => None
}
}
pub fn is_empty(&self) -> bool {
match self.0.as_ref() {
ListImpl::Cons(_h, _t) => false,
ListImpl::Nil => true
}
}
pub fn map<R, F: FnOnce(&T) -> R + Copy>(&self, f: F) -> List<R> {
match self.0.as_ref() {
ListImpl::Cons(h, t) => List(Arc::new(ListImpl::Cons(
f(h),
List::map(&List(t.clone()), f).0
))),
ListImpl::Nil => List(Arc::new(ListImpl::Nil))
}
}
pub fn new(elements: &[T]) -> List<T> {
let mut list = List(Arc::new(ListImpl::Nil));
for (_i, element) in elements.iter().rev().enumerate() {
list = list.add(*element);
}
list
}
pub fn tail(&self) -> List<T> {
match self.0.as_ref() {
ListImpl::Cons(_h, t) => List(t.clone()),
ListImpl::Nil => List(Arc::new(ListImpl::Nil))
}
}
}
#[cfg(test)]
mod test {
use super::*;
use alloc::string::String;
use alloc::string::ToString;
impl<T: Copy> List<T> {
fn map_strong_count(&self) -> String {
let mut sc = Arc::strong_count(&self.0).to_string();
let mut arc = &self.0;
loop {
match arc.as_ref() {
ListImpl::Cons(_h, t) => {
arc = t;
sc.push_str(", ");
sc.push_str(Arc::strong_count(arc).to_string().as_str());
},
ListImpl::Nil => break
}
}
sc
}
}
#[test]
fn test_empty() {
let empty_list: List<i32> = List::empty();
assert!(empty_list.head().is_none());
assert!(empty_list.is_empty());
}
#[test]
fn test_add() {
let empty_list: List<i32> = List::empty();
let one_item_list = empty_list.add(17);
assert!(!one_item_list.is_empty());
assert_eq!(one_item_list.head(), Some(17));
}
#[test]
fn test_fold() {
let list: List<i32> = List::new(&[1, 2, 3, 4]);
let sum = list.fold(&0, |x, y| x + y);
assert_eq!(sum, 10);
}
#[test]
fn test_map() {
let list: List<i32> = List::new(&[1, 2, 3, 4]);
let list_double = list.map(|x| x * 2);
assert_eq!(list_double.head(), Some(2));
assert_eq!(list_double.tail().head(), Some(4));
assert_eq!(list_double.tail().tail().head(), Some(6));
assert_eq!(list_double.tail().tail().tail().head(), Some(8));
}
#[test]
fn test_context() {
let list: List<i32> = List::new(&[1, 2, 3, 4]);
let count_list = list.map_strong_count();
assert_eq!(count_list, "1, 1, 1, 1, 1");
{
let lt = list.tail();
let cl_lt = lt.map_strong_count();
assert_eq!(cl_lt, "2, 1, 1, 1");
let count_list = list.map_strong_count();
assert_eq!(count_list, "1, 2, 1, 1, 1");
{
let lm = list.map(|x| x * 2);
let cl_lm = lm.map_strong_count();
assert_eq!(cl_lm, "1, 1, 1, 1, 1");
let count_list = list.map_strong_count();
assert_eq!(count_list, "1, 2, 1, 1, 1");
}
let count_list = list.map_strong_count();
assert_eq!(count_list, "1, 2, 1, 1, 1");
let ltt = lt.tail();
let cl_ltt = ltt.map_strong_count();
assert_eq!(cl_ltt, "2, 1, 1");
let count_list = list.map_strong_count();
assert_eq!(count_list, "1, 2, 2, 1, 1");
{
let ltta = ltt.add(3);
let cl_ltta = ltta.map_strong_count();
assert_eq!(cl_ltta, "1, 3, 1, 1");
let count_list = list.map_strong_count();
assert_eq!(count_list, "1, 2, 3, 1, 1");
}
let cl_ltt = ltt.map_strong_count();
assert_eq!(cl_ltt, "2, 1, 1");
let count_list = list.map_strong_count();
assert_eq!(count_list, "1, 2, 2, 1, 1");
}
let count_list = list.map_strong_count();
assert_eq!(count_list, "1, 1, 1, 1, 1");
}
}
| 28.247312 | 81 | 0.455082 |
e9810bba05331ae07d459325b9cdec064fe77f3b
| 11,670 |
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
//! Mappings for the content of dwrite_2.h
use ctypes::{c_void, wchar_t};
use shared::basetsd::{UINT16, UINT32, UINT8};
use shared::d3d9types::D3DCOLORVALUE;
use shared::minwindef::{BOOL, FLOAT};
use um::dcommon::DWRITE_MEASURING_MODE;
use um::dwrite::{
DWRITE_FONT_FEATURE_TAG, DWRITE_FONT_STRETCH, DWRITE_FONT_STYLE, DWRITE_FONT_WEIGHT,
DWRITE_GLYPH_RUN, DWRITE_GLYPH_RUN_DESCRIPTION, DWRITE_MATRIX, DWRITE_PIXEL_GEOMETRY,
DWRITE_RENDERING_MODE, DWRITE_SCRIPT_ANALYSIS, DWRITE_STRIKETHROUGH, DWRITE_UNDERLINE,
IDWriteFont, IDWriteFontCollection, IDWriteFontFace, IDWriteGlyphRunAnalysis,
IDWriteInlineObject, IDWriteRenderingParams, IDWriteTextAnalysisSource, IDWriteTextFormat,
IDWriteTextFormatVtbl, IDWriteTextRenderer, IDWriteTextRendererVtbl,
};
use um::dwrite_1::{
DWRITE_GLYPH_ORIENTATION_ANGLE, DWRITE_OUTLINE_THRESHOLD, DWRITE_TEXT_ANTIALIAS_MODE,
DWRITE_UNICODE_RANGE, DWRITE_VERTICAL_GLYPH_ORIENTATION, IDWriteFactory1,
IDWriteFactory1Vtbl, IDWriteFont1, IDWriteFont1Vtbl, IDWriteFontFace1, IDWriteFontFace1Vtbl,
IDWriteRenderingParams1, IDWriteRenderingParams1Vtbl, IDWriteTextAnalyzer1,
IDWriteTextAnalyzer1Vtbl, IDWriteTextLayout1, IDWriteTextLayout1Vtbl,
};
use um::unknwnbase::{IUnknown, IUnknownVtbl};
use um::winnt::{HRESULT, WCHAR};
ENUM!{enum DWRITE_OPTICAL_ALIGNMENT {
DWRITE_OPTICAL_ALIGNMENT_NONE = 0x0, // 0
DWRITE_OPTICAL_ALIGNMENT_NO_SIDE_BEARINGS = 0x1, // 1
}}
ENUM!{enum DWRITE_GRID_FIT_MODE {
DWRITE_GRID_FIT_MODE_DEFAULT = 0x0, // 0
DWRITE_GRID_FIT_MODE_DISABLED = 0x1, // 1
DWRITE_GRID_FIT_MODE_ENABLED = 0x2, // 2
}}
STRUCT!{struct DWRITE_TEXT_METRICS1 {
left: FLOAT,
top: FLOAT,
width: FLOAT,
widthIncludingTrailingWhitespace: FLOAT,
height: FLOAT,
layoutWidth: FLOAT,
layoutHeight: FLOAT,
maxBidiReorderingDepth: UINT32,
lineCount: UINT32,
heightIncludingTrailingWhitespace: FLOAT,
}}
RIDL!{#[uuid(0xd3e0e934, 0x22a0, 0x427e, 0xaa, 0xe4, 0x7d, 0x95, 0x74, 0xb5, 0x9d, 0xb1)]
interface IDWriteTextRenderer1(IDWriteTextRenderer1Vtbl):
IDWriteTextRenderer(IDWriteTextRendererVtbl) {
fn DrawGlyphRun(
clientDrawingContext: *mut c_void,
baselineOriginX: FLOAT,
baselineOriginY: FLOAT,
orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
measuringMode: DWRITE_MEASURING_MODE,
glyphRun: *const DWRITE_GLYPH_RUN,
glyphRunDescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
clientDrawingEffect: *mut IUnknown,
) -> HRESULT,
fn DrawUnderline(
clientDrawingContext: *mut c_void,
baselineOriginX: FLOAT,
baselineOriginY: FLOAT,
orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
underline: *const DWRITE_UNDERLINE,
clientDrawingEffect: *mut IUnknown,
) -> HRESULT,
fn DrawStrikethrough(
clientDrawingContext: *mut c_void,
baselineOriginX: FLOAT,
baselineOriginY: FLOAT,
orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
strikethrough: *const DWRITE_STRIKETHROUGH,
clientDrawingEffect: *mut IUnknown,
) -> HRESULT,
fn DrawInlineObject(
clientDrawingContext: *mut c_void,
originX: FLOAT,
originY: FLOAT,
orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
inlineObject: *mut IDWriteInlineObject,
isSideways: BOOL,
isRightToLeft: BOOL,
clientDrawingEffect: *mut IUnknown,
) -> HRESULT,
}}
RIDL!{#[uuid(0x5f174b49, 0x0d8b, 0x4cfb, 0x8b, 0xca, 0xf1, 0xcc, 0xe9, 0xd0, 0x6c, 0x67)]
interface IDWriteTextFormat1(IDWriteTextFormat1Vtbl):
IDWriteTextFormat(IDWriteTextFormatVtbl) {
fn SetVerticalGlyphOrientation(
glyphOrientation: DWRITE_VERTICAL_GLYPH_ORIENTATION,
) -> HRESULT,
fn GetVerticalGlyphOrientation() -> DWRITE_VERTICAL_GLYPH_ORIENTATION,
fn SetLastLineWrapping(
isLastLineWrappingEnabled: BOOL,
) -> HRESULT,
fn GetLastLineWrapping() -> BOOL,
fn SetOpticalAlignment(
opticalAlignment: DWRITE_OPTICAL_ALIGNMENT,
) -> HRESULT,
fn GetOpticalAlignment() -> DWRITE_OPTICAL_ALIGNMENT,
fn SetFontFallback(
fontFallback: *mut IDWriteFontFallback,
) -> HRESULT,
fn GetFontFallback(
fontFallback: *mut *mut IDWriteFontFallback,
) -> HRESULT,
}}
RIDL!{#[uuid(0x1093c18f, 0x8d5e, 0x43f0, 0xb0, 0x64, 0x09, 0x17, 0x31, 0x1b, 0x52, 0x5e)]
interface IDWriteTextLayout2(IDWriteTextLayout2Vtbl):
IDWriteTextLayout1(IDWriteTextLayout1Vtbl) {
fn GetMetrics(
textMetrics: *mut DWRITE_TEXT_METRICS1,
) -> HRESULT,
fn SetVerticalGlyphOrientation(
glyphOrientation: DWRITE_VERTICAL_GLYPH_ORIENTATION,
) -> HRESULT,
fn GetVerticalGlyphOrientation() -> DWRITE_VERTICAL_GLYPH_ORIENTATION,
fn SetLastLineWrapping(
isLastLineWrappingEnabled: BOOL,
) -> HRESULT,
fn GetLastLineWrapping() -> BOOL,
fn SetOpticalAlignment(
opticalAlignment: DWRITE_OPTICAL_ALIGNMENT,
) -> HRESULT,
fn GetOpticalAlignment() -> DWRITE_OPTICAL_ALIGNMENT,
fn SetFontFallback(
fontFallback: *mut IDWriteFontFallback,
) -> HRESULT,
fn GetFontFallback(
fontFallback: *mut *mut IDWriteFontFallback,
) -> HRESULT,
}}
RIDL!{#[uuid(0x553a9ff3, 0x5693, 0x4df7, 0xb5, 0x2b, 0x74, 0x80, 0x6f, 0x7f, 0x2e, 0xb9)]
interface IDWriteTextAnalyzer2(IDWriteTextAnalyzer2Vtbl):
IDWriteTextAnalyzer1(IDWriteTextAnalyzer1Vtbl) {
fn GetGlyphOrientationTransform(
glyphOrientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
isSideways: BOOL,
originX: FLOAT,
originY: FLOAT,
transform: *mut DWRITE_MATRIX,
) -> HRESULT,
fn GetTypographicFeatures(
fontFace: *mut IDWriteFontFace,
scriptAnalysis: DWRITE_SCRIPT_ANALYSIS,
localeName: *const WCHAR,
maxTagCount: UINT32,
actualTagCount: *mut UINT32,
tags: *mut DWRITE_FONT_FEATURE_TAG,
) -> HRESULT,
fn CheckTypographicFeature(
fontFace: *mut IDWriteFontFace,
scriptAnalysis: DWRITE_SCRIPT_ANALYSIS,
localeName: *const WCHAR,
featureTag: DWRITE_FONT_FEATURE_TAG,
glyphCount: UINT32,
glyphIndices: *const UINT16,
featureApplies: *mut UINT8,
) -> HRESULT,
}}
RIDL!{#[uuid(0xefa008f9, 0xf7a1, 0x48bf, 0xb0, 0x5c, 0xf2, 0x24, 0x71, 0x3c, 0xc0, 0xff)]
interface IDWriteFontFallback(IDWriteFontFallbackVtbl): IUnknown(IUnknownVtbl) {
fn MapCharacters(
analysisSource: *mut IDWriteTextAnalysisSource,
textPosition: UINT32,
textLength: UINT32,
baseFontCollection: *mut IDWriteFontCollection,
baseFamilyName: *mut wchar_t,
baseWeight: DWRITE_FONT_WEIGHT,
baseStyle: DWRITE_FONT_STYLE,
baseStretch: DWRITE_FONT_STRETCH,
mappedLength: *mut UINT32,
mappedFont: *mut *mut IDWriteFont,
scale: *mut FLOAT,
) -> HRESULT,
}}
RIDL!{#[uuid(0xfd882d06, 0x8aba, 0x4fb8, 0xb8, 0x49, 0x8b, 0xe8, 0xb7, 0x3e, 0x14, 0xde)]
interface IDWriteFontFallbackBuilder(IDWriteFontFallbackBuilderVtbl):
IUnknown(IUnknownVtbl) {
fn AddMapping(
ranges: *const DWRITE_UNICODE_RANGE,
rangesCount: UINT32,
targetFamilyNames: *mut *const WCHAR,
targetFamilyNamesCount: UINT32,
fontCollection: *mut IDWriteFontCollection,
localeName: *const WCHAR,
baseFamilyName: *const WCHAR,
scale: FLOAT,
) -> HRESULT,
fn AddMappings(
fontFallback: *mut IDWriteFontFallback,
) -> HRESULT,
fn CreateFontFallback(
fontFallback: *mut *mut IDWriteFontFallback,
) -> HRESULT,
}}
pub type DWRITE_COLOR_F = D3DCOLORVALUE;
RIDL!{#[uuid(0x29748ed6, 0x8c9c, 0x4a6a, 0xbe, 0x0b, 0xd9, 0x12, 0xe8, 0x53, 0x89, 0x44)]
interface IDWriteFont2(IDWriteFont2Vtbl): IDWriteFont1(IDWriteFont1Vtbl) {
fn IsColorFont() -> BOOL,
}}
RIDL!{#[uuid(0xd8b768ff, 0x64bc, 0x4e66, 0x98, 0x2b, 0xec, 0x8e, 0x87, 0xf6, 0x93, 0xf7)]
interface IDWriteFontFace2(IDWriteFontFace2Vtbl):
IDWriteFontFace1(IDWriteFontFace1Vtbl) {
fn IsColorFont() -> BOOL,
fn GetColorPaletteCount() -> UINT32,
fn GetPaletteEntryCount() -> UINT32,
fn GetPaletteEntries(
colorPaletteIndex: UINT32,
firstEntryIndex: UINT32,
entryCount: UINT32,
paletteEntries: *mut DWRITE_COLOR_F,
) -> HRESULT,
fn GetRecommendedRenderingMode(
fontEmSize: FLOAT,
dpiX: FLOAT,
dpiY: FLOAT,
transform: *const DWRITE_MATRIX,
isSideways: BOOL,
outlineThreshold: DWRITE_OUTLINE_THRESHOLD,
measuringMode: DWRITE_MEASURING_MODE,
renderingParams: *mut IDWriteRenderingParams,
renderingMode: *mut DWRITE_RENDERING_MODE,
gridFitMode: *mut DWRITE_GRID_FIT_MODE,
) -> HRESULT,
}}
STRUCT!{struct DWRITE_COLOR_GLYPH_RUN {
glyphRun: DWRITE_GLYPH_RUN,
glyphRunDescription: *mut DWRITE_GLYPH_RUN_DESCRIPTION,
baselineOriginX: FLOAT,
baselineOriginY: FLOAT,
runColor: DWRITE_COLOR_F,
paletteIndex: UINT16,
}}
RIDL!{#[uuid(0xd31fbe17, 0xf157, 0x41a2, 0x8d, 0x24, 0xcb, 0x77, 0x9e, 0x05, 0x60, 0xe8)]
interface IDWriteColorGlyphRunEnumerator(IDWriteColorGlyphRunEnumeratorVtbl):
IUnknown(IUnknownVtbl) {
fn MoveNext(
hasRun: *mut BOOL,
) -> HRESULT,
fn GetCurrentRun(
colorGlyphRun: *mut *const DWRITE_COLOR_GLYPH_RUN,
) -> HRESULT,
}}
RIDL!{#[uuid(0xf9d711c3, 0x9777, 0x40ae, 0x87, 0xe8, 0x3e, 0x5a, 0xf9, 0xbf, 0x09, 0x48)]
interface IDWriteRenderingParams2(IDWriteRenderingParams2Vtbl):
IDWriteRenderingParams1(IDWriteRenderingParams1Vtbl) {
fn GetGridFitMode() -> DWRITE_GRID_FIT_MODE,
}}
RIDL!{#[uuid(0x0439fc60, 0xca44, 0x4994, 0x8d, 0xee, 0x3a, 0x9a, 0xf7, 0xb7, 0x32, 0xec)]
interface IDWriteFactory2(IDWriteFactory2Vtbl): IDWriteFactory1(IDWriteFactory1Vtbl) {
fn GetSystemFontFallback(
fontFallback: *mut *mut IDWriteFontFallback,
) -> HRESULT,
fn CreateFontFallbackBuilder(
fontFallbackBuilder: *mut *mut IDWriteFontFallbackBuilder,
) -> HRESULT,
fn TranslateColorGlyphRun(
baselineOriginX: FLOAT,
baselineOriginY: FLOAT,
glyphRun: *const DWRITE_GLYPH_RUN,
glyphRunDescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
measuringMode: DWRITE_MEASURING_MODE,
worldToDeviceTransform: *const DWRITE_MATRIX,
colorPaletteIndex: UINT32,
colorLayers: *mut *mut IDWriteColorGlyphRunEnumerator,
) -> HRESULT,
fn CreateCustomRenderingParams(
gamma: FLOAT,
enhancedContrast: FLOAT,
grayscaleEnhancedContrast: FLOAT,
clearTypeLevel: FLOAT,
pixelGeometry: DWRITE_PIXEL_GEOMETRY,
renderingMode: DWRITE_RENDERING_MODE,
gridFitMode: DWRITE_GRID_FIT_MODE,
renderingParams: *mut *mut IDWriteRenderingParams2,
) -> HRESULT,
fn CreateGlyphRunAnalysis(
glyphRun: *const DWRITE_GLYPH_RUN,
transform: *const DWRITE_MATRIX,
renderingMode: DWRITE_RENDERING_MODE,
measuringMode: DWRITE_MEASURING_MODE,
gridFitMode: DWRITE_GRID_FIT_MODE,
antialiasMode: DWRITE_TEXT_ANTIALIAS_MODE,
baselineOriginX: FLOAT,
baselineOriginY: FLOAT,
glyphRunAnalysis: *mut *mut IDWriteGlyphRunAnalysis,
) -> HRESULT,
}}
| 39.693878 | 96 | 0.715767 |
f71c86fb10fa6f83723af57b0708bc1d8ad1bd98
| 3,244 |
use std::fmt::Debug;
///! Contains Basic setup for testing, testable trait and its result type
use anyhow::{bail, Error, Result};
#[derive(Debug)]
/// Enum indicating result of the test. This is like an extended std::result,
/// which includes a Skip variant to indicate that a test was skipped, and the Ok variant has no associated value
pub enum TestResult {
/// Test was ok
Passed,
/// Test needed to be skipped
Skipped,
/// Test was error
Failed(Error),
}
impl<T> From<Result<T>> for TestResult {
fn from(result: Result<T>) -> Self {
match result {
Ok(_) => TestResult::Passed,
Err(err) => TestResult::Failed(err),
}
}
}
/// This trait indicates that something can be run as a test, or is 'testable'
/// This forms the basis of the framework, as all places where tests are done,
/// expect structs which implement this
pub trait Testable<'a> {
fn get_name(&self) -> &'a str;
fn can_run(&self) -> bool {
true
}
fn run(&self) -> TestResult;
}
/// This trait indicates that something forms a group of tests.
/// Test groups are used to group tests in sensible manner as well as provide namespacing to tests
pub trait TestableGroup<'a> {
fn get_name(&self) -> &'a str;
fn run_all(&'a self) -> Vec<(&'a str, TestResult)>;
fn run_selected(&'a self, selected: &[&str]) -> Vec<(&'a str, TestResult)>;
}
#[macro_export]
macro_rules! test_result {
($e:expr $(,)?) => {
match $e {
core::result::Result::Ok(val) => val,
core::result::Result::Err(err) => {
return $crate::testable::TestResult::Failed(err);
}
}
};
}
#[macro_export]
macro_rules! assert_result_eq {
($expected:expr, $actual:expr $(,)?) => ({
match (&$expected, &$actual) {
(expected_val, actual_val) => {
if !(*expected_val == *actual_val) {
test_framework::testable::assert_failed(&*expected_val, &*actual_val, std::option::Option::None)
} else {
Ok(())
}
}
}
});
($expected:expr, $actual:expr, $($arg:tt)+) => ({
match (&$expected, &$actual) {
(expected_val, actual_val) => {
if !(*expected_val == *actual_val) {
test_framework::testable::assert_failed(&*expected_val, &*actual_val, std::option::Option::Some(format_args!($($arg)+)))
} else {
Ok(())
}
}
}
});
}
#[doc(hidden)]
pub fn assert_failed<T, U>(
expected: &T,
actual: &U,
args: Option<std::fmt::Arguments<'_>>,
) -> Result<()>
where
T: Debug + ?Sized,
U: Debug + ?Sized,
{
match args {
Some(args) => {
bail!(
r#"assertion failed:
expected: `{:?}`,
actual: `{:?}`: {}"#,
expected,
actual,
args
)
}
None => {
bail!(
r#"assertion failed:
expected: `{:?}`,
actual: `{:?}`"#,
expected,
actual
)
}
}
}
| 27.965517 | 140 | 0.512022 |
fedf9fe3c3edd60b5e8337f3e5445383e1e0b390
| 799 |
use super::*;
use ::png;
///
/// Creates a PNG image in memory for an RGBA buffer
///
pub fn png_data_for_rgba(rgba: &[u8], width: u32, height: u32) -> InMemoryImageData {
// Create the buffer to write the PNG data to
let mut png_data: Vec<u8> = vec![];
{
// Create an encoder that will write to this buffer
let mut png_encoder = png::Encoder::new(&mut png_data, width, height);
png_encoder.set_color(png::ColorType::RGBA);
png_encoder.set_depth(png::BitDepth::Eight);
// Write the header
let mut png_writer = png_encoder.write_header().unwrap();
// Write the image data
png_writer.write_image_data(rgba).unwrap();
}
// Generate the image data object for the final PNG
InMemoryImageData::from(png_data)
}
| 28.535714 | 85 | 0.645807 |
115b6bf947a5450742dbbcfef8a86ec4ad7165e8
| 2,554 |
use crate::common::resources::{ResourceAllocation, ResourceRequest};
use crate::common::WrappedRcRefCell;
use crate::messages::worker::ComputeTaskMsg;
use crate::worker::data::DataObjectRef;
use crate::worker::taskenv::TaskEnv;
use crate::{OutputId, Priority, TaskId, TaskTypeId};
pub enum TaskState {
Waiting(u32),
Uploading(TaskEnv, u32, ResourceAllocation),
Running(TaskEnv, ResourceAllocation),
Removed,
}
pub struct Task {
pub id: TaskId,
pub type_id: TaskTypeId,
pub state: TaskState,
pub priority: (Priority, Priority),
pub deps: Vec<DataObjectRef>,
pub resources: ResourceRequest,
pub n_outputs: OutputId,
pub spec: Vec<u8>,
}
impl Task {
#[inline]
pub fn is_waiting(&self) -> bool {
matches!(self.state, TaskState::Waiting(_))
}
#[inline]
pub fn is_ready(&self) -> bool {
matches!(self.state, TaskState::Waiting(0))
}
#[inline]
pub fn is_running(&self) -> bool {
matches!(self.state, TaskState::Running(_, _))
}
pub fn is_removed(&self) -> bool {
matches!(self.state, TaskState::Removed)
}
pub fn resource_allocation(&self) -> Option<&ResourceAllocation> {
match &self.state {
TaskState::Uploading(_, _, a) | TaskState::Running(_, a) => Some(a),
TaskState::Waiting(_) => None,
TaskState::Removed => unreachable!(),
}
}
pub fn get_waiting(&self) -> u32 {
match self.state {
TaskState::Waiting(x) => x,
_ => 0,
}
}
pub fn decrease_waiting_count(&mut self) -> bool {
match &mut self.state {
TaskState::Waiting(ref mut x) => {
assert!(*x > 0);
*x -= 1;
*x == 0
}
_ => unreachable!(),
}
}
pub fn increase_waiting_count(&mut self) {
match &mut self.state {
TaskState::Waiting(ref mut x) => {
*x += 1;
}
_ => unreachable!(),
}
}
}
pub type TaskRef = WrappedRcRefCell<Task>;
impl TaskRef {
pub fn new(message: ComputeTaskMsg) -> Self {
TaskRef::wrap(Task {
id: message.id,
type_id: message.type_id,
n_outputs: message.n_outputs,
spec: message.spec,
priority: (message.user_priority, message.scheduler_priority),
state: TaskState::Waiting(0),
deps: Default::default(),
resources: message.resources,
})
}
}
| 26.061224 | 80 | 0.559514 |
0957d641027466c080f450ff0b415f66e9b1957e
| 4,321 |
//! # lorri
//! lorri is a wrapper over Nix to abstract project-specific build
//! configuration and patterns in to a declarative configuration.
#![warn(missing_docs)]
// We usually want to use matches for clarity
#![allow(clippy::match_bool)]
#![allow(clippy::single_match)]
// I don’t think return, .into() is clearer than ?, sorry
#![allow(clippy::try_err)]
// triggered by select (TODO: fixed in crossbeam_channel 0.5)
#![allow(clippy::drop_copy, clippy::zero_ptr)]
// Remove clippy checks for stuff that is not even in stable yet (ugh)
#![allow(clippy::match_like_matches_macro)]
#[macro_use]
extern crate structopt;
#[macro_use]
extern crate serde_derive;
pub mod bash;
pub mod build_loop;
pub mod builder;
pub mod cas;
pub mod changelog;
pub mod cli;
pub mod constants;
pub mod daemon;
pub mod error;
pub mod locate_file;
pub mod logging;
pub mod nix;
pub mod ops;
pub mod osstrlines;
pub mod pathreduction;
pub mod project;
pub mod run_async;
pub mod socket;
pub mod thread;
pub mod watch;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
// OUT_DIR and build_rev.rs are generated by cargo, see ../build.rs
include!(concat!(env!("OUT_DIR"), "/build_rev.rs"));
/// Path guaranteed to be absolute by construction.
#[derive(Hash, PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub struct AbsPathBuf(PathBuf);
impl AbsPathBuf {
/// Convert from a path to an absolute path.
///
/// If the path is not absolute, the original `PathBuf`
/// is returned (similar to `OsString.into_string()`)
pub fn new(path: PathBuf) -> Result<Self, PathBuf> {
if path.is_absolute() {
Ok(Self::new_unchecked(path))
} else {
Err(path)
}
}
/// Convert from a known absolute path.
///
/// Passing a relative path is a programming bug (unchecked).
pub fn new_unchecked(path: PathBuf) -> Self {
AbsPathBuf(path)
}
/// The absolute path, as `&Path`.
pub fn as_absolute_path(&self) -> &Path {
&self.0
}
/// Proxy through the `Display` class for `PathBuf`.
pub fn display(&self) -> std::path::Display {
self.0.display()
}
/// Joins a path to the end of this absolute path.
/// If the path is absolute, it will replace this absolute path.
pub fn join<P: AsRef<Path>>(&self, pb: P) -> Self {
let mut new = self.0.to_owned();
new.push(pb);
Self::new_unchecked(new)
}
/// Proxy through `with_file_name` for `PathBuf`
pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> Self {
// replacing the file name will never make the path relative
Self::new_unchecked(self.0.with_file_name(file_name))
}
}
impl AsRef<Path> for AbsPathBuf {
fn as_ref(&self) -> &Path {
self.as_absolute_path()
}
}
/// A .nix file.
///
/// Is guaranteed to have an absolute path by construction.
#[derive(Hash, PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub struct NixFile(AbsPathBuf);
impl NixFile {
/// Absolute path of this file.
pub fn as_absolute_path(&self) -> &Path {
&self.0.as_absolute_path()
}
}
impl NixFile {
/// `display` the path.
pub fn display(&self) -> std::path::Display {
self.0.display()
}
}
impl From<AbsPathBuf> for NixFile {
fn from(abs_path: AbsPathBuf) -> Self {
NixFile(abs_path)
}
}
impl slog::Value for NixFile {
fn serialize(
&self,
_record: &slog::Record,
key: slog::Key,
serializer: &mut dyn slog::Serializer,
) -> slog::Result {
serializer.emit_arguments(key, &format_args!("{}", self.as_absolute_path().display()))
}
}
/// A .drv file (generated by `nix-instantiate`).
#[derive(Hash, PartialEq, Eq, Clone, Debug)]
pub struct DrvFile(PathBuf);
impl DrvFile {
/// Underlying `Path`.
pub fn as_path(&self) -> &Path {
self.0.as_ref()
}
}
impl From<PathBuf> for DrvFile {
fn from(p: PathBuf) -> DrvFile {
DrvFile(p)
}
}
/// Struct that will never be constructed (no elements).
/// In newer rustc, this corresponds to the (compiler supported) `!` type.
pub struct Never {}
impl Never {
/// This will never be called, so we can return anything.
pub fn never<T>(&self) -> T {
panic!("can never be called");
}
}
| 25.874251 | 94 | 0.641055 |
1c4ae9ee1d58769226fca39e7018ad5864a17c7c
| 4,555 |
//! Abstractions over the proving system and parameters.
use crate::{
merkle_tree::MerklePath,
sapling::{
redjubjub::{PublicKey, Signature},
Node,
},
transaction::components::{Amount, GROTH_PROOF_SIZE},
};
use super::{Diversifier, PaymentAddress, ProofGenerationKey, Rseed};
/// Interface for creating zero-knowledge proofs for shielded transactions.
pub trait TxProver {
/// Type for persisting any necessary context across multiple Sapling proofs.
type SaplingProvingContext;
/// Instantiate a new Sapling proving context.
fn new_sapling_proving_context(&self) -> Self::SaplingProvingContext;
/// Create the value commitment, re-randomized key, and proof for a Sapling
/// [`SpendDescription`], while accumulating its value commitment randomness inside
/// the context for later use.
///
/// [`SpendDescription`]: crate::transaction::components::SpendDescription
#[allow(clippy::too_many_arguments)]
fn spend_proof(
&self,
ctx: &mut Self::SaplingProvingContext,
proof_generation_key: ProofGenerationKey,
diversifier: Diversifier,
rseed: Rseed,
ar: jubjub::Fr,
value: u64,
anchor: bls12_381::Scalar,
merkle_path: MerklePath<Node>,
) -> Result<([u8; GROTH_PROOF_SIZE], jubjub::ExtendedPoint, PublicKey), ()>;
/// Create the value commitment and proof for a Sapling [`OutputDescription`],
/// while accumulating its value commitment randomness inside the context for later
/// use.
///
/// [`OutputDescription`]: crate::transaction::components::OutputDescription
fn output_proof(
&self,
ctx: &mut Self::SaplingProvingContext,
esk: jubjub::Fr,
payment_address: PaymentAddress,
rcm: jubjub::Fr,
value: u64,
) -> ([u8; GROTH_PROOF_SIZE], jubjub::ExtendedPoint);
/// Create the `bindingSig` for a Sapling transaction. All calls to
/// [`TxProver::spend_proof`] and [`TxProver::output_proof`] must be completed before
/// calling this function.
fn binding_sig(
&self,
ctx: &mut Self::SaplingProvingContext,
value_balance: Amount,
sighash: &[u8; 32],
) -> Result<Signature, ()>;
}
#[cfg(any(test, feature = "test-dependencies"))]
pub mod mock {
use ff::Field;
use rand_core::OsRng;
use crate::{
constants::SPENDING_KEY_GENERATOR,
merkle_tree::MerklePath,
sapling::{
redjubjub::{PublicKey, Signature},
Diversifier, Node, PaymentAddress, ProofGenerationKey, Rseed, ValueCommitment,
},
transaction::components::{Amount, GROTH_PROOF_SIZE},
};
use super::TxProver;
pub struct MockTxProver;
impl TxProver for MockTxProver {
type SaplingProvingContext = ();
fn new_sapling_proving_context(&self) -> Self::SaplingProvingContext {}
fn spend_proof(
&self,
_ctx: &mut Self::SaplingProvingContext,
proof_generation_key: ProofGenerationKey,
_diversifier: Diversifier,
_rcm: Rseed,
ar: jubjub::Fr,
value: u64,
_anchor: bls12_381::Scalar,
_merkle_path: MerklePath<Node>,
) -> Result<([u8; GROTH_PROOF_SIZE], jubjub::ExtendedPoint, PublicKey), ()> {
let mut rng = OsRng;
let cv = ValueCommitment {
value,
randomness: jubjub::Fr::random(&mut rng),
}
.commitment()
.into();
let rk = PublicKey(proof_generation_key.ak.clone().into())
.randomize(ar, SPENDING_KEY_GENERATOR);
Ok(([0u8; GROTH_PROOF_SIZE], cv, rk))
}
fn output_proof(
&self,
_ctx: &mut Self::SaplingProvingContext,
_esk: jubjub::Fr,
_payment_address: PaymentAddress,
_rcm: jubjub::Fr,
value: u64,
) -> ([u8; GROTH_PROOF_SIZE], jubjub::ExtendedPoint) {
let mut rng = OsRng;
let cv = ValueCommitment {
value,
randomness: jubjub::Fr::random(&mut rng),
}
.commitment()
.into();
([0u8; GROTH_PROOF_SIZE], cv)
}
fn binding_sig(
&self,
_ctx: &mut Self::SaplingProvingContext,
_value_balance: Amount,
_sighash: &[u8; 32],
) -> Result<Signature, ()> {
Err(())
}
}
}
| 31.413793 | 90 | 0.592097 |
8fdfce31e9bf5feabff9ea856adfe19e2773a35c
| 1,589 |
use crate::prelude::*;
pub mod grid_routine;
/// Adds the necessary nodes to render the 3d viewport of the app. The viewport
/// is rendered into a render target, and its handle is returned.
#[allow(clippy::too_many_arguments)]
pub fn blackjack_viewport_rendergraph<'node>(
base: &'node r3::BaseRenderGraph,
graph: &mut r3::RenderGraph<'node>,
ready: &r3::ReadyData,
pbr: &'node r3::PbrRoutine,
tonemapping: &'node r3::TonemappingRoutine,
grid: &'node grid_routine::GridRoutine,
resolution: UVec2,
samples: r3::SampleCount,
ambient: Vec4,
) -> r3::RenderTargetHandle {
// Create intermediate storage
let state = r3::BaseRenderGraphIntermediateState::new(graph, ready, resolution, samples);
// Preparing and uploading data
state.pbr_pre_culling(graph);
state.create_frame_uniforms(graph, base, ambient);
// Culling
state.pbr_shadow_culling(graph, base, pbr);
state.pbr_culling(graph, base, pbr);
// Depth-only rendering
state.pbr_prepass_rendering(graph, pbr, samples);
// Forward rendering
state.pbr_forward_rendering(graph, pbr, samples);
grid.add_to_graph(graph, &state);
// Make the reference to the surface
let output = graph.add_render_target(r3::RenderTargetDescriptor {
label: Some("Blackjack Viewport Output".into()),
resolution,
samples,
format: r3::TextureFormat::Bgra8UnormSrgb,
usage: r3::TextureUsages::RENDER_ATTACHMENT | r3::TextureUsages::TEXTURE_BINDING,
});
state.tonemapping(graph, tonemapping, output);
output
}
| 31.78 | 93 | 0.699182 |
ab96c50a006297a94416aafaca6c53a2081e60df
| 2,204 |
#![warn(missing_docs)]
use std::sync::Arc;
use parallel_runtime::opaque::Block;
use primitives::{AccountId, Balance, CurrencyId, DataProviderId, Index, TimeStampedPrice};
pub use sc_rpc_api::DenyUnsafe;
use sp_api::ProvideRuntimeApi;
use sp_block_builder::BlockBuilder;
use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
use sp_transaction_pool::TransactionPool;
/// Full client dependencies.
pub struct FullDeps<C, P> {
/// The client instance to use.
pub client: Arc<C>,
/// Transaction pool instance.
pub pool: Arc<P>,
/// Whether to deny unsafe calls
pub deny_unsafe: DenyUnsafe,
}
/// Instantiate all full RPC extensions.
pub fn create_full<C, P>(deps: FullDeps<C, P>) -> jsonrpc_core::IoHandler<sc_rpc::Metadata>
where
C: ProvideRuntimeApi<Block>,
C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
C: Send + Sync + 'static,
C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
C::Api: orml_oracle_rpc::OracleRuntimeApi<Block, DataProviderId, CurrencyId, TimeStampedPrice>,
C::Api: BlockBuilder<Block>,
P: TransactionPool + 'static,
{
use orml_oracle_rpc::{Oracle, OracleApi};
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};
use substrate_frame_rpc_system::{FullSystem, SystemApi};
let mut io = jsonrpc_core::IoHandler::default();
let FullDeps {
client,
pool,
deny_unsafe,
} = deps;
io.extend_with(SystemApi::to_delegate(FullSystem::new(
client.clone(),
pool,
deny_unsafe,
)));
io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(
client.clone(),
)));
// Extend this RPC with a custom API by using the following syntax.
// `YourRpcStruct` should have a reference to a client, which is needed
// to call into the runtime.
// `io.extend_with(YourRpcTrait::to_delegate(YourRpcStruct::new(ReferenceToClient, ...)));`
io.extend_with(OracleApi::to_delegate(Oracle::new(client.clone())));
io
}
| 34.4375 | 99 | 0.71098 |
21e41f4127cb8a2087187f226506b9e2274db73b
| 7,031 |
use {
crate::{
parse_account_data::{ParsableAccount, ParseAccountError},
UiAccountData, UiAccountEncoding,
},
bincode::{deserialize, serialized_size},
paychains_sdk::{bpf_loader_upgradeable::UpgradeableLoaderState, pubkey::Pubkey},
};
pub fn parse_bpf_upgradeable_loader(
data: &[u8],
) -> Result<BpfUpgradeableLoaderAccountType, ParseAccountError> {
let account_state: UpgradeableLoaderState = deserialize(data).map_err(|_| {
ParseAccountError::AccountNotParsable(ParsableAccount::BpfUpgradeableLoader)
})?;
let parsed_account = match account_state {
UpgradeableLoaderState::Uninitialized => BpfUpgradeableLoaderAccountType::Uninitialized,
UpgradeableLoaderState::Buffer { authority_address } => {
let offset = if authority_address.is_some() {
UpgradeableLoaderState::buffer_data_offset().unwrap()
} else {
// This case included for code completeness; in practice, a Buffer account will
// always have authority_address.is_some()
UpgradeableLoaderState::buffer_data_offset().unwrap()
- serialized_size(&Pubkey::default()).unwrap() as usize
};
BpfUpgradeableLoaderAccountType::Buffer(UiBuffer {
authority: authority_address.map(|pubkey| pubkey.to_string()),
data: UiAccountData::Binary(
base64::encode(&data[offset as usize..]),
UiAccountEncoding::Base64,
),
})
}
UpgradeableLoaderState::Program {
programdata_address,
} => BpfUpgradeableLoaderAccountType::Program(UiProgram {
program_data: programdata_address.to_string(),
}),
UpgradeableLoaderState::ProgramData {
slot,
upgrade_authority_address,
} => {
let offset = if upgrade_authority_address.is_some() {
UpgradeableLoaderState::programdata_data_offset().unwrap()
} else {
UpgradeableLoaderState::programdata_data_offset().unwrap()
- serialized_size(&Pubkey::default()).unwrap() as usize
};
BpfUpgradeableLoaderAccountType::ProgramData(UiProgramData {
slot,
authority: upgrade_authority_address.map(|pubkey| pubkey.to_string()),
data: UiAccountData::Binary(
base64::encode(&data[offset as usize..]),
UiAccountEncoding::Base64,
),
})
}
};
Ok(parsed_account)
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", tag = "type", content = "info")]
pub enum BpfUpgradeableLoaderAccountType {
Uninitialized,
Buffer(UiBuffer),
Program(UiProgram),
ProgramData(UiProgramData),
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct UiBuffer {
pub authority: Option<String>,
pub data: UiAccountData,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct UiProgram {
pub program_data: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct UiProgramData {
pub slot: u64,
pub authority: Option<String>,
pub data: UiAccountData,
}
#[cfg(test)]
mod test {
use {super::*, bincode::serialize, paychains_sdk::pubkey::Pubkey};
#[test]
fn test_parse_bpf_upgradeable_loader_accounts() {
let bpf_loader_state = UpgradeableLoaderState::Uninitialized;
let account_data = serialize(&bpf_loader_state).unwrap();
assert_eq!(
parse_bpf_upgradeable_loader(&account_data).unwrap(),
BpfUpgradeableLoaderAccountType::Uninitialized
);
let program = vec![7u8; 64]; // Arbitrary program data
let authority = Pubkey::new_unique();
let bpf_loader_state = UpgradeableLoaderState::Buffer {
authority_address: Some(authority),
};
let mut account_data = serialize(&bpf_loader_state).unwrap();
account_data.extend_from_slice(&program);
assert_eq!(
parse_bpf_upgradeable_loader(&account_data).unwrap(),
BpfUpgradeableLoaderAccountType::Buffer(UiBuffer {
authority: Some(authority.to_string()),
data: UiAccountData::Binary(base64::encode(&program), UiAccountEncoding::Base64),
})
);
// This case included for code completeness; in practice, a Buffer account will always have
// authority_address.is_some()
let bpf_loader_state = UpgradeableLoaderState::Buffer {
authority_address: None,
};
let mut account_data = serialize(&bpf_loader_state).unwrap();
account_data.extend_from_slice(&program);
assert_eq!(
parse_bpf_upgradeable_loader(&account_data).unwrap(),
BpfUpgradeableLoaderAccountType::Buffer(UiBuffer {
authority: None,
data: UiAccountData::Binary(base64::encode(&program), UiAccountEncoding::Base64),
})
);
let programdata_address = Pubkey::new_unique();
let bpf_loader_state = UpgradeableLoaderState::Program {
programdata_address,
};
let account_data = serialize(&bpf_loader_state).unwrap();
assert_eq!(
parse_bpf_upgradeable_loader(&account_data).unwrap(),
BpfUpgradeableLoaderAccountType::Program(UiProgram {
program_data: programdata_address.to_string(),
})
);
let authority = Pubkey::new_unique();
let slot = 42;
let bpf_loader_state = UpgradeableLoaderState::ProgramData {
slot,
upgrade_authority_address: Some(authority),
};
let mut account_data = serialize(&bpf_loader_state).unwrap();
account_data.extend_from_slice(&program);
assert_eq!(
parse_bpf_upgradeable_loader(&account_data).unwrap(),
BpfUpgradeableLoaderAccountType::ProgramData(UiProgramData {
slot,
authority: Some(authority.to_string()),
data: UiAccountData::Binary(base64::encode(&program), UiAccountEncoding::Base64),
})
);
let bpf_loader_state = UpgradeableLoaderState::ProgramData {
slot,
upgrade_authority_address: None,
};
let mut account_data = serialize(&bpf_loader_state).unwrap();
account_data.extend_from_slice(&program);
assert_eq!(
parse_bpf_upgradeable_loader(&account_data).unwrap(),
BpfUpgradeableLoaderAccountType::ProgramData(UiProgramData {
slot,
authority: None,
data: UiAccountData::Binary(base64::encode(&program), UiAccountEncoding::Base64),
})
);
}
}
| 38.631868 | 99 | 0.626511 |
29b67f710041831c55ef1727518840a70fbe9d87
| 1,546 |
use macros::route_wrapper;
use warp::filters::BoxedFilter;
use warp::Filter;
use warp::Reply;
use crate::auth::{require_login, LoginGuard};
use crate::errors::AppError;
use crate::errors::Result;
use crate::state::AppState;
pub(super) fn route(state: AppState) -> BoxedFilter<(impl Reply,)> {
let with_state = with_state!(state);
let hello = warp::get().and(warp::path("hello")).and_then(hello);
let hello_error = warp::get()
.and(warp::path("hello_error"))
.and_then(hello_error);
let hello_require_login = warp::get()
.and(warp::path("hello_require_login"))
.and(require_login(state.clone()))
.and_then(hello_require_login);
let hello_with_state = warp::get()
.and(warp::path("hello_with_state"))
.and(with_state)
.and_then(hello_with_state);
let route = warp::any().and(
hello
.or(hello_error)
.or(hello_require_login)
.or(hello_with_state),
);
route.boxed()
}
#[route_wrapper]
async fn hello() -> Result<&'static str> {
Ok("hello world")
}
#[route_wrapper]
async fn hello_error() -> Result<&'static str> {
Err(AppError::MyError("my error".into()))
}
/// note: must use `_guard: LoginGuard` instead `_: LoginGuard`
#[route_wrapper]
async fn hello_require_login(_guard: LoginGuard) -> Result<&'static str> {
Ok("you are logged in")
}
#[route_wrapper]
async fn hello_with_state(state: AppState) -> Result<&'static str> {
let _ = state.db.query();
Ok("hello with state")
}
| 24.935484 | 74 | 0.642303 |
03f01e79a19e2e8228a44c230f5446e37d2a5126
| 7,998 |
use crate::Bss;
use crate::Interface;
use crate::Nl80211Attr;
use crate::Nl80211Cmd;
use crate::Socket;
use crate::Station;
use crate::NL_80211_GENL_VERSION;
use neli::consts::genl::{CtrlAttr, CtrlCmd};
use neli::consts::{nl::GenlId, nl::NlmF, nl::NlmFFlags, nl::Nlmsg};
use neli::err::NlError;
use neli::genl::{Genlmsghdr, Nlattr};
use neli::nl::{NlPayload, Nlmsghdr};
use neli::socket::tokio::NlSocket;
use neli::types::GenlBuffer;
/// A generic netlink socket to send commands and receive messages
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub struct AsyncSocket {
sock: NlSocket,
family_id: u16,
}
impl TryFrom<Socket> for AsyncSocket {
type Error = std::io::Error;
fn try_from(from: Socket) -> Result<Self, Self::Error> {
Ok(Self {
sock: NlSocket::new(from.sock)?,
family_id: from.family_id,
})
}
}
impl AsyncSocket {
/// Create a new nl80211 socket with netlink
pub fn connect() -> Result<Self, NlError<GenlId, Genlmsghdr<CtrlCmd, CtrlAttr>>> {
Ok(Socket::connect()?.try_into()?)
}
/// Get information for all your wifi interfaces
///
/// # Example
///
/// ```no_run
/// # use neli_wifi::AsyncSocket;
/// # use std::error::Error;
///
/// # async fn test() -> Result<(), Box<dyn Error>>{
/// let wifi_interfaces = AsyncSocket::connect()?.get_interfaces_info().await?;
/// for wifi_interface in wifi_interfaces {
/// println!("{:#?}", wifi_interface);
/// }
/// # Ok(())
/// # };
///```
pub async fn get_interfaces_info(&mut self) -> Result<Vec<Interface>, NlError> {
let msghdr = Genlmsghdr::<Nl80211Cmd, Nl80211Attr>::new(
Nl80211Cmd::CmdGetInterface,
NL_80211_GENL_VERSION,
GenlBuffer::new(),
);
let nlhdr = {
let len = None;
let nl_type = self.family_id;
let flags = NlmFFlags::new(&[NlmF::Request, NlmF::Dump]);
let seq = None;
let pid = None;
let payload = NlPayload::Payload(msghdr);
Nlmsghdr::new(len, nl_type, flags, seq, pid, payload)
};
self.sock.send(&nlhdr).await?;
let mut buf = Vec::new();
let mut interfaces = Vec::new();
loop {
let res = self
.sock
.recv::<Nlmsg, Genlmsghdr<Nl80211Cmd, Nl80211Attr>>(&mut buf)
.await?;
for response in res {
match response.nl_type {
Nlmsg::Noop => (),
Nlmsg::Error => panic!("Error"),
Nlmsg::Done => return Ok(interfaces),
_ => {
let handle = response.nl_payload.get_payload().unwrap().get_attr_handle();
interfaces.push(handle.try_into()?);
}
};
}
}
}
/// Get access point information for a specific interface
///
/// # Example
///
/// ```no_run
/// # use neli_wifi::AsyncSocket;
/// # use std::error::Error;
///
/// # async fn test() -> Result<(), Box<dyn Error>> {
/// let mut socket = AsyncSocket::connect()?;
/// // First of all we need to get wifi interface information to get more data
/// let wifi_interfaces = socket.get_interfaces_info().await?;
/// for wifi_interface in wifi_interfaces {
/// if let Some(netlink_index) = wifi_interface.index {
/// // Then for each wifi interface we can fetch station information
/// let station_info = socket.get_station_info(&netlink_index.clone()).await?;
/// println!("{:#?}", station_info);
/// }
/// }
/// # Ok(())
/// # }
///```
pub async fn get_station_info(
&mut self,
interface_attr_if_index: &[u8],
) -> Result<Station, NlError> {
let msghdr = Genlmsghdr::<Nl80211Cmd, Nl80211Attr>::new(
Nl80211Cmd::CmdGetStation,
NL_80211_GENL_VERSION,
{
let mut attrs = GenlBuffer::new();
attrs.push(
Nlattr::new(
false,
false,
Nl80211Attr::AttrIfindex,
NlPayload::<(), Vec<u8>>::Payload(interface_attr_if_index.to_owned()),
)
.unwrap(),
);
attrs
},
);
let nlhdr = {
let len = None;
let nl_type = self.family_id;
let flags = NlmFFlags::new(&[NlmF::Request, NlmF::Dump]);
let seq = None;
let pid = None;
let payload = NlPayload::Payload(msghdr);
Nlmsghdr::new(len, nl_type, flags, seq, pid, payload)
};
self.sock.send(&nlhdr).await?;
let mut buf = Vec::new();
let mut retval = None;
loop {
let res = self
.sock
.recv::<Nlmsg, Genlmsghdr<Nl80211Cmd, Nl80211Attr>>(&mut buf)
.await?;
for response in res {
match response.nl_type {
Nlmsg::Noop => (),
Nlmsg::Error => panic!("Error"),
Nlmsg::Done => return Ok(retval.unwrap_or_default()),
_ => {
retval = Some(
response
.nl_payload
.get_payload()
.unwrap()
.get_attr_handle()
.try_into()?,
);
}
};
}
}
}
pub async fn get_bss_info(&mut self, interface_attr_if_index: &[u8]) -> Result<Bss, NlError> {
let msghdr = Genlmsghdr::<Nl80211Cmd, Nl80211Attr>::new(
Nl80211Cmd::CmdGetScan,
NL_80211_GENL_VERSION,
{
let mut attrs = GenlBuffer::new();
attrs.push(
Nlattr::new(
false,
false,
Nl80211Attr::AttrIfindex,
NlPayload::<(), Vec<u8>>::Payload(interface_attr_if_index.to_owned()),
)
.unwrap(),
);
attrs
},
);
let nlhdr = {
let len = None;
let nl_type = self.family_id;
let flags = NlmFFlags::new(&[NlmF::Request, NlmF::Dump]);
let seq = None;
let pid = None;
let payload = NlPayload::Payload(msghdr);
Nlmsghdr::new(len, nl_type, flags, seq, pid, payload)
};
self.sock.send(&nlhdr).await?;
let mut buf = Vec::new();
let mut retval = None;
loop {
let res = self
.sock
.recv::<Nlmsg, Genlmsghdr<Nl80211Cmd, Nl80211Attr>>(&mut buf)
.await?;
for response in res {
match response.nl_type {
Nlmsg::Noop => (),
Nlmsg::Error => panic!("Error"),
Nlmsg::Done => return Ok(retval.unwrap_or_default()),
_ => {
retval = Some(
response
.nl_payload
.get_payload()
.unwrap()
.get_attr_handle()
.try_into()?,
);
}
}
}
}
}
}
impl From<AsyncSocket> for NlSocket {
/// Returns the underlying generic netlink socket
fn from(sock: AsyncSocket) -> Self {
sock.sock
}
}
| 32.25 | 98 | 0.462116 |
2fc3275bc6f5a38a471ad50910d99cc378762cc7
| 20,812 |
use crate::ast::CommandX;
use crate::context::ValidityResult;
#[allow(unused_imports)]
use crate::parser::nodes_to_commands;
#[allow(unused_imports)]
use crate::printer::macro_push_node;
use crate::smt_manager::SmtManager;
#[allow(unused_imports)]
use sise::Node;
#[allow(dead_code)]
fn run_nodes_as_test(should_typecheck: bool, should_be_valid: bool, nodes: &[Node]) {
let mut air_context = crate::context::Context::new(SmtManager::new());
air_context.set_z3_param("air_recommended_options", "true");
match nodes_to_commands(&nodes) {
Ok(commands) => {
for command in commands.iter() {
let result = air_context.command(&command);
match (&**command, should_typecheck, should_be_valid, result) {
(_, false, _, ValidityResult::TypeError(_)) => {}
(_, true, _, ValidityResult::TypeError(s)) => {
panic!("type error: {}", s);
}
(_, _, true, ValidityResult::Valid) => {}
(_, _, false, ValidityResult::Invalid(_, _, _)) => {}
(CommandX::CheckValid(_), _, _, _) => {
panic!("unexpected result");
}
_ => {}
}
}
}
Err(s) => {
println!("{}", s);
panic!();
}
}
}
#[allow(unused_macros)]
macro_rules! yes {
( $( $x:tt )* ) => {
{
let mut v = Vec::new();
$(macro_push_node(&mut v, node!($x));)*
run_nodes_as_test(true, true, &v)
}
};
}
#[allow(unused_macros)]
macro_rules! no {
( $( $x:tt )* ) => {
{
let mut v = Vec::new();
$(macro_push_node(&mut v, node!($x));)*
run_nodes_as_test(true, false, &v)
}
};
}
#[allow(unused_macros)]
macro_rules! untyped {
( $( $x:tt )* ) => {
{
let mut v = Vec::new();
$(macro_push_node(&mut v, node!($x));)*
run_nodes_as_test(false, false, &v)
}
};
}
#[test]
fn yes_true() {
yes!(
(check-valid
(assert true)
)
);
}
#[test]
fn no_false() {
no!(
(check-valid
(assert false)
)
);
}
#[test]
fn yes_int_const() {
yes!(
(check-valid
(assert
(= (+ 2 2) 4)
)
)
);
}
#[test]
fn no_int_const() {
no!(
(check-valid
(assert
(= (+ 2 2) 5)
)
)
);
}
#[test]
fn yes_int_vars() {
yes!(
(check-valid
(declare-const x Int)
(declare-const y Int)
(declare-const z Int)
(assert
(= (+ x y z) (+ z y x))
)
)
);
}
#[test]
fn no_int_vars() {
no!(
(check-valid
(declare-const x Int)
(declare-const y Int)
(assert
(= (+ x y) (+ y y))
)
)
);
}
#[test]
fn yes_int_neg() {
yes!(
(check-valid
(declare-const x Int)
(assert
(= (+ x (- 2)) (- x 2))
)
)
);
}
#[test]
fn yes_int_axiom() {
yes!(
(check-valid
(declare-const x Int)
(axiom (> x 3))
(assert
(>= x 3)
)
)
);
}
#[test]
fn no_int_axiom() {
no!(
(check-valid
(declare-const x Int)
(axiom (>= x 3))
(assert
(> x 3)
)
)
);
}
#[test]
fn yes_test_block() {
yes!(
(check-valid
(declare-const x Int)
(block
(assume (> x 3))
(assert (>= x 3))
(assume (> x 5))
(assert (>= x 5))
)
)
);
}
#[test]
fn no_test_block() {
no!(
(check-valid
(declare-const x Int)
(block
(assume (> x 3))
(assert (>= x 3))
(assert (>= x 5))
(assume (> x 5))
)
)
);
}
#[test]
fn yes_test_block_nest() {
yes!(
(check-valid
(declare-const x Int)
(block
(assume (> x 3))
(block
(assert (>= x 3))
(assume (> x 5))
)
(assert (>= x 5))
)
)
);
}
#[test]
fn yes_global() {
yes!(
(push)
(axiom false)
(check-valid
(assert false)
)
(pop)
);
}
#[test]
fn no_global() {
no!(
(push)
(axiom false)
(pop)
(check-valid
(assert false)
)
);
}
#[test]
fn yes_type() {
yes!(
(check-valid
(declare-sort T)
(declare-const x T)
(assert
(= x x)
)
)
);
}
#[test]
fn no_type() {
no!(
(check-valid
(declare-sort T)
(declare-const x T)
(declare-const y T)
(assert
(= x y)
)
)
);
}
#[test]
fn yes_assign() {
yes!(
(check-valid
(declare-var x Int)
(declare-var y Int)
(block
(assume (= x 100))
(assume (= y 200))
(assign x (+ x 1))
(assign x (+ x 1))
(assert (= x 102))
(assert (= y 200))
)
)
);
}
#[test]
fn no_assign() {
no!(
(check-valid
(declare-var x Int)
(declare-var y Int)
(block
(assume (= x 100))
(assume (= y 200))
(assign x (+ x 1))
(assign x (+ x 1))
(assert (not (= x 102)))
)
)
);
}
#[test]
fn yes_havoc() {
yes!(
(check-valid
(declare-var x Int)
(declare-var y Int)
(block
(assume (= x 100))
(assume (= y 200))
(havoc x)
(assert (= y 200))
)
)
);
}
#[test]
fn no_havoc() {
no!(
(check-valid
(declare-var x Int)
(declare-var y Int)
(block
(assume (= x 100))
(assume (= y 200))
(havoc y)
(assert (= y 200))
)
)
);
}
#[test]
fn yes_snapshot() {
yes!(
(check-valid
(declare-var x Int)
(declare-var y Int)
(block
(assume (= x 100))
(assume (= y 200))
(assign x (+ x 1))
(snapshot A)
(snapshot B)
(assign x (+ x 1))
(assert (= (old A x) 101))
(assert (= (old B x) 101))
(assert (= x 102))
(assert (= y 200))
(snapshot A)
(assert (= (old A x) 102))
(assert (= (old B x) 101))
)
)
)
}
#[test]
fn yes_test_switch1() {
yes!(
(check-valid
(declare-const x Int)
(block
(switch
(assume (> x 20))
(assume (< x 10))
)
(assert (or (> x 20) (< x 10)))
)
)
);
}
#[test]
fn no_test_switch1() {
no!(
(check-valid
(declare-const x Int)
(block
(switch
(assume (> x 20))
(assume (< x 10))
)
(assert (> x 20))
)
)
);
}
#[test]
fn yes_test_switch2() {
yes!(
(check-valid
(declare-var x Int)
(block
(assign x 10)
(switch
(block
)
(assign x 15)
(block
(assign x 20)
(assign x (+ x 30))
(assign x (- x 40))
)
(assign x (+ x 7))
)
(assert (>= x 10))
(assert (<= x 20))
)
)
);
}
#[test]
fn no_test_switch2() {
no!(
(check-valid
(declare-var x Int)
(block
(assign x 10)
(switch
(block
)
(assign x 15)
(block
(assign x 20)
(assign x (+ x 30))
(assign x (- x 40))
)
(assign x (+ x 7))
)
(assert (> x 10))
(assert (<= x 20))
)
)
);
}
#[test]
fn no_test_switch3() {
no!(
(check-valid
(declare-var x Int)
(block
(assign x 10)
(switch
(block
)
(assign x 15)
(block
(assign x 20)
(assign x (+ x 30))
(assign x (- x 40))
)
(assign x (+ x 7))
)
(assert (>= x 10))
(assert (< x 17))
)
)
);
}
#[test]
fn untyped_scope1() {
untyped!(
(declare-const x Int)
(declare-const x Int) // error: x already in scope
);
}
#[test]
fn untyped_scope2() {
untyped!(
(declare-const x Int)
(push)
(declare-const x Int) // error: x already in scope
(pop)
);
}
#[test]
fn untyped_scope3() {
untyped!(
(declare-const x Int)
(check-valid
(declare-const x Int) // error: x already in scope
(assert true)
)
);
}
#[test]
fn untyped_scope4() {
untyped!(
(declare-const x Int)
(check-valid
(declare-var x Int) // error: x already in scope
(assert true)
)
);
}
#[test]
fn untyped_scope5() {
untyped!(
(declare-const "x@0" Int)
(check-valid
(declare-var x Int) // error: x@0 already in scope
(assert true)
)
);
}
#[test]
fn untyped_scope6() {
untyped!(
(declare-var x Int) // error: declare-var not allowed in global scope
);
}
#[test]
fn untyped_scope7() {
untyped!(
(declare-const x Int)
(declare-fun x (Int Int) Int) // error: x already in scope
);
}
#[test]
fn yes_scope1() {
yes!(
(push)
(declare-const x Int)
(pop)
(push)
(declare-const x Int)
(pop)
);
}
#[test]
fn yes_scope2() {
yes!(
(push)
(declare-const x Int)
(pop)
(declare-const x Int)
);
}
#[test]
fn yes_scope3() {
yes!(
(push)
(declare-const x Int)
(pop)
(check-valid
(declare-var x Int)
(assert true)
)
);
}
#[test]
fn yes_fun1() {
yes!(
(check-valid
(declare-fun f (Int Bool) Bool)
(block
(assume (f 10 true))
(assert (f 10 true))
)
)
)
}
#[test]
fn no_fun1() {
no!(
(check-valid
(declare-fun f (Int Bool) Bool)
(block
(assume (f 10 true))
(assert (f 11 true))
)
)
)
}
#[test]
fn no_typing1() {
untyped!(
(axiom 10)
)
}
#[test]
fn no_typing2() {
untyped!(
(axiom b)
)
}
#[test]
fn no_typing3() {
untyped!(
(declare-fun f (Int Bool) Bool)
(axiom (f 10))
)
}
#[test]
fn no_typing4() {
untyped!(
(declare-fun f (Int Bool) Bool)
(axiom (f 10 20))
)
}
#[test]
fn no_typing5() {
untyped!(
(check-valid
(declare-var x Int)
(assign x true)
)
)
}
#[test]
fn yes_let1() {
yes!(
(check-valid
(assert (let ((x 10) (y 20)) (< x y)))
)
)
}
#[test]
fn yes_let2() {
yes!(
(check-valid
(assert
(let ((x 10) (y 20))
(=
40
(let ((x (+ x 10))) (+ x y)) // can shadow other let/forall bindings
)
)
)
)
)
}
#[test]
fn yes_let3() {
yes!(
(check-valid
(assert
(let ((x 10) (y 20))
(=
(let ((x (+ x 10))) (+ x y)) // can shadow other let/forall bindings
(+ x x y) // make sure old values are restored here
)
)
)
)
)
}
#[test]
fn yes_let4() {
yes!(
(check-valid
(assert
(let ((x true) (y 20))
(and
(=
(let ((x (+ y 10))) (+ x y))
50
)
x // make sure old type is restored here
)
)
)
)
)
}
#[test]
fn untyped_let1() {
untyped!(
(check-valid
(assert (let ((x 10) (x 20)) true)) // no duplicates allowed in single let
)
)
}
#[test]
fn untyped_let2() {
untyped!(
(declare-const y Int)
(check-valid
(assert (let ((x 10) (y 20)) true)) // cannot shadow global name
)
)
}
#[test]
fn untyped_let3() {
untyped!(
(declare-fun y (Int) Int)
(check-valid
(assert (let ((x 10) (y 20)) true)) // cannot shadow global name
)
)
}
#[test]
fn untyped_let4() {
untyped!(
(declare-sort y)
(check-valid
(assert (let ((x 10) (y 20)) true)) // cannot shadow global name
)
)
}
#[test]
fn no_let1() {
no!(
(check-valid
(assert
(let ((x 10) (y 20))
(=
(let ((x (+ x 10))) (+ x y))
(+ x y) // make sure old values are restored here
)
)
)
)
)
}
#[test]
fn yes_forall1() {
yes!(
(check-valid
(assert
(forall ((i Int)) true)
)
)
)
}
#[test]
fn yes_forall2() {
yes!(
(declare-fun f (Int Int) Bool)
(check-valid
(assert
(=>
(forall ((i Int) (j Int)) (f i j))
(f 10 20)
)
)
)
)
}
#[test]
fn yes_forall3() {
yes!(
(declare-fun f (Int Int) Bool)
(check-valid
(assert
(=>
(forall ((i Int) (j Int)) (!
(f i j)
:pattern ((f i j))
))
(f 10 20)
)
)
)
)
}
#[test]
fn yes_forall4() {
yes!(
(declare-fun f (Int Int) Bool)
(declare-fun g (Int Int) Bool)
(check-valid
(assert
(=>
(forall ((i Int) (j Int)) (!
(f i j)
:pattern ((g i j))
:pattern ((f i j))
))
(f 10 20)
)
)
)
)
}
#[test]
fn yes_forall5() {
yes!(
(declare-fun f (Int) Bool)
(declare-fun g (Int) Bool)
(axiom
(forall ((i Int) (j Int)) (!
(=> (f i) (g j))
:pattern ((f i) (g j))
))
)
(check-valid
(assert
(=> (f 10) (g 10))
)
)
)
}
#[test]
fn no_forall1() {
no!(
(check-valid
(assert
(forall ((i Int)) false)
)
)
)
}
#[test]
fn no_forall2() {
no!(
(declare-fun f (Int Int) Bool)
(declare-fun g (Int Int) Bool)
(check-valid
(assert
(=>
(forall ((i Int) (j Int)) (!
(f i j)
:pattern ((g i j))
))
(f 10 20) // doesn't match (g i j)
)
)
)
)
}
#[test]
fn untyped_forall1() {
untyped!(
(check-valid
(assert
(let
((
x
(forall ((i Int)) i)
))
true
)
)
)
)
}
#[test]
fn yes_exists1() {
yes!(
(declare-fun f (Int Int) Bool)
(check-valid
(assert
(=>
(f 10 20)
(exists ((i Int) (j Int)) (!
(f i j)
:pattern ((f i j))
))
)
)
)
)
}
#[test]
fn no_exists1() {
no!(
(declare-fun f (Int Int) Bool)
(check-valid
(assert
(=>
(exists ((i Int) (j Int)) (!
(f i j)
:pattern ((f i j))
))
(f 10 20)
)
)
)
)
}
#[test]
fn yes_ite1() {
yes!(
(check-valid
(block
(assert (= (ite true 10 20) 10))
(assert (= (ite false 10 20) 20))
)
)
)
}
#[test]
fn no_ite1() {
no!(
(check-valid
(assert (= (ite true 10 20) 20))
)
)
}
#[test]
fn untyped_ite1() {
untyped!(
(check-valid
(assert (= (ite 0 10 20) 20))
)
)
}
#[test]
fn untyped_ite2() {
untyped!(
(check-valid
(assert (= (ite true 10 true) 20))
)
)
}
#[test]
fn yes_distinct() {
yes!(
(check-valid
(assert (distinct 10 20 30))
)
)
}
#[test]
fn no_distinct() {
no!(
(check-valid
(assert (distinct 10 20 10))
)
)
}
#[test]
fn untyped_distinct() {
untyped!(
(check-valid
(assert (distinct 10 20 true))
)
)
}
#[test]
fn yes_datatype1() {
yes!(
(declare-datatypes () (
(IntPair
(int_pair
(ip1 Int)
(ip2 Int)
)
)
))
(check-valid
(declare-const x IntPair)
(block
(assume (= x (int_pair 10 20)))
(assert (= 10 (ip1 x)))
)
)
)
}
#[test]
fn yes_datatype2() {
yes!(
(declare-datatypes () (
(Tree
(empty)
(full
(children Pair)
)
)
(Pair
(pair
(fst Tree)
(snd Tree)
)
)
))
(check-valid
(declare-const x Tree)
(block
(assume (= x (full (pair (empty) (empty)))))
(assert (= (empty) (fst (children x))))
(assert (is-empty (snd (children x))))
)
)
)
}
#[test]
fn yes_deadend() {
yes!(
(declare-const b Bool)
(check-valid
(block
(assume b)
(deadend
(block
(assert b)
)
)
(assert b)
)
)
)
}
#[test]
fn no_deadend1() {
no!(
(declare-const b Bool)
(check-valid
(block
(deadend
(block
(assume b)
(assert b)
)
)
(assert b)
)
)
)
}
#[test]
fn no_deadend2() {
no!(
(declare-const b Bool)
(check-valid
(block
(deadend
(block
(assume b)
(assert false)
)
)
(assert b)
)
)
)
}
| 19.076077 | 92 | 0.33966 |
4b6c631b294b20677594c3fba2b34e7bf8daf92d
| 107,272 |
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
extern crate yup_hyper_mock as mock;
extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate mime;
extern crate strsim;
extern crate google_accesscontextmanager1 as api;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
mod cmn;
use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg,
input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol,
calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo};
use std::default::Default;
use std::str::FromStr;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, FlowType};
use serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(api::Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::AccessContextManager<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
fn _access_policies_access_levels_create(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"update-time" => Some(("updateTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"basic.combining-function" => Some(("basic.combiningFunction", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"create-time" => Some(("createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["basic", "combining-function", "create-time", "description", "name", "title", "update-time"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::AccessLevel = json::value::from_value(object).unwrap();
let mut call = self.hub.access_policies().access_levels_create(request, opt.value_of("parent").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_access_levels_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.access_policies().access_levels_delete(opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_access_levels_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.access_policies().access_levels_get(opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"access-level-format" => {
call = call.access_level_format(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["access-level-format"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_access_levels_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.access_policies().access_levels_list(opt.value_of("parent").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"page-size" => {
call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer"));
},
"access-level-format" => {
call = call.access_level_format(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["access-level-format", "page-token", "page-size"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_access_levels_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"update-time" => Some(("updateTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"basic.combining-function" => Some(("basic.combiningFunction", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"create-time" => Some(("createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["basic", "combining-function", "create-time", "description", "name", "title", "update-time"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::AccessLevel = json::value::from_value(object).unwrap();
let mut call = self.hub.access_policies().access_levels_patch(request, opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"update-mask" => {
call = call.update_mask(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["update-mask"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_create(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"update-time" => Some(("updateTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"create-time" => Some(("createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"parent" => Some(("parent", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["create-time", "name", "parent", "title", "update-time"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::AccessPolicy = json::value::from_value(object).unwrap();
let mut call = self.hub.access_policies().create(request);
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.access_policies().delete(opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.access_policies().get(opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.access_policies().list();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"parent" => {
call = call.parent(value.unwrap_or(""));
},
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"page-size" => {
call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["page-token", "page-size", "parent"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"update-time" => Some(("updateTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"create-time" => Some(("createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"parent" => Some(("parent", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["create-time", "name", "parent", "title", "update-time"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::AccessPolicy = json::value::from_value(object).unwrap();
let mut call = self.hub.access_policies().patch(request, opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"update-mask" => {
call = call.update_mask(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["update-mask"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_service_perimeters_create(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"status.restricted-services" => Some(("status.restrictedServices", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
"status.resources" => Some(("status.resources", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
"status.access-levels" => Some(("status.accessLevels", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
"update-time" => Some(("updateTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"perimeter-type" => Some(("perimeterType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"create-time" => Some(("createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["access-levels", "create-time", "description", "name", "perimeter-type", "resources", "restricted-services", "status", "title", "update-time"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ServicePerimeter = json::value::from_value(object).unwrap();
let mut call = self.hub.access_policies().service_perimeters_create(request, opt.value_of("parent").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_service_perimeters_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.access_policies().service_perimeters_delete(opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_service_perimeters_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.access_policies().service_perimeters_get(opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_service_perimeters_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.access_policies().service_perimeters_list(opt.value_of("parent").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"page-size" => {
call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["page-token", "page-size"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _access_policies_service_perimeters_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"status.restricted-services" => Some(("status.restrictedServices", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
"status.resources" => Some(("status.resources", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
"status.access-levels" => Some(("status.accessLevels", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
"update-time" => Some(("updateTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"perimeter-type" => Some(("perimeterType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"create-time" => Some(("createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["access-levels", "create-time", "description", "name", "perimeter-type", "resources", "restricted-services", "status", "title", "update-time"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ServicePerimeter = json::value::from_value(object).unwrap();
let mut call = self.hub.access_policies().service_perimeters_patch(request, opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"update-mask" => {
call = call.update_mask(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["update-mask"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _operations_cancel(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec![]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::CancelOperationRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.operations().cancel(request, opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _operations_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.operations().delete(opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _operations_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.operations().get(opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _operations_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.operations().list(opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"page-size" => {
call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer"));
},
"filter" => {
call = call.filter(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["filter", "page-token", "page-size"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
let mut err = InvalidOptionsError::new();
let mut call_result: Result<(), DoitError> = Ok(());
let mut err_opt: Option<InvalidOptionsError> = None;
match self.opt.subcommand() {
("access-policies", Some(opt)) => {
match opt.subcommand() {
("access-levels-create", Some(opt)) => {
call_result = self._access_policies_access_levels_create(opt, dry_run, &mut err);
},
("access-levels-delete", Some(opt)) => {
call_result = self._access_policies_access_levels_delete(opt, dry_run, &mut err);
},
("access-levels-get", Some(opt)) => {
call_result = self._access_policies_access_levels_get(opt, dry_run, &mut err);
},
("access-levels-list", Some(opt)) => {
call_result = self._access_policies_access_levels_list(opt, dry_run, &mut err);
},
("access-levels-patch", Some(opt)) => {
call_result = self._access_policies_access_levels_patch(opt, dry_run, &mut err);
},
("create", Some(opt)) => {
call_result = self._access_policies_create(opt, dry_run, &mut err);
},
("delete", Some(opt)) => {
call_result = self._access_policies_delete(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._access_policies_get(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._access_policies_list(opt, dry_run, &mut err);
},
("patch", Some(opt)) => {
call_result = self._access_policies_patch(opt, dry_run, &mut err);
},
("service-perimeters-create", Some(opt)) => {
call_result = self._access_policies_service_perimeters_create(opt, dry_run, &mut err);
},
("service-perimeters-delete", Some(opt)) => {
call_result = self._access_policies_service_perimeters_delete(opt, dry_run, &mut err);
},
("service-perimeters-get", Some(opt)) => {
call_result = self._access_policies_service_perimeters_get(opt, dry_run, &mut err);
},
("service-perimeters-list", Some(opt)) => {
call_result = self._access_policies_service_perimeters_list(opt, dry_run, &mut err);
},
("service-perimeters-patch", Some(opt)) => {
call_result = self._access_policies_service_perimeters_patch(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("access-policies".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("operations", Some(opt)) => {
match opt.subcommand() {
("cancel", Some(opt)) => {
call_result = self._operations_cancel(opt, dry_run, &mut err);
},
("delete", Some(opt)) => {
call_result = self._operations_delete(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._operations_get(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._operations_list(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("operations".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
_ => {
err.issues.push(CLIError::MissingCommandError);
writeln!(io::stderr(), "{}\n", self.opt.usage()).ok();
}
}
if dry_run {
if err.issues.len() > 0 {
err_opt = Some(err);
}
Err(err_opt)
} else {
Ok(call_result)
}
}
// Please note that this call will fail if any part of the opt can't be handled
fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) {
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
Ok(p) => p,
};
match cmn::application_secret_from_directory(&config_dir, "accesscontextmanager1-secret.json",
"{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") {
Ok(secret) => (config_dir, secret),
Err(e) => return Err(InvalidOptionsError::single(e, 4))
}
};
let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate,
if opt.is_present("debug-auth") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
},
JsonTokenStorage {
program_name: "accesscontextmanager1",
db_dir: config_dir.clone(),
}, Some(FlowType::InstalledRedirect(54324)));
let client =
if opt.is_present("debug") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
};
let engine = Engine {
opt: opt,
hub: api::AccessContextManager::new(client, auth),
gp: vec!["$-xgafv", "access-token", "alt", "callback", "fields", "key", "oauth-token", "pretty-print", "quota-user", "upload-type", "upload-protocol"],
gpm: vec![
("$-xgafv", "$.xgafv"),
("access-token", "access_token"),
("oauth-token", "oauth_token"),
("pretty-print", "prettyPrint"),
("quota-user", "quotaUser"),
("upload-type", "uploadType"),
("upload-protocol", "upload_protocol"),
]
};
match engine._doit(true) {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
fn doit(&self) -> Result<(), DoitError> {
match self._doit(false) {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
fn main() {
let mut exit_status = 0i32;
let arg_data = [
("access-policies", "methods: 'access-levels-create', 'access-levels-delete', 'access-levels-get', 'access-levels-list', 'access-levels-patch', 'create', 'delete', 'get', 'list', 'patch', 'service-perimeters-create', 'service-perimeters-delete', 'service-perimeters-get', 'service-perimeters-list' and 'service-perimeters-patch'", vec![
("access-levels-create",
Some(r##"Create an Access Level. The longrunning
operation from this RPC will have a successful status once the Access
Level has
propagated to long-lasting storage. Access Levels containing
errors will result in an error response for the first error encountered."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_access-levels-create",
vec![
(Some(r##"parent"##),
None,
Some(r##"Required. Resource name for the access policy which owns this Access
Level.
Format: `accessPolicies/{policy_id}`"##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("access-levels-delete",
Some(r##"Delete an Access Level by resource
name. The longrunning operation from this RPC will have a successful status
once the Access Level has been removed
from long-lasting storage."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_access-levels-delete",
vec![
(Some(r##"name"##),
None,
Some(r##"Required. Resource name for the Access Level.
Format:
`accessPolicies/{policy_id}/accessLevels/{access_level_id}`"##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("access-levels-get",
Some(r##"Get an Access Level by resource
name."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_access-levels-get",
vec![
(Some(r##"name"##),
None,
Some(r##"Required. Resource name for the Access Level.
Format:
`accessPolicies/{policy_id}/accessLevels/{access_level_id}`"##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("access-levels-list",
Some(r##"List all Access Levels for an access
policy."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_access-levels-list",
vec![
(Some(r##"parent"##),
None,
Some(r##"Required. Resource name for the access policy to list Access Levels from.
Format:
`accessPolicies/{policy_id}`"##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("access-levels-patch",
Some(r##"Update an Access Level. The longrunning
operation from this RPC will have a successful status once the changes to
the Access Level have propagated
to long-lasting storage. Access Levels containing
errors will result in an error response for the first error encountered."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_access-levels-patch",
vec![
(Some(r##"name"##),
None,
Some(r##"Required. Resource name for the Access Level. The `short_name` component
must begin with a letter and only include alphanumeric and '_'. Format:
`accessPolicies/{policy_id}/accessLevels/{short_name}`"##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("create",
Some(r##"Create an `AccessPolicy`. Fails if this organization already has a
`AccessPolicy`. The longrunning Operation will have a successful status
once the `AccessPolicy` has propagated to long-lasting storage.
Syntactic and basic semantic errors will be returned in `metadata` as a
BadRequest proto."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_create",
vec![
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("delete",
Some(r##"Delete an AccessPolicy by resource
name. The longrunning Operation will have a successful status once the
AccessPolicy
has been removed from long-lasting storage."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_delete",
vec![
(Some(r##"name"##),
None,
Some(r##"Required. Resource name for the access policy to delete.
Format `accessPolicies/{policy_id}`"##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get",
Some(r##"Get an AccessPolicy by name."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_get",
vec![
(Some(r##"name"##),
None,
Some(r##"Required. Resource name for the access policy to get.
Format `accessPolicies/{policy_id}`"##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"List all AccessPolicies under a
container."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_list",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("patch",
Some(r##"Update an AccessPolicy. The
longrunning Operation from this RPC will have a successful status once the
changes to the AccessPolicy have propagated
to long-lasting storage. Syntactic and basic semantic errors will be
returned in `metadata` as a BadRequest proto."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_patch",
vec![
(Some(r##"name"##),
None,
Some(r##"Output only. Resource name of the `AccessPolicy`. Format:
`accessPolicies/{policy_id}`"##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("service-perimeters-create",
Some(r##"Create an Service Perimeter. The
longrunning operation from this RPC will have a successful status once the
Service Perimeter has
propagated to long-lasting storage. Service Perimeters containing
errors will result in an error response for the first error encountered."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_service-perimeters-create",
vec![
(Some(r##"parent"##),
None,
Some(r##"Required. Resource name for the access policy which owns this Service
Perimeter.
Format: `accessPolicies/{policy_id}`"##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("service-perimeters-delete",
Some(r##"Delete an Service Perimeter by resource
name. The longrunning operation from this RPC will have a successful status
once the Service Perimeter has been
removed from long-lasting storage."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_service-perimeters-delete",
vec![
(Some(r##"name"##),
None,
Some(r##"Required. Resource name for the Service Perimeter.
Format:
`accessPolicies/{policy_id}/servicePerimeters/{service_perimeter_id}`"##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("service-perimeters-get",
Some(r##"Get an Service Perimeter by resource
name."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_service-perimeters-get",
vec![
(Some(r##"name"##),
None,
Some(r##"Required. Resource name for the Service Perimeter.
Format:
`accessPolicies/{policy_id}/servicePerimeters/{service_perimeters_id}`"##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("service-perimeters-list",
Some(r##"List all Service Perimeters for an
access policy."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_service-perimeters-list",
vec![
(Some(r##"parent"##),
None,
Some(r##"Required. Resource name for the access policy to list Service Perimeters from.
Format:
`accessPolicies/{policy_id}`"##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("service-perimeters-patch",
Some(r##"Update an Service Perimeter. The
longrunning operation from this RPC will have a successful status once the
changes to the Service Perimeter have
propagated to long-lasting storage. Service Perimeter containing
errors will result in an error response for the first error encountered."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/access-policies_service-perimeters-patch",
vec![
(Some(r##"name"##),
None,
Some(r##"Required. Resource name for the ServicePerimeter. The `short_name`
component must begin with a letter and only include alphanumeric and '_'.
Format: `accessPolicies/{policy_id}/servicePerimeters/{short_name}`"##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("operations", "methods: 'cancel', 'delete', 'get' and 'list'", vec![
("cancel",
Some(r##"Starts asynchronous cancellation on a long-running operation. The server
makes a best effort to cancel the operation, but success is not
guaranteed. If the server doesn't support this method, it returns
`google.rpc.Code.UNIMPLEMENTED`. Clients can use
Operations.GetOperation or
other methods to check whether the cancellation succeeded or whether the
operation completed despite cancellation. On successful cancellation,
the operation is not deleted; instead, it becomes an operation with
an Operation.error value with a google.rpc.Status.code of 1,
corresponding to `Code.CANCELLED`."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/operations_cancel",
vec![
(Some(r##"name"##),
None,
Some(r##"The name of the operation resource to be cancelled."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("delete",
Some(r##"Deletes a long-running operation. This method indicates that the client is
no longer interested in the operation result. It does not cancel the
operation. If the server doesn't support this method, it returns
`google.rpc.Code.UNIMPLEMENTED`."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/operations_delete",
vec![
(Some(r##"name"##),
None,
Some(r##"The name of the operation resource to be deleted."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get",
Some(r##"Gets the latest state of a long-running operation. Clients can use this
method to poll the operation result at intervals as recommended by the API
service."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/operations_get",
vec![
(Some(r##"name"##),
None,
Some(r##"The name of the operation resource."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Lists operations that match the specified filter in the request. If the
server doesn't support this method, it returns `UNIMPLEMENTED`.
NOTE: the `name` binding allows API services to override the binding
to use different resource name schemes, such as `users/*/operations`. To
override the binding, API services can add a binding such as
`"/v1/{name=users/*}/operations"` to their service configuration.
For backwards compatibility, the default name includes the operations
collection id, however overriding users must ensure the name binding
is the parent resource, without the operations collection id."##),
"Details at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli/operations_list",
vec![
(Some(r##"name"##),
None,
Some(r##"The name of the operation's parent resource."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
];
let mut app = App::new("accesscontextmanager1")
.author("Sebastian Thiel <[email protected]>")
.version("1.0.10+20190626")
.about("An API for setting attribute based access control to requests to GCP services.")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_accesscontextmanager1_cli")
.arg(Arg::with_name("url")
.long("scope")
.help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.")
.multiple(true)
.takes_value(true))
.arg(Arg::with_name("folder")
.long("config-dir")
.help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli")
.multiple(false)
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false))
.arg(Arg::with_name("debug-auth")
.long("debug-auth")
.help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false));
for &(main_command_name, about, ref subcommands) in arg_data.iter() {
let mut mcmd = SubCommand::with_name(main_command_name).about(about);
for &(sub_command_name, ref desc, url_info, ref args) in subcommands {
let mut scmd = SubCommand::with_name(sub_command_name);
if let &Some(desc) = desc {
scmd = scmd.about(desc);
}
scmd = scmd.after_help(url_info);
for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args {
let arg_name_str =
match (arg_name, flag) {
(&Some(an), _ ) => an,
(_ , &Some(f)) => f,
_ => unreachable!(),
};
let mut arg = Arg::with_name(arg_name_str)
.empty_values(false);
if let &Some(short_flag) = flag {
arg = arg.short(short_flag);
}
if let &Some(desc) = desc {
arg = arg.help(desc);
}
if arg_name.is_some() && flag.is_some() {
arg = arg.takes_value(true);
}
if let &Some(required) = required {
arg = arg.required(required);
}
if let &Some(multi) = multi {
arg = arg.multiple(multi);
}
scmd = scmd.arg(arg);
}
mcmd = mcmd.subcommand(scmd);
}
app = app.subcommand(mcmd);
}
let matches = app.get_matches();
let debug = matches.is_present("debug");
match Engine::new(matches) {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit() {
exit_status = 1;
match doit_err {
DoitError::IoError(path, err) => {
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
},
DoitError::ApiError(err) => {
if debug {
writeln!(io::stderr(), "{:#?}", err).ok();
} else {
writeln!(io::stderr(), "{}", err).ok();
}
}
}
}
}
}
std::process::exit(exit_status);
}
| 49.617021 | 526 | 0.446333 |
08b14e92292494a18dbb6124b66d12709b7f5fb7
| 16,685 |
// Copyright 2018 The xi-editor 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.
//! Manages recording and enables playback for client sent events.
//!
//! Clients can store multiple, named recordings.
use xi_trace::trace_block;
use std::collections::HashMap;
use std::mem;
use crate::edit_types::{BufferEvent, EventDomain};
/// A container that manages and holds all recordings for the current editing session
pub(crate) struct Recorder {
active_recording: Option<String>,
recording_buffer: Vec<EventDomain>,
recordings: HashMap<String, Recording>,
}
impl Recorder {
pub(crate) fn new() -> Recorder {
Recorder {
active_recording: None,
recording_buffer: Vec::new(),
recordings: HashMap::new(),
}
}
pub(crate) fn is_recording(&self) -> bool {
self.active_recording.is_some()
}
/// Starts or stops the specified recording.
///
///
/// There are three outcome behaviors:
/// - If the current recording name is specified, the active recording is saved
/// - If no recording name is specified, the currently active recording is saved
/// - If a recording name other than the active recording is specified,
/// the current recording will be thrown out and will be switched to the new name
///
/// In addition to the above:
/// - If the recording was saved, there is no active recording
/// - If the recording was switched, there will be a new active recording
pub(crate) fn toggle_recording(&mut self, recording_name: Option<String>) {
let is_recording = self.is_recording();
let last_recording = self.active_recording.take();
match (is_recording, &last_recording, &recording_name) {
(true, Some(last_recording), None) => {
self.save_recording_buffer(last_recording.clone())
}
(true, Some(last_recording), Some(recording_name)) => {
if last_recording != recording_name {
self.recording_buffer.clear();
} else {
self.save_recording_buffer(last_recording.clone());
return;
}
}
_ => {}
}
mem::replace(&mut self.active_recording, recording_name);
}
/// Saves an event into the currently active recording.
///
/// Every sequential `BufferEvent::Insert` event will be merged together to cut down the number of
/// `Editor::commit_delta` calls we need to make when playing back.
pub(crate) fn record(&mut self, current_event: EventDomain) {
assert!(self.is_recording());
let recording_buffer = &mut self.recording_buffer;
if recording_buffer.last().is_none() {
recording_buffer.push(current_event);
return;
}
{
let last_event = recording_buffer.last_mut().unwrap();
if let (
EventDomain::Buffer(BufferEvent::Insert(old_characters)),
EventDomain::Buffer(BufferEvent::Insert(new_characters)),
) = (last_event, ¤t_event)
{
old_characters.push_str(new_characters);
return;
}
}
recording_buffer.push(current_event);
}
/// Iterates over a specified recording's buffer and runs the specified action
/// on each event.
pub(crate) fn play<F>(&self, recording_name: &str, action: F)
where
F: FnMut(&EventDomain) -> (),
{
let is_current_recording: bool = self
.active_recording
.as_ref()
.map_or(false, |current_recording| current_recording == recording_name);
if is_current_recording {
warn!("Cannot play recording while it's currently active!");
return;
}
self.recordings.get(recording_name).and_then(|recording| {
recording.play(action);
Some(())
});
}
/// Completely removes the specified recording from the Recorder
pub(crate) fn clear(&mut self, recording_name: &str) {
self.recordings.remove(recording_name);
}
/// Cleans the recording buffer by filtering out any undo or redo events and then saving it
/// with the specified name.
///
/// A recording should not store any undos or redos--
/// call this once a recording is 'finalized.'
fn save_recording_buffer(&mut self, recording_name: String) {
let mut saw_undo = false;
let mut saw_redo = false;
// Walk the recording backwards and remove any undo / redo events
let filtered: Vec<EventDomain> = self
.recording_buffer
.clone()
.into_iter()
.rev()
.filter(|event| {
if let EventDomain::Buffer(event) = event {
return match event {
BufferEvent::Undo => {
saw_undo = !saw_redo;
saw_redo = false;
false
}
BufferEvent::Redo => {
saw_redo = !saw_undo;
saw_undo = false;
false
}
_ => {
let ret = !saw_undo;
saw_undo = false;
saw_redo = false;
ret
}
};
}
true
})
.collect::<Vec<EventDomain>>()
.into_iter()
.rev()
.collect();
let current_recording = Recording::new(filtered);
self.recordings.insert(recording_name, current_recording);
self.recording_buffer.clear();
}
}
struct Recording {
events: Vec<EventDomain>,
}
impl Recording {
fn new(events: Vec<EventDomain>) -> Recording {
Recording { events }
}
/// Iterates over the recording buffer and runs the specified action
/// on each event.
fn play<F>(&self, action: F)
where
F: FnMut(&EventDomain) -> (),
{
let _guard = trace_block("Recording::play", &["core", "recording"]);
self.events.iter().for_each(action)
}
}
// Tests for filtering undo / redo from the recording buffer
// A = Event
// B = Event
// U = Undo
// R = Redo
#[cfg(test)]
mod tests {
use crate::edit_types::{BufferEvent, EventDomain};
use crate::recorder::Recorder;
#[test]
fn play_recording() {
let mut recorder = Recorder::new();
let recording_name = String::new();
let mut expected_events: Vec<EventDomain> = vec![
BufferEvent::Indent.into(),
BufferEvent::Outdent.into(),
BufferEvent::DuplicateLine.into(),
BufferEvent::Transpose.into(),
];
recorder.toggle_recording(Some(recording_name.clone()));
for event in expected_events.iter().rev() {
recorder.record(event.clone());
}
recorder.toggle_recording(Some(recording_name.clone()));
recorder.play(&recording_name, |event| {
// We shouldn't iterate more times than we added items!
let expected_event = expected_events.pop();
assert!(expected_event.is_some());
// Should be the event we expect
assert_eq!(*event, expected_event.unwrap());
});
// We should have iterated over everything we inserted
assert_eq!(expected_events.len(), 0);
}
#[test]
fn play_only_after_saved() {
let mut recorder = Recorder::new();
let recording_name = String::new();
let expected_events: Vec<EventDomain> = vec![
BufferEvent::Indent.into(),
BufferEvent::Outdent.into(),
BufferEvent::DuplicateLine.into(),
BufferEvent::Transpose.into(),
];
recorder.toggle_recording(Some(recording_name.clone()));
for event in expected_events.iter().rev() {
recorder.record(event.clone());
}
recorder.play(&recording_name, |_| {
// We shouldn't have any events to play since nothing was saved!
assert!(false);
});
}
#[test]
fn prevent_same_playback() {
let mut recorder = Recorder::new();
let recording_name = String::new();
let expected_events: Vec<EventDomain> = vec![
BufferEvent::Indent.into(),
BufferEvent::Outdent.into(),
BufferEvent::DuplicateLine.into(),
BufferEvent::Transpose.into(),
];
recorder.toggle_recording(Some(recording_name.clone()));
for event in expected_events.iter().rev() {
recorder.record(event.clone());
}
recorder.toggle_recording(Some(recording_name.clone()));
recorder.toggle_recording(Some(recording_name.clone()));
recorder.play(&recording_name, |_| {
// We shouldn't be able to play a recording while recording with the same name
assert!(false);
});
}
#[test]
fn clear_recording() {
let mut recorder = Recorder::new();
let recording_name = String::new();
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.record(BufferEvent::Outdent.into());
recorder.record(BufferEvent::Indent.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(recorder.recordings.get(&recording_name).unwrap().events.len(), 4);
recorder.clear(&recording_name);
assert!(recorder.recordings.get(&recording_name).is_none());
}
#[test]
fn multiple_recordings() {
let mut recorder = Recorder::new();
let recording_a = "a".to_string();
let recording_b = "b".to_string();
recorder.toggle_recording(Some(recording_a.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.toggle_recording(Some(recording_a.clone()));
recorder.toggle_recording(Some(recording_b.clone()));
recorder.record(BufferEvent::Outdent.into());
recorder.record(BufferEvent::Indent.into());
recorder.toggle_recording(Some(recording_b.clone()));
assert_eq!(
recorder.recordings.get(&recording_a).unwrap().events,
vec![BufferEvent::Transpose.into(), BufferEvent::DuplicateLine.into()]
);
assert_eq!(
recorder.recordings.get(&recording_b).unwrap().events,
vec![BufferEvent::Outdent.into(), BufferEvent::Indent.into()]
);
recorder.clear(&recording_a);
assert!(recorder.recordings.get(&recording_a).is_none());
assert!(recorder.recordings.get(&recording_b).is_some());
}
#[test]
fn text_playback() {
let mut recorder = Recorder::new();
let recording_name = String::new();
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Insert("Foo".to_owned()).into());
recorder.record(BufferEvent::Insert("B".to_owned()).into());
recorder.record(BufferEvent::Insert("A".to_owned()).into());
recorder.record(BufferEvent::Insert("R".to_owned()).into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::Insert("FooBAR".to_owned()).into()]
);
}
#[test]
fn basic_undo() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Undo removes last item, redo only affects undo
// A U B R => B
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::Undo.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.record(BufferEvent::Redo.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::DuplicateLine.into()]
);
}
#[test]
fn basic_undo_swapped() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Swapping order of undo and redo from the basic test should give us a different leftover item
// A R B U => A
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::Redo.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.record(BufferEvent::Undo.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::Transpose.into()]
);
}
#[test]
fn redo_cancels_undo() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Redo cancels out an undo
// A U R B => A B
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::Undo.into());
recorder.record(BufferEvent::Redo.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::Transpose.into(), BufferEvent::DuplicateLine.into()]
);
}
#[test]
fn undo_cancels_redo() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Undo should cancel a redo, preventing it from canceling another undo
// A U R U => _
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::Undo.into());
recorder.record(BufferEvent::Redo.into());
recorder.record(BufferEvent::Undo.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(recorder.recordings.get(&recording_name).unwrap().events, vec![]);
}
#[test]
fn undo_as_first_item() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Undo shouldn't do anything as the first item
// U A B R => A B
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Undo.into());
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.record(BufferEvent::Redo.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::Transpose.into(), BufferEvent::DuplicateLine.into()]
);
}
#[test]
fn redo_as_first_item() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Redo shouldn't do anything as the first item
// R A B U => A
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Redo.into());
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.record(BufferEvent::Undo.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::Transpose.into()]
);
}
}
| 34.544513 | 103 | 0.596943 |
3a8a09529fc149783a37ab6ccd39c6c084fdb9cf
| 6,368 |
// Generated from definition io.k8s.api.authorization.v1beta1.SubjectRulesReviewStatus
/// SubjectRulesReviewStatus contains the result of a rules check. This check can be incomplete depending on the set of authorizers the server is configured with and any errors experienced during evaluation. Because authorization rules are additive, if a rule appears in a list it's safe to assume the subject has that permission, even if that list is incomplete.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SubjectRulesReviewStatus {
/// EvaluationError can appear in combination with Rules. It indicates an error occurred during rule evaluation, such as an authorizer that doesn't support rule evaluation, and that ResourceRules and/or NonResourceRules may be incomplete.
pub evaluation_error: Option<String>,
/// Incomplete is true when the rules returned by this call are incomplete. This is most commonly encountered when an authorizer, such as an external authorizer, doesn't support rules evaluation.
pub incomplete: bool,
/// NonResourceRules is the list of actions the subject is allowed to perform on non-resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete.
pub non_resource_rules: Vec<crate::v1_10::api::authorization::v1beta1::NonResourceRule>,
/// ResourceRules is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete.
pub resource_rules: Vec<crate::v1_10::api::authorization::v1beta1::ResourceRule>,
}
impl<'de> serde::Deserialize<'de> for SubjectRulesReviewStatus {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_evaluation_error,
Key_incomplete,
Key_non_resource_rules,
Key_resource_rules,
Other,
}
impl<'de> serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error {
Ok(match v {
"evaluationError" => Field::Key_evaluation_error,
"incomplete" => Field::Key_incomplete,
"nonResourceRules" => Field::Key_non_resource_rules,
"resourceRules" => Field::Key_resource_rules,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = SubjectRulesReviewStatus;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "struct SubjectRulesReviewStatus")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> {
let mut value_evaluation_error: Option<String> = None;
let mut value_incomplete: Option<bool> = None;
let mut value_non_resource_rules: Option<Vec<crate::v1_10::api::authorization::v1beta1::NonResourceRule>> = None;
let mut value_resource_rules: Option<Vec<crate::v1_10::api::authorization::v1beta1::ResourceRule>> = None;
while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_evaluation_error => value_evaluation_error = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_incomplete => value_incomplete = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Key_non_resource_rules => value_non_resource_rules = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Key_resource_rules => value_resource_rules = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(SubjectRulesReviewStatus {
evaluation_error: value_evaluation_error,
incomplete: value_incomplete.ok_or_else(|| serde::de::Error::missing_field("incomplete"))?,
non_resource_rules: value_non_resource_rules.ok_or_else(|| serde::de::Error::missing_field("nonResourceRules"))?,
resource_rules: value_resource_rules.ok_or_else(|| serde::de::Error::missing_field("resourceRules"))?,
})
}
}
deserializer.deserialize_struct(
"SubjectRulesReviewStatus",
&[
"evaluationError",
"incomplete",
"nonResourceRules",
"resourceRules",
],
Visitor,
)
}
}
impl serde::Serialize for SubjectRulesReviewStatus {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
let mut state = serializer.serialize_struct(
"SubjectRulesReviewStatus",
3 +
self.evaluation_error.as_ref().map_or(0, |_| 1),
)?;
if let Some(value) = &self.evaluation_error {
serde::ser::SerializeStruct::serialize_field(&mut state, "evaluationError", value)?;
}
serde::ser::SerializeStruct::serialize_field(&mut state, "incomplete", &self.incomplete)?;
serde::ser::SerializeStruct::serialize_field(&mut state, "nonResourceRules", &self.non_resource_rules)?;
serde::ser::SerializeStruct::serialize_field(&mut state, "resourceRules", &self.resource_rules)?;
serde::ser::SerializeStruct::end(state)
}
}
| 53.512605 | 363 | 0.612908 |
38c3539a7279882069210a1d0e48270399bf02a1
| 592 |
/*
* Copyright 2018 ProximaX Limited. All rights reserved.
* Use of this source code is governed by the Apache 2.0
* license that can be found in the LICENSE file.
*/
use regex::Regex;
pub fn is_hex(input: &str) -> bool {
if input == "" {
return false;
}
let re = Regex::new(r"^[a-fA-F0-9]+$").unwrap();
re.is_match(input)
}
pub fn hex_decode(data: &str) -> Vec<u8> {
hex::decode(data)
.map_err(|err| panic!("Failed to decode hex data {} : {}", data, err))
.unwrap()
}
pub fn hex_encode(bytes: &[u8]) -> String {
hex::encode(bytes)
}
| 21.142857 | 78 | 0.591216 |
febe4dd08fd3ca01e8ef841cdac3b6d1bb85dee0
| 11,140 |
use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Context, Poll};
use std::{fmt, thread};
use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::channel::oneshot::{channel, Canceled, Sender};
use futures::{Future, Stream};
use tokio::task::LocalSet;
use super::runtime::Runtime;
use super::system::System;
thread_local!(
static ADDR: RefCell<Option<Arbiter>> = RefCell::new(None);
static STORAGE: RefCell<HashMap<TypeId, Box<dyn Any>>> =
RefCell::new(HashMap::new());
);
pub(super) static COUNT: AtomicUsize = AtomicUsize::new(0);
pub(super) enum ArbiterCommand {
Stop,
Execute(Box<dyn Future<Output = ()> + Unpin + Send>),
ExecuteFn(Box<dyn FnExec>),
}
/// Arbiters provide an asynchronous execution environment for actors, functions
/// and futures. When an Arbiter is created, it spawns a new OS thread, and
/// hosts an event loop. Some Arbiter functions execute on the current thread.
pub struct Arbiter {
sender: UnboundedSender<ArbiterCommand>,
thread_handle: Option<thread::JoinHandle<()>>,
}
impl fmt::Debug for Arbiter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Arbiter")
}
}
impl Clone for Arbiter {
fn clone(&self) -> Self {
Self::with_sender(self.sender.clone())
}
}
impl Default for Arbiter {
fn default() -> Self {
Self::new()
}
}
impl Arbiter {
pub(super) fn new_system(local: &LocalSet) -> Self {
let (tx, rx) = unbounded();
let arb = Arbiter::with_sender(tx);
ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
STORAGE.with(|cell| cell.borrow_mut().clear());
local.spawn_local(ArbiterController { stop: None, rx });
arb
}
/// Returns the current thread's arbiter's address. If no Arbiter is present, then this
/// function will panic!
pub fn current() -> Arbiter {
ADDR.with(|cell| match *cell.borrow() {
Some(ref addr) => addr.clone(),
None => panic!("Arbiter is not running"),
})
}
/// Stop arbiter from continuing it's event loop.
pub fn stop(&self) {
let _ = self.sender.unbounded_send(ArbiterCommand::Stop);
}
/// Spawn new thread and run event loop in spawned thread.
/// Returns address of newly created arbiter.
pub fn new() -> Arbiter {
let id = COUNT.fetch_add(1, Ordering::Relaxed);
let name = format!("ntex-rt:worker:{}", id);
let sys = System::current();
let (arb_tx, arb_rx) = unbounded();
let arb_tx2 = arb_tx.clone();
let handle = thread::Builder::new()
.name(name.clone())
.spawn(move || {
let mut rt = Runtime::new().expect("Can not create Runtime");
let arb = Arbiter::with_sender(arb_tx);
let (stop, stop_rx) = channel();
STORAGE.with(|cell| cell.borrow_mut().clear());
System::set_current(sys);
// start arbiter controller
rt.spawn(ArbiterController {
stop: Some(stop),
rx: arb_rx,
});
ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
// register arbiter
let _ = System::current()
.sys()
.unbounded_send(SystemCommand::RegisterArbiter(id, arb));
// run loop
let _ = rt.block_on(stop_rx);
// unregister arbiter
let _ = System::current()
.sys()
.unbounded_send(SystemCommand::UnregisterArbiter(id));
})
.unwrap_or_else(|err| {
panic!("Cannot spawn an arbiter's thread {:?}: {:?}", &name, err)
});
Arbiter {
sender: arb_tx2,
thread_handle: Some(handle),
}
}
/// Send a future to the Arbiter's thread, and spawn it.
pub fn send<F>(&self, future: F)
where
F: Future<Output = ()> + Send + Unpin + 'static,
{
let _ = self
.sender
.unbounded_send(ArbiterCommand::Execute(Box::new(future)));
}
/// Send a function to the Arbiter's thread. This function will be executed asynchronously.
/// A future is created, and when resolved will contain the result of the function sent
/// to the Arbiters thread.
pub fn exec<F, R>(&self, f: F) -> impl Future<Output = Result<R, Canceled>>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let (tx, rx) = channel();
let _ = self
.sender
.unbounded_send(ArbiterCommand::ExecuteFn(Box::new(move || {
if !tx.is_canceled() {
let _ = tx.send(f());
}
})));
rx
}
/// Send a function to the Arbiter's thread, and execute it. Any result from the function
/// is discarded.
pub fn exec_fn<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let _ = self
.sender
.unbounded_send(ArbiterCommand::ExecuteFn(Box::new(move || {
f();
})));
}
/// Set item to current arbiter's storage
pub fn set_item<T: 'static>(item: T) {
STORAGE.with(move |cell| {
cell.borrow_mut().insert(TypeId::of::<T>(), Box::new(item))
});
}
/// Check if arbiter storage contains item
pub fn contains_item<T: 'static>() -> bool {
STORAGE.with(move |cell| cell.borrow().get(&TypeId::of::<T>()).is_some())
}
/// Get a reference to a type previously inserted on this arbiter's storage.
///
/// Panics is item is not inserted
pub fn get_item<T: 'static, F, R>(mut f: F) -> R
where
F: FnMut(&T) -> R,
{
STORAGE.with(move |cell| {
let st = cell.borrow();
let item = st
.get(&TypeId::of::<T>())
.and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref())
.unwrap();
f(item)
})
}
/// Get a mutable reference to a type previously inserted on this arbiter's storage.
///
/// Panics is item is not inserted
pub fn get_mut_item<T: 'static, F, R>(mut f: F) -> R
where
F: FnMut(&mut T) -> R,
{
STORAGE.with(move |cell| {
let mut st = cell.borrow_mut();
let item = st
.get_mut(&TypeId::of::<T>())
.and_then(|boxed| {
(&mut **boxed as &mut (dyn Any + 'static)).downcast_mut()
})
.unwrap();
f(item)
})
}
fn with_sender(sender: UnboundedSender<ArbiterCommand>) -> Self {
Self {
sender,
thread_handle: None,
}
}
/// Wait for the event loop to stop by joining the underlying thread (if have Some).
pub fn join(&mut self) -> thread::Result<()> {
if let Some(thread_handle) = self.thread_handle.take() {
thread_handle.join()
} else {
Ok(())
}
}
}
struct ArbiterController {
stop: Option<Sender<i32>>,
rx: UnboundedReceiver<ArbiterCommand>,
}
impl Drop for ArbiterController {
fn drop(&mut self) {
if thread::panicking() {
if System::current().stop_on_panic() {
eprintln!("Panic in Arbiter thread, shutting down system.");
System::current().stop_with_code(1)
} else {
eprintln!("Panic in Arbiter thread.");
}
}
}
}
impl Future for ArbiterController {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
match Pin::new(&mut self.rx).poll_next(cx) {
Poll::Ready(None) => return Poll::Ready(()),
Poll::Ready(Some(item)) => match item {
ArbiterCommand::Stop => {
if let Some(stop) = self.stop.take() {
let _ = stop.send(0);
};
return Poll::Ready(());
}
ArbiterCommand::Execute(fut) => {
tokio::task::spawn_local(fut);
}
ArbiterCommand::ExecuteFn(f) => {
f.call_box();
}
},
Poll::Pending => return Poll::Pending,
}
}
}
}
#[derive(Debug)]
pub(super) enum SystemCommand {
Exit(i32),
RegisterArbiter(usize, Arbiter),
UnregisterArbiter(usize),
}
#[derive(Debug)]
pub(super) struct SystemArbiter {
stop: Option<Sender<i32>>,
commands: UnboundedReceiver<SystemCommand>,
arbiters: HashMap<usize, Arbiter>,
}
impl SystemArbiter {
pub(super) fn new(
stop: Sender<i32>,
commands: UnboundedReceiver<SystemCommand>,
) -> Self {
SystemArbiter {
commands,
stop: Some(stop),
arbiters: HashMap::new(),
}
}
}
impl Future for SystemArbiter {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
match Pin::new(&mut self.commands).poll_next(cx) {
Poll::Ready(None) => return Poll::Ready(()),
Poll::Ready(Some(cmd)) => match cmd {
SystemCommand::Exit(code) => {
// stop arbiters
for arb in self.arbiters.values() {
arb.stop();
}
// stop event loop
if let Some(stop) = self.stop.take() {
let _ = stop.send(code);
}
}
SystemCommand::RegisterArbiter(name, hnd) => {
self.arbiters.insert(name, hnd);
}
SystemCommand::UnregisterArbiter(name) => {
self.arbiters.remove(&name);
}
},
Poll::Pending => return Poll::Pending,
}
}
}
}
pub(super) trait FnExec: Send + 'static {
fn call_box(self: Box<Self>);
}
impl<F> FnExec for F
where
F: FnOnce() + Send + 'static,
{
#[allow(clippy::boxed_local)]
fn call_box(self: Box<Self>) {
(*self)()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_arbiter_local_storage() {
let _s = System::new("test");
Arbiter::set_item("test");
assert!(Arbiter::get_item::<&'static str, _, _>(|s| *s == "test"));
assert!(Arbiter::get_mut_item::<&'static str, _, _>(|s| *s == "test"));
assert!(format!("{:?}", Arbiter::current()).contains("Arbiter"));
}
}
| 30.026954 | 95 | 0.513914 |
8ac66c463baa7ccc001cc1879e6e96d5bd5a802c
| 12,224 |
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use std::path::{Path, PathBuf};
use codespan_reporting::term::termcolor::Buffer;
use anyhow::anyhow;
use itertools::Itertools;
use move_prover::{cli::Options, run_move_prover};
use move_prover_test_utils::{
baseline_test::verify_or_update_baseline, extract_test_directives, read_env_var,
};
use tempfile::TempDir;
use datatest_stable::Requirements;
#[allow(unused_imports)]
use log::{debug, info, warn};
use std::sync::atomic::{AtomicBool, Ordering};
use walkdir::WalkDir;
use once_cell::sync::OnceCell;
const ENV_FLAGS: &str = "MVP_TEST_FLAGS";
const ENV_TEST_EXTENDED: &str = "MVP_TEST_X";
const ENV_TEST_INCONSISTENCY: &str = "MVP_TEST_INCONSISTENCY";
const ENV_TEST_FEATURE: &str = "MVP_TEST_FEATURE";
const ENV_TEST_ON_CI: &str = "MVP_TEST_ON_CI";
const INCONSISTENCY_TEST_FLAGS: &[&str] = &[
"--dependency=../move-stdlib/modules",
"--dependency=../diem-framework/modules",
"--check-inconsistency",
];
const REGULAR_TEST_FLAGS: &[&str] = &[
"--dependency=../move-stdlib/modules",
"--dependency=../diem-framework/modules",
];
static NOT_CONFIGURED_WARNED: AtomicBool = AtomicBool::new(false);
/// A struct to describe a feature to test.
struct Feature {
/// Name of this feature.
name: &'static str,
/// Flags specific to this feature.
flags: &'static [&'static str],
/// Inclusion mode.
inclusion_mode: InclusionMode,
/// True if the tests should only be run if requested by MVP_TEST_FEATURE
only_if_requested: bool,
/// Whether this feature will be tested in CI.
enable_in_ci: bool,
/// Whether this feature has as a separate baseline file.
separate_baseline: bool,
/// A static function pointer to the runner to be used for datatest. Since datatest
/// does not support function values and closures, we need to have a different runner for
/// each feature
runner: fn(&Path) -> datatest_stable::Result<()>,
/// A predicate to be called on the path determining whether the feature is enabled.
/// The first name is the name of the test group, the second the path to the test
/// source.
enabling_condition: fn(&str, &str) -> bool,
}
/// An inclusion mode. A feature may be run in one of these modes.
#[derive(Clone, Copy)]
enum InclusionMode {
/// Only a test which has the comment `// also_include_for: <feature>` will be included.
#[allow(dead_code)]
Explicit,
/// Every test will be included unless it has the comment `// exclude_for: <feature>`.
Implicit,
}
fn get_features() -> &'static [Feature] {
static TESTED_FEATURES: OnceCell<Vec<Feature>> = OnceCell::new();
TESTED_FEATURES.get_or_init(|| {
// Tests the default configuration.
vec![
Feature {
name: "default",
flags: &[],
inclusion_mode: InclusionMode::Implicit,
enable_in_ci: true,
only_if_requested: false,
separate_baseline: false,
runner: |p| test_runner_for_feature(p, get_feature_by_name("default")),
enabling_condition: |_, _| true,
},
// Tests with cvc4 as a backend for boogie.
Feature {
name: "cvc4",
flags: &["--use-cvc4"],
inclusion_mode: InclusionMode::Implicit,
enable_in_ci: false, // Do not enable in CI until we have more data about stability
only_if_requested: false,
separate_baseline: false,
runner: |p| test_runner_for_feature(p, get_feature_by_name("cvc4")),
enabling_condition: |group, _| group == "unit",
},
// Tests for new invariants
Feature {
name: "inv-v1",
flags: &["--inv-v1"],
inclusion_mode: InclusionMode::Implicit,
enable_in_ci: false, // Do not enable in CI until we have more data about stability
only_if_requested: false,
separate_baseline: false,
runner: |p| test_runner_for_feature(p, get_feature_by_name("inv-v1")),
enabling_condition: |_, _| true,
},
]
})
}
fn get_feature_by_name(name: &str) -> &'static Feature {
for feature in get_features() {
if feature.name == name {
return feature;
}
}
panic!("feature not found")
}
/// Test runner for a given feature.
fn test_runner_for_feature(path: &Path, feature: &Feature) -> datatest_stable::Result<()> {
// Use the below + `cargo test -- --test-threads=1` to identify a long running test
// println!(">>> testing {}", path.to_string_lossy().to_string());
info!(
"testing {} with feature `{}` (flags = `{}`)",
path.display(),
feature.name,
feature.flags.iter().map(|s| s.to_string()).join(" ")
);
let temp_dir = TempDir::new()?;
std::fs::create_dir_all(temp_dir.path())?;
let (mut args, baseline_path) = get_flags_and_baseline(temp_dir.path(), path, feature)?;
args.insert(0, "mvp_test".to_owned());
args.push("--verbose=warn".to_owned());
// TODO: timeouts aren't handled correctly by the boogie wrapper but lead to hang. Determine
// reasons and reactivate.
// args.push("--num-instances=2".to_owned()); // run two Boogie instances with different seeds
// args.push("--sequential".to_owned());
// Move source.
args.push(path.to_string_lossy().to_string());
let mut options = Options::create_from_args(&args)?;
options.setup_logging_for_test();
let no_tools = read_env_var("BOOGIE_EXE").is_empty()
|| !options.backend.use_cvc4 && read_env_var("Z3_EXE").is_empty()
|| options.backend.use_cvc4 && read_env_var("CVC4_EXE").is_empty();
let baseline_valid =
!no_tools || !extract_test_directives(path, "// no-boogie-test")?.is_empty();
if no_tools {
options.prover.generate_only = true;
if NOT_CONFIGURED_WARNED
.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
warn!(
"Prover tools are not configured, verification tests will be skipped. \
See https://github.com/diem/diem/tree/main/language/move-prover/doc/user/install.md \
for instructions."
);
}
}
options.backend.check_tool_versions()?;
options.prover.stable_test_output = true;
options.backend.stable_test_output = true;
let mut error_writer = Buffer::no_color();
let mut diags = match run_move_prover(&mut error_writer, options) {
Ok(()) => "".to_string(),
Err(err) => format!("Move prover returns: {}\n", err),
};
if baseline_valid {
if let Some(ref path) = baseline_path {
diags += &String::from_utf8_lossy(&error_writer.into_inner()).to_string();
verify_or_update_baseline(path.as_path(), &diags)?
} else if !diags.is_empty() {
return Err(anyhow!(
"Unexpected prover output (expected none): {}{}",
diags,
String::from_utf8_lossy(&error_writer.into_inner())
)
.into());
}
}
Ok(())
}
/// Returns flags and baseline file for this test run
fn get_flags_and_baseline(
temp_dir: &Path,
path: &Path,
feature: &Feature,
) -> anyhow::Result<(Vec<String>, Option<PathBuf>)> {
// Determine the way how to configure tests based on directory of the path.
let path_str = path.to_string_lossy();
let stdlib_test_flags = if read_env_var(ENV_TEST_INCONSISTENCY).is_empty() {
REGULAR_TEST_FLAGS
} else {
INCONSISTENCY_TEST_FLAGS
};
let (base_flags, baseline_path) =
if path_str.contains("diem-framework/") || path_str.contains("move-stdlib/") {
(stdlib_test_flags, None)
} else {
let feature_name = feature.name.to_string();
let separate_baseline = feature.separate_baseline
|| extract_test_directives(path, "// separate_baseline: ")?.contains(&feature_name);
(
REGULAR_TEST_FLAGS,
Some(path.with_extension(if separate_baseline {
format!("{}_exp", feature.name)
} else {
"exp".to_string()
})),
)
};
let mut flags = base_flags.iter().map(|s| (*s).to_string()).collect_vec();
// Add flags specific to the feature.
flags.extend(feature.flags.iter().map(|f| f.to_string()));
// Add flags specified in the source.
flags.extend(extract_test_directives(path, "// flag:")?);
// Add flags specified via environment variable.
flags.extend(shell_words::split(&read_env_var(ENV_FLAGS))?);
// Create a temporary file for output. We inject the modifier to potentially prevent
// any races between similar named files in different directories, as it appears TempPath
// isn't working always.
let base_name = format!("{}.bpl", path.file_stem().unwrap().to_str().unwrap());
let output = temp_dir.join(base_name).to_str().unwrap().to_string();
flags.push(format!("--output={}", output));
Ok((flags, baseline_path))
}
/// Collects the enabled tests, accumulating them as datatest requirements.
/// We collect the test data sources ourselves instead of letting datatest
/// do it because we want to select them based on enabled feature as indicated
/// in the source. We still use datatest to finally run the tests to utilize its
/// execution engine.
fn collect_enabled_tests(reqs: &mut Vec<Requirements>, group: &str, feature: &Feature, path: &str) {
let mut p = PathBuf::new();
p.push(path);
for entry in WalkDir::new(p.clone()).min_depth(1).into_iter().flatten() {
if !entry.file_name().to_string_lossy().ends_with(".move") {
continue;
}
let path = entry.path();
let mut included = match feature.inclusion_mode {
InclusionMode::Implicit => !extract_test_directives(path, "// exclude_for: ")
.unwrap_or_default()
.iter()
.any(|s| s.as_str() == feature.name),
InclusionMode::Explicit => extract_test_directives(path, "// also_include_for: ")
.unwrap_or_default()
.iter()
.any(|s| s.as_str() == feature.name),
};
if included && read_env_var(ENV_TEST_ON_CI) == "1" {
included = feature.enable_in_ci
&& extract_test_directives(path, "// no_ci:")
.unwrap_or_default()
.is_empty();
}
let root_str = p.to_string_lossy().to_string();
let path_str = path.to_string_lossy().to_string();
if included {
included = (feature.enabling_condition)(group, &path_str);
}
if included {
reqs.push(Requirements::new(
feature.runner,
format!("prover {}[{}]", group, feature.name),
root_str,
path_str,
));
}
}
}
// Test entry point based on datatest runner.
fn main() {
let mut reqs = vec![];
for feature in get_features() {
// Evaluate whether the user narrowed which feature to test.
let feature_narrow = read_env_var(ENV_TEST_FEATURE);
if !feature_narrow.is_empty() && feature.name != feature_narrow {
continue;
}
if feature_narrow.is_empty() && feature.only_if_requested {
continue;
}
// Check whether we are running extended tests
if read_env_var(ENV_TEST_EXTENDED) == "1" {
collect_enabled_tests(&mut reqs, "extended", feature, "tests/xsources");
} else {
collect_enabled_tests(&mut reqs, "unit", feature, "tests/sources");
collect_enabled_tests(&mut reqs, "stdlib", feature, "../move-stdlib");
collect_enabled_tests(&mut reqs, "diem", feature, "../diem-framework");
}
}
datatest_stable::runner(&reqs);
}
| 38.561514 | 100 | 0.612484 |
16568e1e1a28478654e584801035853f7defde72
| 1,698 |
use twitch_api2::helix::HelixClient;
use twitch_oauth2::{AccessToken, UserToken};
fn main() {
use std::error::Error;
if let Err(err) = run() {
println!("Error: {}", err);
let mut e: &'_ dyn Error = err.as_ref();
while let Some(cause) = e.source() {
println!("Caused by: {:?}", cause);
e = cause;
}
}
}
#[tokio::main]
async fn run() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
let _ = dotenv::dotenv();
let mut args = std::env::args().skip(1);
let token = UserToken::from_existing(
twitch_oauth2::client::reqwest_http_client,
std::env::var("TWITCH_TOKEN")
.ok()
.or_else(|| args.next())
.map(AccessToken::new)
.expect("Please set env: TWITCH_TOKEN or pass token as first argument"),
None,
None,
)
.await
.unwrap();
let client: HelixClient<'static, reqwest::Client> = HelixClient::new();
let streams = client.get_followed_streams(&token).await?;
let games = client
.get_games_by_id(
streams
.iter()
.map(|s| s.game_id.clone())
.collect::<Vec<_>>()
.as_slice(),
&token,
)
.await?;
println!(
"{}",
streams
.iter()
.map(|s| format!(
"{user_name}: [{game}] | {title}",
user_name = s.user_name,
game = games.get(&s.game_id).map(|c| c.name.as_str()).unwrap_or(""),
title = s.title
))
.collect::<Vec<_>>()
.join("\n")
);
Ok(())
}
| 27.387097 | 84 | 0.47821 |
1e7c236e91f1804e7d641b8ca4add0205ca4e1ec
| 1,273 |
//! Test suite for the Web and headless browsers.
#![cfg(target_arch = "wasm32")]
extern crate wasm_bindgen_test;
use keygen::*;
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
fn gen_key() {
// just test that the random generator works
let _key = Ed25519ExtendedPrivate::generate();
}
#[wasm_bindgen_test]
fn encrypt_decrypt() {
let data = [1u8; 64 * 2];
let password = [1u8, 2, 3, 4];
let encrypted = symmetric_encrypt(&password, &data).unwrap();
assert_eq!(
&symmetric_decrypt(&password, &encrypted).unwrap()[..],
&data[..]
);
}
#[wasm_bindgen_test]
fn gen_key_from_seed() {
let seed1 = [1u8; 32];
let key1 = Ed25519ExtendedPrivate::from_seed(seed1.as_ref()).unwrap();
let key2 = Ed25519ExtendedPrivate::from_seed(seed1.as_ref()).unwrap();
assert_eq!(key1.bytes(), key2.bytes());
let seed2 = [2u8; 32];
let key3 = Ed25519ExtendedPrivate::from_seed(seed2.as_ref()).unwrap();
assert_ne!(key3.bytes(), key1.bytes());
}
#[wasm_bindgen_test]
fn gen_key_from_invalid_seed_fails() {
const INVALID_SEED_SIZE: usize = 32 + 1;
let bad_seed = [2u8; INVALID_SEED_SIZE];
assert!(Ed25519ExtendedPrivate::from_seed(bad_seed.as_ref()).is_err())
}
| 26.520833 | 74 | 0.680283 |
9c2ae2fc6b83cec42242ac5d1d6d166f72fbb238
| 23,057 |
use crossbeam_channel::bounded;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use mpstthree::binary::close::close;
use mpstthree::binary::fork::fork_with_thread_id;
use mpstthree::binary::recv::recv;
use mpstthree::binary::send::send;
use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session};
use mpstthree::role::broadcast::RoleBroadcast;
use mpstthree::role::end::RoleEnd;
use mpstthree::{
bundle_struct_fork_close_multi, choose, create_fn_choose_mpst_multi_to_all_bundle,
create_multiple_normal_role_short, create_recv_mpst_session_bundle,
create_send_mpst_session_bundle, offer, offer_mpst,
};
use std::error::Error;
use std::thread::{spawn, JoinHandle};
// use std::time::Duration;
// Create the new MeshedChannels for nine participants and the close and fork functions
bundle_struct_fork_close_multi!(close_mpst_multi, fork_mpst, MeshedChannelsNine, 9);
// Create new roles
// normal
create_multiple_normal_role_short!(A, B, C, D, E, F, G, H, I);
// Create new send functions
// A
create_send_mpst_session_bundle!(
send_mpst_a_to_b, RoleB, 1 | =>
RoleA, MeshedChannelsNine, 9
);
// B
create_send_mpst_session_bundle!(
send_mpst_b_to_a, RoleA, 1 |
send_mpst_b_to_c, RoleC, 2 | =>
RoleB, MeshedChannelsNine, 9
);
// C
create_send_mpst_session_bundle!(
send_mpst_c_to_b, RoleB, 2 |
send_mpst_c_to_d, RoleD, 3 | =>
RoleC, MeshedChannelsNine, 9
);
// D
create_send_mpst_session_bundle!(
send_mpst_d_to_c, RoleC, 3 |
send_mpst_d_to_e, RoleE, 4 | =>
RoleD, MeshedChannelsNine, 9
);
// E
create_send_mpst_session_bundle!(
send_mpst_e_to_d, RoleD, 4 |
send_mpst_e_to_f, RoleF, 5 | =>
RoleE, MeshedChannelsNine, 9
);
// F
create_send_mpst_session_bundle!(
send_mpst_f_to_e, RoleE, 5 |
send_mpst_f_to_g, RoleG, 6 | =>
RoleF, MeshedChannelsNine, 9
);
// G
create_send_mpst_session_bundle!(
send_mpst_g_to_f, RoleF, 6 |
send_mpst_g_to_h, RoleH, 7 | =>
RoleG, MeshedChannelsNine, 9
);
// H
create_send_mpst_session_bundle!(
send_mpst_h_to_g, RoleG, 7 |
send_mpst_h_to_i, RoleI, 8 | =>
RoleH, MeshedChannelsNine, 9
);
// I
create_send_mpst_session_bundle!(
send_mpst_i_to_h, RoleH, 8 | =>
RoleI, MeshedChannelsNine, 9
);
// Create new recv functions and related types
// A
create_recv_mpst_session_bundle!(
recv_mpst_a_from_b, RoleB, 1 |
recv_mpst_a_from_i, RoleI, 8 | =>
RoleA, MeshedChannelsNine, 9
);
// B
create_recv_mpst_session_bundle!(
recv_mpst_b_from_a, RoleA, 1 |
recv_mpst_b_from_c, RoleC, 2 |
recv_mpst_b_from_i, RoleI, 8 | =>
RoleB, MeshedChannelsNine, 9
);
// C
create_recv_mpst_session_bundle!(
recv_mpst_c_from_b, RoleB, 2 |
recv_mpst_c_from_d, RoleD, 3 |
recv_mpst_c_from_i, RoleI, 8 | =>
RoleC, MeshedChannelsNine, 9
);
// D
create_recv_mpst_session_bundle!(
recv_mpst_d_from_c, RoleC, 3 |
recv_mpst_d_from_e, RoleE, 4 |
recv_mpst_d_from_i, RoleI, 8 | =>
RoleD, MeshedChannelsNine, 9
);
// E
create_recv_mpst_session_bundle!(
recv_mpst_e_from_d, RoleD, 4 |
recv_mpst_e_from_f, RoleF, 5 |
recv_mpst_e_from_i, RoleI, 8 | =>
RoleE, MeshedChannelsNine, 9
);
// F
create_recv_mpst_session_bundle!(
recv_mpst_f_from_e, RoleE, 5 |
recv_mpst_f_from_g, RoleG, 6 |
recv_mpst_f_from_i, RoleI, 8 | =>
RoleF, MeshedChannelsNine, 9
);
// G
create_recv_mpst_session_bundle!(
recv_mpst_g_from_f, RoleF, 6 |
recv_mpst_g_from_h, RoleH, 7 |
recv_mpst_g_from_i, RoleI, 8 | =>
RoleG, MeshedChannelsNine, 9
);
// H
create_recv_mpst_session_bundle!(
recv_mpst_h_from_g, RoleG, 7 |
recv_mpst_h_from_i, RoleI, 8 | =>
RoleH, MeshedChannelsNine, 9
);
// I
create_recv_mpst_session_bundle!(
recv_mpst_i_from_h, RoleH, 8 | =>
RoleI, MeshedChannelsNine, 9
);
// Names
type NameA = RoleA<RoleEnd>;
type NameB = RoleB<RoleEnd>;
type NameC = RoleC<RoleEnd>;
type NameD = RoleD<RoleEnd>;
type NameE = RoleE<RoleEnd>;
type NameF = RoleF<RoleEnd>;
type NameG = RoleG<RoleEnd>;
type NameH = RoleH<RoleEnd>;
type NameI = RoleI<RoleEnd>;
// Types
// A
enum Branching0fromItoA {
Forward(
MeshedChannelsNine<
Send<(), End>,
End,
End,
End,
End,
End,
End,
RecursAtoI,
RoleB<RoleI<RoleEnd>>,
NameA,
>,
),
Backward(
MeshedChannelsNine<
Recv<(), End>,
End,
End,
End,
End,
End,
End,
RecursAtoI,
RoleB<RoleI<RoleEnd>>,
NameA,
>,
),
Done(MeshedChannelsNine<End, End, End, End, End, End, End, End, RoleEnd, NameA>),
}
type RecursAtoI = <Choose0fromItoA as Session>::Dual;
// B
enum Branching0fromItoB {
Forward(
MeshedChannelsNine<
Recv<(), End>,
Send<(), End>,
End,
End,
End,
End,
End,
RecursBtoI,
RoleA<RoleC<RoleI<RoleEnd>>>,
NameB,
>,
),
Backward(
MeshedChannelsNine<
Send<(), End>,
Recv<(), End>,
End,
End,
End,
End,
End,
RecursBtoI,
RoleC<RoleA<RoleI<RoleEnd>>>,
NameB,
>,
),
Done(MeshedChannelsNine<End, End, End, End, End, End, End, End, RoleEnd, NameB>),
}
type RecursBtoI = <Choose0fromItoB as Session>::Dual;
// C
enum Branching0fromItoC {
Forward(
MeshedChannelsNine<
End,
Recv<(), End>,
Send<(), End>,
End,
End,
End,
End,
RecursCtoI,
RoleB<RoleD<RoleI<RoleEnd>>>,
NameC,
>,
),
Backward(
MeshedChannelsNine<
End,
Send<(), End>,
Recv<(), End>,
End,
End,
End,
End,
RecursCtoI,
RoleD<RoleB<RoleI<RoleEnd>>>,
NameC,
>,
),
Done(MeshedChannelsNine<End, End, End, End, End, End, End, End, RoleEnd, NameC>),
}
type RecursCtoI = <Choose0fromItoC as Session>::Dual;
// D
enum Branching0fromItoD {
Forward(
MeshedChannelsNine<
End,
End,
Recv<(), End>,
Send<(), End>,
End,
End,
End,
RecursDtoI,
RoleC<RoleE<RoleI<RoleEnd>>>,
NameD,
>,
),
Backward(
MeshedChannelsNine<
End,
End,
Send<(), End>,
Recv<(), End>,
End,
End,
End,
RecursDtoI,
RoleE<RoleC<RoleI<RoleEnd>>>,
NameD,
>,
),
Done(MeshedChannelsNine<End, End, End, End, End, End, End, End, RoleEnd, NameD>),
}
type RecursDtoI = <Choose0fromItoD as Session>::Dual;
// E
enum Branching0fromItoE {
Forward(
MeshedChannelsNine<
End,
End,
End,
Recv<(), End>,
Send<(), End>,
End,
End,
RecursEtoI,
RoleD<RoleF<RoleI<RoleEnd>>>,
NameE,
>,
),
Backward(
MeshedChannelsNine<
End,
End,
End,
Send<(), End>,
Recv<(), End>,
End,
End,
RecursEtoI,
RoleF<RoleD<RoleI<RoleEnd>>>,
NameE,
>,
),
Done(MeshedChannelsNine<End, End, End, End, End, End, End, End, RoleEnd, NameE>),
}
type RecursEtoI = <Choose0fromItoE as Session>::Dual;
// F
enum Branching0fromItoF {
Forward(
MeshedChannelsNine<
End,
End,
End,
End,
Recv<(), End>,
Send<(), End>,
End,
RecursFtoI,
RoleE<RoleG<RoleI<RoleEnd>>>,
NameF,
>,
),
Backward(
MeshedChannelsNine<
End,
End,
End,
End,
Send<(), End>,
Recv<(), End>,
End,
RecursFtoI,
RoleG<RoleE<RoleI<RoleEnd>>>,
NameF,
>,
),
Done(MeshedChannelsNine<End, End, End, End, End, End, End, End, RoleEnd, NameF>),
}
type RecursFtoI = <Choose0fromItoF as Session>::Dual;
// G
enum Branching0fromItoG {
Forward(
MeshedChannelsNine<
End,
End,
End,
End,
End,
Recv<(), End>,
Send<(), End>,
RecursGtoI,
RoleF<RoleH<RoleI<RoleEnd>>>,
NameG,
>,
),
Backward(
MeshedChannelsNine<
End,
End,
End,
End,
End,
Send<(), End>,
Recv<(), End>,
RecursGtoI,
RoleH<RoleF<RoleI<RoleEnd>>>,
NameG,
>,
),
Done(MeshedChannelsNine<End, End, End, End, End, End, End, End, RoleEnd, NameG>),
}
type RecursGtoI = <Choose0fromItoG as Session>::Dual;
// H
enum Branching0fromItoH {
Forward(
MeshedChannelsNine<
End,
End,
End,
End,
End,
End,
Recv<(), End>,
Send<(), RecursHtoI>,
RoleG<RoleI<RoleI<RoleEnd>>>,
NameH,
>,
),
Backward(
MeshedChannelsNine<
End,
End,
End,
End,
End,
End,
Send<(), End>,
Recv<(), RecursHtoI>,
RoleI<RoleG<RoleI<RoleEnd>>>,
NameH,
>,
),
Done(MeshedChannelsNine<End, End, End, End, End, End, End, End, RoleEnd, NameH>),
}
type RecursHtoI = <Choose0fromItoH as Session>::Dual;
// I
type Choose0fromItoA = Send<Branching0fromItoA, End>;
type Choose0fromItoB = Send<Branching0fromItoB, End>;
type Choose0fromItoC = Send<Branching0fromItoC, End>;
type Choose0fromItoD = Send<Branching0fromItoD, End>;
type Choose0fromItoE = Send<Branching0fromItoE, End>;
type Choose0fromItoF = Send<Branching0fromItoF, End>;
type Choose0fromItoG = Send<Branching0fromItoG, End>;
type Choose0fromItoH = Send<Branching0fromItoH, End>;
type EndpointDoneI = MeshedChannelsNine<End, End, End, End, End, End, End, End, RoleEnd, NameI>;
type EndpointForwardI = MeshedChannelsNine<
Choose0fromItoA,
Choose0fromItoB,
Choose0fromItoC,
Choose0fromItoD,
Choose0fromItoE,
Choose0fromItoF,
Choose0fromItoG,
Recv<(), Choose0fromItoH>,
RoleH<RoleBroadcast>,
NameI,
>;
type EndpointBackwardI = MeshedChannelsNine<
Choose0fromItoA,
Choose0fromItoB,
Choose0fromItoC,
Choose0fromItoD,
Choose0fromItoE,
Choose0fromItoF,
Choose0fromItoG,
Send<(), Choose0fromItoH>,
RoleH<RoleBroadcast>,
NameI,
>;
// Creating the MP sessions
type EndpointA =
MeshedChannelsNine<End, End, End, End, End, End, End, RecursAtoI, RoleI<RoleEnd>, NameA>;
type EndpointB =
MeshedChannelsNine<End, End, End, End, End, End, End, RecursBtoI, RoleI<RoleEnd>, NameB>;
type EndpointC =
MeshedChannelsNine<End, End, End, End, End, End, End, RecursCtoI, RoleI<RoleEnd>, NameC>;
type EndpointD =
MeshedChannelsNine<End, End, End, End, End, End, End, RecursDtoI, RoleI<RoleEnd>, NameD>;
type EndpointE =
MeshedChannelsNine<End, End, End, End, End, End, End, RecursEtoI, RoleI<RoleEnd>, NameE>;
type EndpointF =
MeshedChannelsNine<End, End, End, End, End, End, End, RecursFtoI, RoleI<RoleEnd>, NameF>;
type EndpointG =
MeshedChannelsNine<End, End, End, End, End, End, End, RecursGtoI, RoleI<RoleEnd>, NameG>;
type EndpointH =
MeshedChannelsNine<End, End, End, End, End, End, End, RecursHtoI, RoleI<RoleEnd>, NameH>;
type EndpointI = MeshedChannelsNine<
Choose0fromItoA,
Choose0fromItoB,
Choose0fromItoC,
Choose0fromItoD,
Choose0fromItoE,
Choose0fromItoF,
Choose0fromItoG,
Choose0fromItoH,
RoleBroadcast,
NameI,
>;
create_fn_choose_mpst_multi_to_all_bundle!(
done_from_i_to_all, forward_from_i_to_all, backward_from_i_to_all, =>
Done, Forward, Backward, =>
EndpointDoneI, EndpointForwardI, EndpointBackwardI, =>
Branching0fromItoA,
Branching0fromItoB,
Branching0fromItoC,
Branching0fromItoD,
Branching0fromItoE,
Branching0fromItoF,
Branching0fromItoG,
Branching0fromItoH, =>
RoleA, RoleB, RoleC, RoleD, RoleE, RoleF, RoleG, RoleH, =>
RoleI, MeshedChannelsNine, 9
);
fn endpoint_a(s: EndpointA) -> Result<(), Box<dyn Error>> {
offer_mpst!(s, recv_mpst_a_from_i, {
Branching0fromItoA::Done(s) => {
close_mpst_multi(s)
},
Branching0fromItoA::Forward(s) => {
let s = send_mpst_a_to_b((), s);
endpoint_a(s)
},
Branching0fromItoA::Backward(s) => {
let (_, s) = recv_mpst_a_from_b(s)?;
endpoint_a(s)
},
})
}
fn endpoint_b(s: EndpointB) -> Result<(), Box<dyn Error>> {
offer_mpst!(s, recv_mpst_b_from_i, {
Branching0fromItoB::Done(s) => {
close_mpst_multi(s)
},
Branching0fromItoB::Forward(s) => {
let ((), s) = recv_mpst_b_from_a(s)?;
let s = send_mpst_b_to_c((), s);
endpoint_b(s)
},
Branching0fromItoB::Backward(s) => {
let ((), s) = recv_mpst_b_from_c(s)?;
let s = send_mpst_b_to_a((), s);
endpoint_b(s)
},
})
}
fn endpoint_c(s: EndpointC) -> Result<(), Box<dyn Error>> {
offer_mpst!(s, recv_mpst_c_from_i, {
Branching0fromItoC::Done(s) => {
close_mpst_multi(s)
},
Branching0fromItoC::Forward(s) => {
let ((), s) = recv_mpst_c_from_b(s)?;
let s = send_mpst_c_to_d((), s);
endpoint_c(s)
},
Branching0fromItoC::Backward(s) => {
let ((), s) = recv_mpst_c_from_d(s)?;
let s = send_mpst_c_to_b((), s);
endpoint_c(s)
},
})
}
fn endpoint_d(s: EndpointD) -> Result<(), Box<dyn Error>> {
offer_mpst!(s, recv_mpst_d_from_i, {
Branching0fromItoD::Done(s) => {
close_mpst_multi(s)
},
Branching0fromItoD::Forward(s) => {
let ((), s) = recv_mpst_d_from_c(s)?;
let s = send_mpst_d_to_e((), s);
endpoint_d(s)
},
Branching0fromItoD::Backward(s) => {
let ((), s) = recv_mpst_d_from_e(s)?;
let s = send_mpst_d_to_c((), s);
endpoint_d(s)
},
})
}
fn endpoint_e(s: EndpointE) -> Result<(), Box<dyn Error>> {
offer_mpst!(s, recv_mpst_e_from_i, {
Branching0fromItoE::Done(s) => {
close_mpst_multi(s)
},
Branching0fromItoE::Forward(s) => {
let ((), s) = recv_mpst_e_from_d(s)?;
let s = send_mpst_e_to_f((), s);
endpoint_e(s)
},
Branching0fromItoE::Backward(s) => {
let ((), s) = recv_mpst_e_from_f(s)?;
let s = send_mpst_e_to_d((), s);
endpoint_e(s)
},
})
}
fn endpoint_f(s: EndpointF) -> Result<(), Box<dyn Error>> {
offer_mpst!(s, recv_mpst_f_from_i, {
Branching0fromItoF::Done(s) => {
close_mpst_multi(s)
},
Branching0fromItoF::Forward(s) => {
let ((), s) = recv_mpst_f_from_e(s)?;
let s = send_mpst_f_to_g((), s);
endpoint_f(s)
},
Branching0fromItoF::Backward(s) => {
let ((), s) = recv_mpst_f_from_g(s)?;
let s = send_mpst_f_to_e((), s);
endpoint_f(s)
},
})
}
fn endpoint_g(s: EndpointG) -> Result<(), Box<dyn Error>> {
offer_mpst!(s, recv_mpst_g_from_i, {
Branching0fromItoG::Done(s) => {
close_mpst_multi(s)
},
Branching0fromItoG::Forward(s) => {
let ((), s) = recv_mpst_g_from_f(s)?;
let s = send_mpst_g_to_h((), s);
endpoint_g(s)
},
Branching0fromItoG::Backward(s) => {
let ((), s) = recv_mpst_g_from_h(s)?;
let s = send_mpst_g_to_f((), s);
endpoint_g(s)
},
})
}
fn endpoint_h(s: EndpointH) -> Result<(), Box<dyn Error>> {
offer_mpst!(s, recv_mpst_h_from_i, {
Branching0fromItoH::Done(s) => {
close_mpst_multi(s)
},
Branching0fromItoH::Forward(s) => {
let ((), s) = recv_mpst_h_from_g(s)?;
let s = send_mpst_h_to_i((), s);
endpoint_h(s)
},
Branching0fromItoH::Backward(s) => {
let ((), s) = recv_mpst_h_from_i(s)?;
let s = send_mpst_h_to_g((), s);
endpoint_h(s)
},
})
}
fn endpoint_i(s: EndpointI) -> Result<(), Box<dyn Error>> {
recurs_i(s, LOOPS)
}
fn recurs_i(s: EndpointI, index: i64) -> Result<(), Box<dyn Error>> {
match index {
0 => {
let s = done_from_i_to_all(s);
close_mpst_multi(s)
}
i if i % 2 == 0 => {
let s = forward_from_i_to_all(s);
let (_, s) = recv_mpst_i_from_h(s)?;
recurs_i(s, i - 1)
}
i => {
let s = backward_from_i_to_all(s);
let s = send_mpst_i_to_h((), s);
recurs_i(s, i - 1)
}
}
}
fn all_mpst() {
let (thread_a, thread_b, thread_c, thread_d, thread_e, thread_f, thread_g, thread_h, thread_i) =
fork_mpst(
black_box(endpoint_a),
black_box(endpoint_b),
black_box(endpoint_c),
black_box(endpoint_d),
black_box(endpoint_e),
black_box(endpoint_f),
black_box(endpoint_g),
black_box(endpoint_h),
black_box(endpoint_i),
);
thread_a.join().unwrap();
thread_b.join().unwrap();
thread_c.join().unwrap();
thread_d.join().unwrap();
thread_e.join().unwrap();
thread_f.join().unwrap();
thread_g.join().unwrap();
thread_h.join().unwrap();
thread_i.join().unwrap();
}
/////////////////////////
// A
enum BinaryA {
Forward(Recv<(), Send<(), RecursA>>),
Done(End),
}
type RecursA = Recv<BinaryA, End>;
fn binary_a_to_b(s: RecursA) -> Result<(), Box<dyn Error>> {
offer!(s, {
BinaryA::Done(s) => {
close(s)
},
BinaryA::Forward(s) => {
let (_, s) = recv(s)?;
let s = send((), s);
binary_a_to_b(s)
},
})
}
// B
type RecursB = <RecursA as Session>::Dual;
fn binary_b_to_a(s: Send<(), Recv<(), RecursB>>) -> Result<RecursB, Box<dyn Error>> {
let s = send((), s);
let (_, s) = recv(s)?;
Ok(s)
}
fn all_binaries() {
let mut threads = Vec::new();
let mut sessions = Vec::new();
for _ in 0..9 {
let (thread, s): (JoinHandle<()>, RecursB) = fork_with_thread_id(black_box(binary_a_to_b));
threads.push(thread);
sessions.push(s);
}
let main = spawn(move || {
for _ in 0..LOOPS {
sessions = sessions
.into_iter()
.map(|s| binary_b_to_a(choose!(BinaryA::Forward, s)).unwrap())
.collect::<Vec<_>>();
}
sessions
.into_iter()
.for_each(|s| close(choose!(BinaryA::Done, s)).unwrap());
threads.into_iter().for_each(|elt| elt.join().unwrap());
});
main.join().unwrap();
}
/////////////////////////
type ReceivingSendingReceiving = crossbeam_channel::Receiver<SendingReceiving>;
type SendingReceivingSending = crossbeam_channel::Sender<ReceivingSending>;
type SendingReceiving = crossbeam_channel::Sender<Receiving>;
type ReceivingSending = crossbeam_channel::Receiver<Sending>;
type Receiving = crossbeam_channel::Receiver<()>;
type Sending = crossbeam_channel::Sender<()>;
fn all_crossbeam() {
let mut threads = Vec::new();
for _ in 0..9 {
let main = spawn(move || {
for _ in 0..LOOPS {
let (sender_0, receiver_0) = bounded::<ReceivingSendingReceiving>(1);
let (sender_4, receiver_4) = bounded::<SendingReceivingSending>(1);
let (sender_1, receiver_1) = bounded::<SendingReceiving>(1);
let (sender_5, receiver_5) = bounded::<ReceivingSending>(1);
let (sender_2, receiver_2) = bounded::<Receiving>(1);
let (sender_6, receiver_6) = bounded::<Sending>(1);
let (sender_3, receiver_3) = bounded::<()>(1);
let (sender_7, receiver_7) = bounded::<()>(1);
sender_0.send(receiver_1).unwrap();
sender_4.send(sender_5).unwrap();
let receiver_1_bis = receiver_0.recv().unwrap();
let sender_5_bis = receiver_4.recv().unwrap();
sender_1.send(sender_2).unwrap();
sender_5_bis.send(receiver_6).unwrap();
let sender_2_bis = receiver_1_bis.recv().unwrap();
let receiver_6_bis = receiver_5.recv().unwrap();
sender_2_bis.send(receiver_3).unwrap();
sender_6.send(sender_7).unwrap();
let receiver_2_bis = receiver_2.recv().unwrap();
let sender_7_bis = receiver_6_bis.recv().unwrap();
sender_3.send(()).unwrap();
sender_7_bis.send(()).unwrap();
receiver_2_bis.recv().unwrap();
receiver_7.recv().unwrap();
}
// "Close" connection
let (sender_close_1, receiver_close_1) = bounded::<()>(1);
let (sender_close_2, receiver_close_2) = bounded::<()>(1);
sender_close_1.send(()).unwrap_or(());
sender_close_2.send(()).unwrap_or(());
receiver_close_1.recv().unwrap_or(());
receiver_close_2.recv().unwrap_or(());
});
threads.push(main);
}
threads.into_iter().for_each(|elt| elt.join().unwrap());
}
/////////////////////////
static LOOPS: i64 = 0;
fn ring_protocol_mpst(c: &mut Criterion) {
c.bench_function(&format!("ring nine empty protocol MPST {}", LOOPS), |b| {
b.iter(all_mpst)
});
}
fn ring_protocol_binary(c: &mut Criterion) {
c.bench_function(&format!("ring nine empty protocol binary {}", LOOPS), |b| {
b.iter(all_binaries)
});
}
fn ring_protocol_crossbeam(c: &mut Criterion) {
c.bench_function(
&format!("ring nine empty protocol crossbeam {}", LOOPS),
|b| b.iter(all_crossbeam),
);
}
criterion_group! {
name = ring_nine;
config = Criterion::default().significance_level(0.1).sample_size(10100);
targets = ring_protocol_mpst, ring_protocol_binary, ring_protocol_crossbeam
}
criterion_main!(ring_nine);
| 26.998829 | 100 | 0.557271 |
f86474e770bfba1895dca3d79ddf13b0e5ed74f0
| 261 |
use actix_web::{server, App, HttpRequest};
fn index(_req: &HttpRequest) -> &'static str {
"Hello world from GAE!"
}
fn main() {
server::new(|| App::new().resource("/", |r| r.f(index)))
.bind("0.0.0.0:8080")
.unwrap()
.run();
}
| 20.076923 | 60 | 0.528736 |
fb5a051c107920a1c100b5a07d5367509adc63be
| 6,017 |
//! Applies the nonlinear Log-Sigmoid function.
//!
//! Non-linearity activation function: y = (1 + e^(-x))^(-1)
//!
//! A classic choice in neural networks.
//! But you might consider using ReLu as an alternative.
//!
//! ReLu, compared to Sigmoid
//!
//! * reduces the likelyhood of vanishing gradients
//! * increases the likelyhood of a more beneficial sparse representation
//! * can be computed faster
//! * is therefore the most popular activation function in DNNs as of this
//! writing (2015).
use co::{IBackend, SharedTensor};
use conn;
use layer::*;
use util::ArcLock;
#[derive(Debug, Clone)]
#[allow(missing_copy_implementations)]
/// Sigmoid Activation Layer
pub struct Sigmoid;
//
// Sigmoid + SigmoidPointwise
// Only on CUDA
//
#[cfg(all(feature="cuda", not(feature="native")))]
impl<B: IBackend + conn::Sigmoid<f32> + conn::SigmoidPointwise<f32>> ILayer<B> for Sigmoid {
impl_ilayer_activation!();
fn compute_in_place(&self) -> bool {
true
}
fn reshape(&mut self,
backend: ::std::rc::Rc<B>,
input_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
input_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>,
weights_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
weights_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>,
output_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
output_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>) {
if let Some(inp) = input_data.get(0) {
let read_inp = inp.read().unwrap();
let input_desc = read_inp.desc();
input_gradient[0].write().unwrap().resize(input_desc).unwrap();
output_data[0].write().unwrap().resize(input_desc).unwrap();
output_gradient[0].write().unwrap().resize(input_desc).unwrap();
}
}
}
#[cfg(all(feature="cuda", not(feature="native")))]
impl<B: IBackend + conn::Sigmoid<f32> + conn::SigmoidPointwise<f32>> ComputeOutput<f32, B> for Sigmoid {
fn compute_output(&self,
backend: &B,
_weights: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
output_data: &mut [&mut SharedTensor<f32>]) {
match input_data.get(0) {
Some(input) => backend.sigmoid_plain(input, output_data[0]).unwrap(),
None => backend.sigmoid_pointwise_plain(output_data[0]).unwrap(),
}
}
}
#[cfg(all(feature="cuda", not(feature="native")))]
impl<B: IBackend + conn::Sigmoid<f32> + conn::SigmoidPointwise<f32>> ComputeInputGradient<f32, B> for Sigmoid {
fn compute_input_gradient(&self,
backend: &B,
weights_data: &[&SharedTensor<f32>],
output_data: &[&SharedTensor<f32>],
output_gradients: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
input_gradients: &mut [&mut SharedTensor<f32>]) {
match output_data.get(0) {
Some(_) => backend.sigmoid_grad_plain(output_data[0], output_gradients[0], input_data[0], input_gradients[0]).unwrap(),
None => backend.sigmoid_pointwise_grad_plain(input_data[0], input_gradients[0]).unwrap(),
}
}
}
#[cfg(all(feature="cuda", not(feature="native")))]
impl<B: IBackend + conn::Sigmoid<f32> + conn::SigmoidPointwise<f32>> ComputeParametersGradient<f32, B> for Sigmoid {}
//
// Sigmoid without SigmoidPointwise
// Only on CUDA
//
#[cfg(feature="native")]
impl<B: IBackend + conn::Sigmoid<f32>> ILayer<B> for Sigmoid {
impl_ilayer_activation!();
fn reshape(&mut self,
backend: ::std::rc::Rc<B>,
input_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
input_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>,
weights_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
weights_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>,
output_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
output_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>) {
if let Some(inp) = input_data.get(0) {
let read_inp = inp.read().unwrap();
let input_desc = read_inp.desc();
input_gradient[0].write().unwrap().resize(input_desc).unwrap();
output_data[0].write().unwrap().resize(input_desc).unwrap();
output_gradient[0].write().unwrap().resize(input_desc).unwrap();
}
}
}
#[cfg(feature="native")]
impl<B: IBackend + conn::Sigmoid<f32>> ComputeOutput<f32, B> for Sigmoid {
fn compute_output(&self,
backend: &B,
_weights: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
output_data: &mut [&mut SharedTensor<f32>]) {
match input_data.get(0) {
Some(input) => backend.sigmoid_plain(input, output_data[0]).unwrap(),
None => panic!("No input provided for Sigmoid layer."),
}
}
}
#[cfg(feature="native")]
impl<B: IBackend + conn::Sigmoid<f32>> ComputeInputGradient<f32, B> for Sigmoid {
fn compute_input_gradient(&self,
backend: &B,
weights_data: &[&SharedTensor<f32>],
output_data: &[&SharedTensor<f32>],
output_gradients: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
input_gradients: &mut [&mut SharedTensor<f32>]) {
match output_data.get(0) {
Some(_) => backend.sigmoid_grad_plain(output_data[0], output_gradients[0], input_data[0], input_gradients[0]).unwrap(),
None => panic!("No output_data provided for Sigmoid layer backward."),
}
}
}
#[cfg(feature="native")]
impl<B: IBackend + conn::Sigmoid<f32>> ComputeParametersGradient<f32, B> for Sigmoid {}
| 41.212329 | 131 | 0.586006 |
3a2d7d23819826d40a9e43b6fca34a85675acec5
| 8,790 |
#![feature(const_generics)]
#![allow(warnings)]
use std::{
fmt::Display,
mem::size_of,
process::exit,
};
use borsh::BorshDeserialize;
use clap::{
crate_description,
crate_name,
crate_version,
value_t,
App,
AppSettings,
Arg,
SubCommand,
};
use hex;
use solana_clap_utils::{
input_parsers::{
keypair_of,
pubkey_of,
value_of,
},
input_validators::{
is_keypair,
is_pubkey_or_keypair,
is_url,
},
};
use solana_client::{
rpc_client::RpcClient,
rpc_config::RpcSendTransactionConfig,
};
use solana_sdk::{
commitment_config::{
CommitmentConfig,
CommitmentLevel,
},
native_token::*,
program_error::ProgramError::AccountAlreadyInitialized,
pubkey::Pubkey,
signature::{
read_keypair_file,
Keypair,
Signer,
},
system_instruction::transfer,
transaction::Transaction,
};
use solitaire::{
processors::seeded::Seeded,
AccountState,
Info,
};
use solitaire_client::Derive;
struct Config {
rpc_client: RpcClient,
owner: Keypair,
fee_payer: Keypair,
commitment_config: CommitmentConfig,
}
type Error = Box<dyn std::error::Error>;
type CommmandResult = Result<Option<Transaction>, Error>;
fn command_init_bridge(config: &Config, bridge: &Pubkey, core_bridge: &Pubkey) -> CommmandResult {
println!("Initializing Token bridge {}", bridge);
let minimum_balance_for_rent_exemption = config
.rpc_client
.get_minimum_balance_for_rent_exemption(size_of::<token_bridge::types::Config>())?;
let ix = token_bridge::instructions::initialize(*bridge, config.owner.pubkey(), *core_bridge)
.unwrap();
println!("config account: {}, ", ix.accounts[1].pubkey.to_string());
let mut transaction = Transaction::new_with_payer(&[ix], Some(&config.fee_payer.pubkey()));
let (recent_blockhash, fee_calculator) = config.rpc_client.get_recent_blockhash()?;
check_fee_payer_balance(
config,
minimum_balance_for_rent_exemption + fee_calculator.calculate_fee(&transaction.message()),
)?;
transaction.sign(&[&config.fee_payer, &config.owner], recent_blockhash);
Ok(Some(transaction))
}
fn main() {
let matches = App::new(crate_name!())
.about(crate_description!())
.version(crate_version!())
.setting(AppSettings::SubcommandRequiredElseHelp)
.arg({
let arg = Arg::with_name("config_file")
.short("C")
.long("config")
.value_name("PATH")
.takes_value(true)
.global(true)
.help("Configuration file to use");
if let Some(ref config_file) = *solana_cli_config::CONFIG_FILE {
arg.default_value(&config_file)
} else {
arg
}
})
.arg(
Arg::with_name("json_rpc_url")
.long("url")
.value_name("URL")
.takes_value(true)
.validator(is_url)
.help("JSON RPC URL for the cluster. Default from the configuration file."),
)
.arg(
Arg::with_name("owner")
.long("owner")
.value_name("KEYPAIR")
.validator(is_keypair)
.takes_value(true)
.help(
"Specify the contract payer account. \
This may be a keypair file, the ASK keyword. \
Defaults to the client keypair.",
),
)
.arg(
Arg::with_name("fee_payer")
.long("fee-payer")
.value_name("KEYPAIR")
.validator(is_keypair)
.takes_value(true)
.help(
"Specify the fee-payer account. \
This may be a keypair file, the ASK keyword. \
Defaults to the client keypair.",
),
)
.subcommand(
SubCommand::with_name("create-bridge")
.about("Create a new bridge")
.arg(
Arg::with_name("bridge")
.long("bridge")
.value_name("BRIDGE_KEY")
.validator(is_pubkey_or_keypair)
.takes_value(true)
.index(1)
.required(true)
.help("Specify the token bridge program address"),
)
.arg(
Arg::with_name("core-bridge")
.validator(is_pubkey_or_keypair)
.value_name("CORE_BRIDGE_KEY")
.takes_value(true)
.index(2)
.required(true)
.help("Address of the Wormhole core bridge program"),
),
)
.get_matches();
let config = {
let cli_config = if let Some(config_file) = matches.value_of("config_file") {
solana_cli_config::Config::load(config_file).unwrap_or_default()
} else {
solana_cli_config::Config::default()
};
let json_rpc_url = value_t!(matches, "json_rpc_url", String)
.unwrap_or_else(|_| cli_config.json_rpc_url.clone());
let client_keypair = || {
read_keypair_file(&cli_config.keypair_path).unwrap_or_else(|err| {
eprintln!("Unable to read {}: {}", cli_config.keypair_path, err);
exit(1)
})
};
let owner = keypair_of(&matches, "owner").unwrap_or_else(client_keypair);
let fee_payer = keypair_of(&matches, "fee_payer").unwrap_or_else(client_keypair);
Config {
rpc_client: RpcClient::new(json_rpc_url),
owner,
fee_payer,
commitment_config: CommitmentConfig::processed(),
}
};
let _ = match matches.subcommand() {
("create-bridge", Some(arg_matches)) => {
let bridge = pubkey_of(arg_matches, "bridge").unwrap();
let core_bridge = pubkey_of(arg_matches, "core-bridge").unwrap();
command_init_bridge(&config, &bridge, &core_bridge)
}
_ => unreachable!(),
}
.and_then(|transaction| {
if let Some(transaction) = transaction {
let signature = config
.rpc_client
.send_and_confirm_transaction_with_spinner_and_config(
&transaction,
config.commitment_config,
RpcSendTransactionConfig {
skip_preflight: true,
preflight_commitment: None,
encoding: None,
},
)?;
println!("Signature: {}", signature);
}
Ok(())
})
.map_err(|err| {
eprintln!("{}", err);
exit(1);
});
}
pub fn is_u8<T>(amount: T) -> Result<(), String>
where
T: AsRef<str> + Display,
{
if amount.as_ref().parse::<u8>().is_ok() {
Ok(())
} else {
Err(format!(
"Unable to parse input amount as integer, provided: {}",
amount
))
}
}
pub fn is_u32<T>(amount: T) -> Result<(), String>
where
T: AsRef<str> + Display,
{
if amount.as_ref().parse::<u32>().is_ok() {
Ok(())
} else {
Err(format!(
"Unable to parse input amount as integer, provided: {}",
amount
))
}
}
pub fn is_u64<T>(amount: T) -> Result<(), String>
where
T: AsRef<str> + Display,
{
if amount.as_ref().parse::<u64>().is_ok() {
Ok(())
} else {
Err(format!(
"Unable to parse input amount as integer, provided: {}",
amount
))
}
}
pub fn is_hex<T>(value: T) -> Result<(), String>
where
T: AsRef<str> + Display,
{
hex::decode(value.to_string())
.map(|_| ())
.map_err(|e| format!("{}", e))
}
fn check_fee_payer_balance(config: &Config, required_balance: u64) -> Result<(), Error> {
let balance = config
.rpc_client
.get_balance_with_commitment(
&config.fee_payer.pubkey(),
CommitmentConfig {
commitment: CommitmentLevel::Processed,
},
)?
.value;
if balance < required_balance {
Err(format!(
"Fee payer, {}, has insufficient balance: {} required, {} available",
config.fee_payer.pubkey(),
lamports_to_sol(required_balance),
lamports_to_sol(balance)
)
.into())
} else {
Ok(())
}
}
| 29.202658 | 98 | 0.527873 |
eb2dff74baa28320427ceb505a270d5b0c284eda
| 1,382 |
impl Solution {
pub fn majority_element(nums: Vec<i32>) -> Vec<i32> {
let mut x = 1e8 as i32;
let mut y = x;
let mut count_x = 0;
let mut count_y = 0;
for &i in nums.iter() {
if i == x {
count_x += 1;
} else if i ==y {
count_y += 1;
} else if count_x == 0 {
x = i;
count_x = 1;
} else if count_y == 0 {
y = i;
count_y = 1;
} else {
count_x -= 1;
count_y -= 1;
}
}
count_x = 0;
count_y = 0;
for &i in nums.iter() {
if i == x {
count_x += 1;
} else if i == y {
count_y += 1;
}
}
let mut res = Vec::with_capacity(2);
if count_x > nums.len() / 3 {
res.push(x);
}
if count_y > nums.len() / 3 {
res.push(y);
}
res
}
}
struct Solution;
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn test_majority_element() {
assert_eq!(
Solution::majority_element(vec![3,2,3]),
vec![3]
);
assert_eq!(
Solution::majority_element(vec![1,1,1,3,3,2,2,2]),
vec![1,2]
);
}
}
| 23.423729 | 62 | 0.369754 |
791e3b8863766bb0dbdb97c236f411b7dc1095a9
| 6,748 |
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use futures::future::try_join_all;
use itertools::Itertools;
use parking_lot::RwLock;
use segment::entry::entry_point::OperationError;
use tokio::runtime::Handle;
use segment::spaces::tools::peek_top_largest_scores_iterable;
use segment::types::{PointIdType, ScoredPoint, SeqNumberType, WithPayload, WithPayloadInterface};
use crate::collection_manager::collection_managers::CollectionSearcher;
use crate::collection_manager::holders::segment_holder::{LockedSegment, SegmentHolder};
use crate::operations::types::CollectionResult;
use crate::operations::types::{Record, SearchRequest};
/// Simple implementation of segment manager
/// - rebuild segment for memory optimization purposes
#[derive(Default)]
pub struct SimpleCollectionSearcher {}
impl SimpleCollectionSearcher {
pub fn new() -> Self {
Self {}
}
}
#[async_trait::async_trait]
impl CollectionSearcher for SimpleCollectionSearcher {
async fn search(
&self,
segments: &RwLock<SegmentHolder>,
request: Arc<SearchRequest>,
runtime_handle: &Handle,
) -> CollectionResult<Vec<ScoredPoint>> {
// Using { } block to ensure segments variable is dropped in the end of it
// and is not transferred across the all_searches.await? boundary as it
// does not impl Send trait
let searches: Vec<_> = {
let segments = segments.read();
let some_segment = segments.iter().next();
if some_segment.is_none() {
return Ok(vec![]);
}
segments
.iter()
.map(|(_id, segment)| search_in_segment(segment.clone(), request.clone()))
.map(|f| runtime_handle.spawn(f))
.collect()
};
let all_searches = try_join_all(searches);
let all_search_results = all_searches.await?;
match all_search_results
.iter()
.filter_map(|res| res.to_owned().err())
.next()
{
None => {}
Some(error) => return Err(error),
}
let mut seen_idx: HashSet<PointIdType> = HashSet::new();
let top_scores = peek_top_largest_scores_iterable(
all_search_results
.into_iter()
.flat_map(Result::unwrap) // already checked for errors
.sorted_by_key(|a| (a.id, 1 - a.version as i64)) // Prefer higher version first
.dedup_by(|a, b| a.id == b.id) // Keep only highest version
.filter(|scored| {
let res = seen_idx.contains(&scored.id);
seen_idx.insert(scored.id);
!res
}),
request.top,
);
Ok(top_scores)
}
async fn retrieve(
&self,
segments: &RwLock<SegmentHolder>,
points: &[PointIdType],
with_payload: &WithPayload,
with_vector: bool,
) -> CollectionResult<Vec<Record>> {
let mut point_version: HashMap<PointIdType, SeqNumberType> = Default::default();
let mut point_records: HashMap<PointIdType, Record> = Default::default();
segments.read().read_points(points, |id, segment| {
let version = segment.point_version(id).ok_or_else(|| {
OperationError::service_error(&format!("No version for point {}", id))
})?;
// If this point was not found yet or this segment have later version
if !point_version.contains_key(&id) || point_version[&id] < version {
point_records.insert(
id,
Record {
id,
payload: if with_payload.enable {
if let Some(selector) = &with_payload.payload_selector {
Some(selector.process(segment.payload(id)?))
} else {
Some(segment.payload(id)?)
}
} else {
None
},
vector: if with_vector {
Some(segment.vector(id)?)
} else {
None
},
},
);
point_version.insert(id, version);
}
Ok(true)
})?;
Ok(point_records.into_iter().map(|(_, r)| r).collect())
}
}
async fn search_in_segment(
segment: LockedSegment,
request: Arc<SearchRequest>,
) -> CollectionResult<Vec<ScoredPoint>> {
let with_payload_interface = request
.with_payload
.as_ref()
.unwrap_or(&WithPayloadInterface::Bool(false));
let with_payload = WithPayload::from(with_payload_interface);
let with_vector = request.with_vector;
let res = segment.get().read().search(
&request.vector,
&with_payload,
with_vector,
request.filter.as_ref(),
request.top,
request.params.as_ref(),
)?;
Ok(res)
}
#[cfg(test)]
mod tests {
use tempdir::TempDir;
use crate::collection_manager::fixtures::build_test_holder;
use super::*;
#[tokio::test]
async fn test_segments_search() {
let dir = TempDir::new("segment_dir").unwrap();
let segment_holder = build_test_holder(dir.path());
let searcher = SimpleCollectionSearcher::new();
let query = vec![1.0, 1.0, 1.0, 1.0];
let req = Arc::new(SearchRequest {
vector: query,
with_payload: None,
with_vector: false,
filter: None,
params: None,
top: 5,
score_threshold: None,
});
let result = searcher
.search(&segment_holder, req, &Handle::current())
.await
.unwrap();
// eprintln!("result = {:?}", &result);
assert_eq!(result.len(), 5);
assert!(result[0].id == 3.into() || result[0].id == 11.into());
assert!(result[1].id == 3.into() || result[1].id == 11.into());
}
#[tokio::test]
async fn test_retrieve() {
let dir = TempDir::new("segment_dir").unwrap();
let segment_holder = build_test_holder(dir.path());
let searcher = SimpleCollectionSearcher::new();
let records = searcher
.retrieve(
&segment_holder,
&[1.into(), 2.into(), 3.into()],
&WithPayload::from(true),
true,
)
.await
.unwrap();
assert_eq!(records.len(), 3);
}
}
| 31.53271 | 97 | 0.541494 |
fc5c139df26fdd562925b4f7af9dd47424c2464f
| 12,366 |
use csv;
use itertools::Itertools;
use phf::Map;
use std::cmp::Ord;
use std::collections::HashMap;
use std::fs::File;
use std::path::Path;
use std::path::PathBuf;
use x86::perfcnt::intel::events::COUNTER_MAP;
use x86::perfcnt::intel::{EventDescription, Tuple};
use super::profile::{MonitoringUnit, PerfEvent};
use super::util::*;
type EventMap = Map<&'static str, EventDescription<'static>>;
type ArchitectureMap = HashMap<&'static str, (&'static str, &'static str, &'static str)>;
/// Saves the event count for all architectures to a file.
fn save_event_counts(key_to_name: &ArchitectureMap, csv_result: &Path) {
let mut writer = csv::Writer::from_file(csv_result).unwrap();
writer
.encode(&[
"year",
"architecture",
"core events",
"uncore events",
"counters",
"uncore groups",
])
.expect(format!("Can't write {:?} header", csv_result).as_str());
for (key, &(name, year, counters)) in key_to_name.iter() {
let events = COUNTER_MAP.get(format!("{}", key).as_str());
let counter_groups: Vec<(MonitoringUnit, usize)> = events.map_or(Vec::new(), |uc| {
let mut units: Vec<(MonitoringUnit, PerfEvent)> = Vec::with_capacity(uc.len());
for ref e in uc.values() {
if e.uncore {
units.push((PerfEvent(&e).unit(), PerfEvent(&e)));
}
}
units.sort_by(|a, b| a.0.cmp(&b.0));
let mut counts: Vec<(MonitoringUnit, usize)> = Vec::with_capacity(10);
for (key, group) in &units.into_iter().group_by(|&(unit, _)| unit) {
counts.push((key, group.count()));
}
counts
});
let cc_count = events
.map(|c| {
let filtered: Vec<&EventDescription> = c.values().filter(|e| !e.uncore).collect();
filtered.len()
})
.unwrap_or(0);
let uc_count = events
.map(|c| {
let filtered: Vec<&EventDescription> = c.values().filter(|e| e.uncore).collect();
filtered.len()
})
.unwrap_or(0);
let group_string = counter_groups
.into_iter()
.map(|(u, c)| format!("{}:{}", u, c))
.join(";");
let cc_count = cc_count.to_string();
let uc_count = uc_count.to_string();
let mut row: Vec<&str> = Vec::new();
row.push(year);
row.push(name);
row.push(cc_count.as_str());
row.push(uc_count.as_str());
row.push(counters);
row.push(group_string.as_str());
writer
.encode(&row.as_slice())
.expect(format!("Can't write for for {:?} file", csv_result).as_str());
}
}
/// Given two EventMaps count all the shared (same event name key) events.
fn common_event_names(a: Option<&'static EventMap>, b: Option<&'static EventMap>) -> usize {
if a.is_none() || b.is_none() {
return 0;
}
let a_map = a.unwrap();
let b_map = b.unwrap();
let mut counter = 0;
for (key, _value) in a_map.entries() {
if b_map.get(key).is_some() {
counter += 1
}
}
counter
}
/// Does pairwise comparison of all architectures and saves their shared events to a file.
fn save_architecture_comparison(key_to_name: &ArchitectureMap, csv_result: &Path) {
let mut writer = csv::Writer::from_file(csv_result)
.expect(format!("Can't write {:?} file", csv_result).as_str());
writer
.encode(&[
"arch1",
"year1",
"arch2",
"year2",
"common events",
"arch1 events",
"arch2 events",
])
.expect(format!("Can't write {:?} header", csv_result).as_str());
for (key1, &(name1, year1, _)) in key_to_name.iter() {
for (key2, &(name2, year2, _)) in key_to_name.iter() {
let events1 = COUNTER_MAP.get(format!("{}", key1).as_str());
let events2 = COUNTER_MAP.get(format!("{}", key2).as_str());
writer
.encode(&[
name1,
year1,
name2,
year2,
common_event_names(events1, events2).to_string().as_str(),
events1.map(|c| c.len()).unwrap_or(0).to_string().as_str(),
events2.map(|c| c.len()).unwrap_or(0).to_string().as_str(),
])
.ok();
}
}
}
/// Computes the Levenshtein edit distance of two strings.
fn edit_distance(a: &str, b: &str) -> i32 {
let len_a = a.chars().count();
let len_b = b.chars().count();
let row: Vec<i32> = vec![0; len_b + 1];
let mut matrix: Vec<Vec<i32>> = vec![row; len_a + 1];
let chars_a: Vec<char> = a.to_lowercase().chars().collect();
let chars_b: Vec<char> = b.to_lowercase().chars().collect();
for i in 0..len_a {
matrix[i + 1][0] = (i + 1) as i32;
}
for i in 0..len_b {
matrix[0][i + 1] = (i + 1) as i32;
}
for i in 0..len_a {
for j in 0..len_b {
let ind: i32 = if chars_a[i] == chars_b[j] { 0 } else { 1 };
let min = vec![
matrix[i][j + 1] + 1,
matrix[i + 1][j] + 1,
matrix[i][j] + ind,
]
.into_iter()
.min()
.unwrap();
matrix[i + 1][j + 1] = if min == 0 { 0 } else { min };
}
}
matrix[len_a][len_b]
}
/// Computes the edit distance of the event description for common events shared in 'a' and 'b'.
fn common_event_desc_distance(
writer: &mut csv::Writer<File>,
a: Option<&'static EventMap>,
b: Option<&'static EventMap>,
uncore: bool,
) -> csv::Result<()> {
if a.is_none() || b.is_none() {
return Ok(());
}
let a_map = a.unwrap();
let b_map = b.unwrap();
for (key1, value1) in a_map.entries() {
match b_map.get(key1) {
Some(value2) => {
assert_eq!(value1.event_name, value2.event_name);
let ed =
edit_distance(value1.brief_description, value2.brief_description).to_string();
let uncore_str = if uncore { "true" } else { "false" };
writer.encode(&[
value1.event_name,
ed.as_str(),
uncore_str,
value1.brief_description,
value2.brief_description,
])?
}
None => {
// Ignore event names that are not shared in both architectures
}
}
}
Ok(())
}
/// Does a pairwise comparison of all architectures by computing edit distances of shared events.
fn save_edit_distances(key_to_name: &ArchitectureMap, output_dir: &Path) {
for (key1, &(name1, _, _)) in key_to_name.iter() {
for (key2, &(name2, _, _)) in key_to_name.iter() {
let mut csv_result = output_dir.to_path_buf();
csv_result.push(format!("editdist_{}-vs-{}.csv", name1, name2));
let mut writer = csv::Writer::from_file(csv_result.clone())
.expect(format!("Can't open {:?}", csv_result).as_str());
writer
.encode(&["event name", "edit distance", "uncore", "desc1", "desc2"])
.expect(format!("Can't write {:?} header", csv_result).as_str());
let events1 = COUNTER_MAP.get(format!("{}", key1).as_str());
let events2 = COUNTER_MAP.get(format!("{}", key2).as_str());
common_event_desc_distance(&mut writer, events1, events2, false).ok();
}
}
}
/// Dump information about performance events on your machine into the given directory.
fn save_event_descriptions(output_path: &Path) {
let events: &'static Map<&'static str, EventDescription<'static>> =
&x86::perfcnt::intel::events().expect("Can't get events for arch");
let pevents: Vec<PerfEvent> = events.into_iter().map(|e| PerfEvent(e.1)).collect();
let mut storage_location = PathBuf::from(output_path);
storage_location.push("ivytown_events.dat");
let mut wtr = csv::Writer::from_file(storage_location.clone())
.expect(format!("Can't open {:?}", storage_location).as_str());
let r = wtr.encode(("unit", "code", "mask", "event_name"));
assert!(r.is_ok());
for event in pevents.iter() {
//println!("{:?}", event.0.event_name);
let unit = event.unit().to_perf_prefix().unwrap_or("none");
match (&event.0.event_code, &event.0.umask) {
(&Tuple::One(e1), &Tuple::One(m1)) => {
wtr.encode(vec![
unit,
&format!("{}", e1),
&format!("{}", m1),
&String::from(event.0.event_name),
])
.ok();
}
(&Tuple::Two(e1, e2), &Tuple::Two(m1, m2)) => {
wtr.encode(vec![
unit,
&format!("{}", e1),
&format!("{}", m1),
&String::from(event.0.event_name),
])
.ok();
wtr.encode(vec![
unit,
&format!("{}", e2),
&format!("{}", m2),
&String::from(event.0.event_name),
])
.ok();
}
(&Tuple::Two(e1, e2), &Tuple::One(m1)) => {
wtr.encode(vec![
unit,
&format!("{}", e1),
&format!("{}", m1),
&String::from(event.0.event_name),
])
.ok();
wtr.encode(vec![
unit,
&format!("{}", e2),
&format!("{}", m1),
&String::from(event.0.event_name),
])
.ok();
}
_ => unreachable!(),
}
}
let r = wtr.flush();
assert!(r.is_ok());
}
/// Generate all the stats about Intel events and save them to a file.
pub fn stats(output_path: &Path) {
mkdir(output_path);
// TODO: Ideally this should come from x86 crate: x86data/perfmon_data/mapfile.csv
let mut key_to_name = HashMap::new();
key_to_name.insert("GenuineIntel-6-1C", ("Bonnell", "2008", "4"));
key_to_name.insert("GenuineIntel-6-1E", ("NehalemEP", "2009", "4"));
key_to_name.insert("GenuineIntel-6-2E", ("NehalemEX", "2010", "4"));
key_to_name.insert("GenuineIntel-6-25", ("WestmereEP-SP", "2010", "4"));
key_to_name.insert("GenuineIntel-6-2C", ("WestmereEP-DP", "2010", "4"));
key_to_name.insert("GenuineIntel-6-2F", ("WestmereEX", "2011", "4"));
key_to_name.insert("GenuineIntel-6-2D", ("Jaketown", "2011", "8"));
key_to_name.insert("GenuineIntel-6-2A", ("SandyBridge", "2011", "8"));
key_to_name.insert("GenuineIntel-6-3A", ("IvyBridge", "2012", "8"));
key_to_name.insert("GenuineIntel-6-37", ("Silvermont", "2013", "8"));
key_to_name.insert("GenuineIntel-6-3C", ("Haswell", "2013", "8"));
key_to_name.insert("GenuineIntel-6-3E", ("IvyBridgeEP", "2014", "8"));
key_to_name.insert("GenuineIntel-6-3F", ("HaswellX", "2014", "8"));
key_to_name.insert("GenuineIntel-6-3D", ("Broadwell", "2014", "8"));
key_to_name.insert("GenuineIntel-6-56", ("BroadwellDE", "2015", "8"));
key_to_name.insert("GenuineIntel-6-4E", ("Skylake", "2015", "8"));
key_to_name.insert("GenuineIntel-6-4F", ("BroadwellX", "2016", "8"));
key_to_name.insert("GenuineIntel-6-5C", ("Goldmont", "2016", "8"));
key_to_name.insert("GenuineIntel-6-57", ("KnightsLanding", "2016", "4"));
key_to_name.insert("GenuineIntel-6-55", ("SkylakeX", "2017", "8"));
let mut csv_result_file = output_path.to_path_buf();
csv_result_file.push("events.csv");
save_event_counts(&key_to_name, csv_result_file.as_path());
let mut csv_result_file = output_path.to_path_buf();
csv_result_file.push("architecture_comparison.csv");
save_architecture_comparison(&key_to_name, csv_result_file.as_path());
save_edit_distances(&key_to_name, output_path);
save_event_descriptions(output_path);
}
| 35.739884 | 98 | 0.527171 |
87d52a1f8405b0e4a916f49e230606d0b81c6c1b
| 10,150 |
// Copyright (c) Microsoft. All rights reserved.
#[derive(Debug)]
pub enum Error {
Internal(InternalError),
InvalidParameter(Option<(&'static str, Box<dyn std::error::Error + Send + Sync>)>),
Unauthorized(libc::uid_t, String),
}
impl Error {
pub(crate) fn invalid_parameter<E>(name: &'static str, err: E) -> Self
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Error::InvalidParameter(Some((name, err.into())))
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Internal(_) => f.write_str("internal error"),
Error::InvalidParameter(Some((name, _))) => {
write!(f, "parameter {:?} has an invalid value", name)
}
Error::InvalidParameter(None) => f.write_str("a parameter has an invalid value"),
Error::Unauthorized(user, id) => {
write!(
f,
"user {} is not authorized to access the key {}",
user, id
)
}
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
#[allow(clippy::match_same_arms)]
match self {
Error::Internal(err) => Some(err),
Error::InvalidParameter(Some((_, err))) => Some(&**err),
Error::InvalidParameter(None) => None,
Error::Unauthorized(_, _) => None,
}
}
}
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub enum InternalError {
CreateKeyIfNotExistsGenerate(crate::keys::CreateKeyIfNotExistsError),
CreateKeyIfNotExistsImport(crate::keys::ImportKeyError),
CreateKeyPairIfNotExists(crate::keys::CreateKeyPairIfNotExistsError),
GetKeyPairPublicParameter(crate::keys::GetKeyPairPublicParameterError),
Decrypt(crate::keys::DecryptError),
DeleteKey(crate::keys::DeleteKeyError),
DeleteKeyPair(crate::keys::DeleteKeyPairError),
DeriveKey(crate::keys::DeriveKeyError),
Encrypt(crate::keys::EncryptError),
GenerateNonce(openssl::error::ErrorStack),
LoadKey(crate::keys::LoadKeyError),
LoadKeyPair(crate::keys::LoadKeyPairError),
LoadLibrary(crate::keys::LoadLibraryError),
ReadConfig(Box<dyn std::error::Error + Send + Sync>),
SetLibraryParameter(crate::keys::SetLibraryParameterError),
Sign(crate::keys::SignError),
Verify(crate::keys::VerifyError),
}
impl std::fmt::Display for InternalError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
InternalError::CreateKeyIfNotExistsGenerate(_) => f.write_str("could not generate key"),
InternalError::CreateKeyIfNotExistsImport(_) => f.write_str("could not import key"),
InternalError::CreateKeyPairIfNotExists(_) => f.write_str("could not create key pair"),
InternalError::Decrypt(_) => f.write_str("could not decrypt"),
InternalError::DeleteKey(_) => f.write_str("could not delete key"),
InternalError::DeleteKeyPair(_) => f.write_str("could not delete key pair"),
InternalError::DeriveKey(_) => f.write_str("could not derive key"),
InternalError::Encrypt(_) => f.write_str("could not encrypt"),
InternalError::GetKeyPairPublicParameter(_) => {
f.write_str("could not get key pair parameter")
}
InternalError::GenerateNonce(_) => f.write_str("could not generate nonce"),
InternalError::LoadKey(_) => f.write_str("could not load key"),
InternalError::LoadKeyPair(_) => f.write_str("could not load key pair"),
InternalError::LoadLibrary(_) => f.write_str("could not load libaziot-keys"),
InternalError::ReadConfig(_) => f.write_str("could not read config"),
InternalError::SetLibraryParameter(_) => {
f.write_str("could not set parameter on libaziot-keys")
}
InternalError::Sign(_) => f.write_str("could not sign"),
InternalError::Verify(_) => f.write_str("could not verify"),
}
}
}
impl std::error::Error for InternalError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
InternalError::CreateKeyIfNotExistsGenerate(err) => Some(err),
InternalError::CreateKeyIfNotExistsImport(err) => Some(err),
InternalError::CreateKeyPairIfNotExists(err) => Some(err),
InternalError::Decrypt(err) => Some(err),
InternalError::DeleteKey(err) => Some(err),
InternalError::DeleteKeyPair(err) => Some(err),
InternalError::DeriveKey(err) => Some(err),
InternalError::Encrypt(err) => Some(err),
InternalError::GetKeyPairPublicParameter(err) => Some(err),
InternalError::GenerateNonce(err) => Some(err),
InternalError::LoadKey(err) => Some(err),
InternalError::LoadKeyPair(err) => Some(err),
InternalError::LoadLibrary(err) => Some(err),
InternalError::ReadConfig(err) => Some(&**err),
InternalError::SetLibraryParameter(err) => Some(err),
InternalError::Sign(err) => Some(err),
InternalError::Verify(err) => Some(err),
}
}
}
impl From<crate::keys::LoadLibraryError> for Error {
fn from(err: crate::keys::LoadLibraryError) -> Self {
Error::Internal(InternalError::LoadLibrary(err))
}
}
impl From<crate::keys::SetLibraryParameterError> for Error {
fn from(err: crate::keys::SetLibraryParameterError) -> Self {
Error::Internal(InternalError::SetLibraryParameter(err))
}
}
impl From<crate::keys::CreateKeyPairIfNotExistsError> for Error {
fn from(err: crate::keys::CreateKeyPairIfNotExistsError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::CreateKeyPairIfNotExists(err)),
}
}
}
impl From<crate::keys::LoadKeyPairError> for Error {
fn from(err: crate::keys::LoadKeyPairError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::LoadKeyPair(err)),
}
}
}
impl From<crate::keys::GetKeyPairPublicParameterError> for Error {
fn from(err: crate::keys::GetKeyPairPublicParameterError) -> Self {
match err {
crate::keys::GetKeyPairPublicParameterError::Api {
err:
crate::keys::KeysRawError(crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER),
} => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::GetKeyPairPublicParameter(err)),
}
}
}
impl From<crate::keys::DeleteKeyPairError> for Error {
fn from(err: crate::keys::DeleteKeyPairError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::DeleteKeyPair(err)),
}
}
}
impl From<crate::keys::CreateKeyIfNotExistsError> for Error {
fn from(err: crate::keys::CreateKeyIfNotExistsError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::CreateKeyIfNotExistsGenerate(err)),
}
}
}
impl From<crate::keys::LoadKeyError> for Error {
fn from(err: crate::keys::LoadKeyError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::LoadKey(err)),
}
}
}
impl From<crate::keys::ImportKeyError> for Error {
fn from(err: crate::keys::ImportKeyError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::CreateKeyIfNotExistsImport(err)),
}
}
}
impl From<crate::keys::DeleteKeyError> for Error {
fn from(err: crate::keys::DeleteKeyError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::DeleteKey(err)),
}
}
}
impl From<crate::keys::DeriveKeyError> for Error {
fn from(err: crate::keys::DeriveKeyError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::DeriveKey(err)),
}
}
}
impl From<crate::keys::SignError> for Error {
fn from(err: crate::keys::SignError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::Sign(err)),
}
}
}
impl From<crate::keys::VerifyError> for Error {
fn from(err: crate::keys::VerifyError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::Verify(err)),
}
}
}
impl From<crate::keys::EncryptError> for Error {
fn from(err: crate::keys::EncryptError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::Encrypt(err)),
}
}
}
impl From<crate::keys::DecryptError> for Error {
fn from(err: crate::keys::DecryptError) -> Self {
match err.err.0 {
crate::keys::sys::AZIOT_KEYS_RC_ERR_INVALID_PARAMETER => Error::InvalidParameter(None),
_ => Error::Internal(InternalError::Decrypt(err)),
}
}
}
| 39.648438 | 101 | 0.622857 |
2f38246b98d78684f8c415f682d6d8915326a0b9
| 18,532 |
pub mod addon_transport;
pub mod state_types;
pub mod types;
#[cfg(test)]
mod tests {
use crate::addon_transport::*;
use crate::state_types::*;
use crate::types::addons::{Descriptor, ResourceRef, ResourceRequest, ResourceResponse};
use crate::types::MetaPreview;
use futures::future::lazy;
use futures::{future, Future};
use serde::de::DeserializeOwned;
use serde::Serialize;
use tokio::executor::current_thread::spawn;
use tokio::runtime::current_thread::run;
#[test]
fn transport_manifests() {
run(lazy(|| {
let cinemeta_url = "https://v3-cinemeta.strem.io/manifest.json";
let legacy_url = "https://opensubtitles.strem.io/stremioget/stremio/v1";
let fut1 = AddonHTTPTransport::<Env>::from_url(&cinemeta_url)
.manifest()
.then(|res| {
if let Err(e) = res {
panic!("failed getting cinemeta manifest {:?}", e);
}
future::ok(())
});
let fut2 = AddonHTTPTransport::<Env>::from_url(&legacy_url)
.manifest()
.then(|res| {
if let Err(e) = res {
panic!("failed getting legacy manifest {:?}", e);
}
future::ok(())
});
fut1.join(fut2).map(|(_, _)| ())
}));
}
#[test]
fn get_videos() {
run(lazy(|| {
let transport_url = "https://v3-cinemeta.strem.io/manifest.json";
AddonHTTPTransport::<Env>::from_url(&transport_url)
.get(&ResourceRef::without_extra("meta", "series", "tt0386676"))
.then(|res| {
match res {
Err(e) => panic!("failed getting metadata {:?}", e),
Ok(ResourceResponse::Meta { meta }) => {
//dbg!(&meta.videos);
assert!(meta.videos.len() > 0, "has videos")
}
_ => panic!("unexpected response"),
};
future::ok(())
})
}));
}
#[test]
fn addon_collection() {
run(lazy(|| {
let collection_url = "https://api.strem.io/addonscollection.json";
let req = Request::get(collection_url)
.body(())
.expect("builder cannot fail");
Env::fetch_serde::<_, Vec<Descriptor>>(req).then(|res| {
match res {
Err(e) => panic!("failed getting addon collection {:?}", e),
Ok(collection) => assert!(collection.len() > 0, "has addons"),
};
future::ok(())
})
}));
}
#[test]
fn sample_storage() {
let key = "foo".to_owned();
let value = "fooobar".to_owned();
// Notihng in the beginning
assert!(Env::get_storage::<String>(&key).wait().unwrap().is_none());
// Then set and read
// with RwLock and BTreeMap, set_storage takes 73993042ns for 10000 iterations (or 74ms)
// get_storage takes 42076632 (or 42ms) for 10000 iterations
assert_eq!(Env::set_storage(&key, Some(&value)).wait().unwrap(), ());
assert_eq!(
Env::get_storage::<String>(&key).wait().unwrap(),
Some(value)
);
}
#[test]
fn stremio_derive() {
// Implement some dummy Ctx and contents
struct Ctx {};
impl Update for Ctx {
fn update(&mut self, _: &Msg) -> Effects {
dummy_effect()
}
}
struct Content {};
impl UpdateWithCtx<Ctx> for Content {
fn update(&mut self, _: &Ctx, _: &Msg) -> Effects {
dummy_effect()
}
}
use stremio_derive::Model;
#[derive(Model)]
struct Model {
pub ctx: Ctx,
pub one: Content,
pub two: Content,
}
let mut m = Model {
ctx: Ctx {},
one: Content {},
two: Content {},
};
let fx = m.update(&Msg::Action(Action::LoadCtx));
assert!(fx.has_changed, "has changed");
assert_eq!(fx.effects.len(), 3, "proper number of effects");
}
fn dummy_effect() -> Effects {
Effects::one(Box::new(future::ok(Msg::Action(Action::LoadCtx))))
}
// Testing the CatalogsGrouped model
// and the Runtime type
#[test]
fn catalog_grouped() {
use stremio_derive::Model;
#[derive(Model, Debug, Default)]
struct Model {
ctx: Ctx<Env>,
catalogs: CatalogGrouped,
}
let app = Model::default();
let (runtime, _) = Runtime::<Env, Model>::new(app, 1000);
// Run a single dispatch of a Load msg
let msg = Msg::Action(Action::Load(ActionLoad::CatalogGrouped { extra: vec![] }));
run(runtime.dispatch(&msg));
// since this is after the .run() has ended, this means all async effects
// have processed
{
let state = &runtime.app.read().unwrap().catalogs;
assert_eq!(state.groups.len(), 7, "groups is the right length");
for g in state.groups.iter() {
assert!(
match g.content {
Loadable::Ready(_) => true,
Loadable::Err(_) => true,
_ => false,
},
"group is Ready or Err"
);
}
}
// Now try the same, but with Search
let extra = vec![("search".to_owned(), "grand tour".to_owned())];
let msg = Msg::Action(Action::Load(ActionLoad::CatalogGrouped { extra }));
run(runtime.dispatch(&msg));
assert_eq!(
runtime.app.read().unwrap().catalogs.groups.len(),
5,
"groups is the right length when searching"
);
}
#[test]
fn catalog_filtered() {
use stremio_derive::Model;
#[derive(Model, Debug, Default)]
struct Model {
ctx: Ctx<Env>,
catalogs: CatalogFiltered<MetaPreview>,
}
let app = Model::default();
let (runtime, _) = Runtime::<Env, Model>::new(app, 1000);
let req = ResourceRequest {
base: "https://v3-cinemeta.strem.io/manifest.json".to_owned(),
path: ResourceRef::without_extra("catalog", "movie", "top"),
};
let action = Action::Load(ActionLoad::CatalogFiltered(req.to_owned()));
run(runtime.dispatch_with(|model| model.catalogs.update(&model.ctx, &action.into())));
// Clone the state so that we don't keep a lock on .app
let state = runtime.app.read().unwrap().catalogs.to_owned();
assert!(state.types[0].is_selected, "first type is selected");
assert!(state.catalogs[0].is_selected, "first catalog is selected");
assert_eq!(state.types[0].type_name, "movie", "first type is movie");
assert_eq!(state.types[1].type_name, "series", "second type is series");
assert!(state.catalogs.len() > 3, "has catalogs");
assert_eq!(state.selected, Some(req), "selected is right");
match &state.content {
Loadable::Ready(x) => assert_eq!(x.len(), 100, "right length of items"),
x => panic!("item_pages[0] is not Ready, but instead: {:?}", x),
}
// Verify that pagination works
let load_next = state
.load_next
.as_ref()
.expect("there should be a next page")
.to_owned();
let action = Action::Load(ActionLoad::CatalogFiltered(load_next));
run(runtime.dispatch(&action.into()));
let state = &runtime.app.read().unwrap().catalogs.to_owned();
assert!(state.types[0].is_selected, "first type is selected");
assert!(
state.catalogs[0].is_selected,
"first catalog is still selected"
);
assert_eq!(
state
.selected
.as_ref()
.expect("there must be .selected")
.path
.get_extra_first_val("skip"),
Some("100")
);
assert_eq!(
state
.load_next
.as_ref()
.expect("there must be .load_next")
.path
.get_extra_first_val("skip"),
Some("200")
);
assert_eq!(
state
.load_prev
.as_ref()
.expect("there must be .load_prev")
.path
.get_extra_first_val("skip"),
Some("0")
);
//dbg!(&state);
let year_catalog = state
.catalogs
.iter()
.find(|c| c.name == "By year")
.expect("could not find year catalog");
let action = Action::Load(ActionLoad::CatalogFiltered(year_catalog.load.to_owned()));
run(runtime.dispatch(&action.into()));
let state = &runtime.app.read().unwrap().catalogs;
let selected = state.selected.as_ref().expect("should have selected");
assert_eq!(
selected.path.get_extra_first_val("skip"),
None,
"first page"
);
assert_eq!(selected.path.id, "year", "year catalog is loaded");
// The year catalog is not seekable
assert_eq!(state.load_prev, None);
assert_eq!(state.load_next, None);
}
#[test]
fn streams() {
use stremio_derive::Model;
#[derive(Model, Debug, Default)]
struct Model {
ctx: Ctx<Env>,
streams: Streams,
}
let app = Model::default();
let (runtime, _) = Runtime::<Env, Model>::new(app, 1000);
// If we login here with some dummy account, we can use this pretty nicely
//let action = Action::UserOp(ActionUser::Login { email, password });
//run(runtime.dispatch(&action.into()));
// @TODO install some addons that provide streams
let action = Action::Load(ActionLoad::Streams {
type_name: "series".to_string(),
id: "tt0773262:6:1".to_string(),
});
run(runtime.dispatch(&action.into()));
let state = &runtime.app.read().unwrap().streams;
assert_eq!(state.groups.len(), 2, "2 groups");
}
#[test]
fn ctx_and_lib() {
use stremio_derive::Model;
#[derive(Model, Debug, Default)]
struct Model {
ctx: Ctx<Env>,
lib_recent: LibRecent,
notifs: Notifications,
}
let (runtime, _) = Runtime::<Env, Model>::new(Model::default(), 1000);
// Log into a user, check if library synced correctly
// We are always support to start with LoadCtx, even though it is not needed here
run(runtime.dispatch(&Msg::Action(Action::LoadCtx)));
// if this user gets deleted, the test will fail
// @TODO register a new user instead
let login_msg: Msg = Action::UserOp(ActionUser::Login {
email: "[email protected]".into(),
password: "ctxandlib".into(),
})
.into();
run(runtime.dispatch(&login_msg));
// @TODO test if the addon collection is pulled
let model = &runtime.app.read().unwrap();
let first_content = model.ctx.content.to_owned();
let first_lib = if let LibraryLoadable::Ready(l) = &model.ctx.library {
assert!(!l.items.is_empty(), "library has items");
// LibRecent is "continue watching"
assert!(!model.lib_recent.recent.is_empty(), "has recent items");
l.to_owned()
} else {
panic!("library must be Ready")
};
// New runtime, just LoadCtx, to see if the ctx was persisted
let (runtime, _) = Runtime::<Env, Model>::new(Model::default(), 1000);
assert_eq!(runtime.app.read().unwrap().ctx.is_loaded, false);
run(runtime.dispatch(&Msg::Action(Action::LoadCtx)));
{
let ctx = &runtime.app.read().unwrap().ctx;
assert_eq!(&first_content, &ctx.content, "content is the same");
if let LibraryLoadable::Ready(l) = &ctx.library {
assert_eq!(&first_lib, l, "loaded lib is same as synced");
} else {
panic!("library must be Ready")
}
assert!(ctx.is_loaded);
}
// Update notifications
{
// ¯\_(ツ)_/¯
// temporary hack (really) until last-videos catalog lands in upstream cinemeta
// and gets updated for our user
let addons: Vec<Descriptor> =
serde_json::from_slice(include_bytes!("../stremio-official-addons/index.json"))
.expect("official addons JSON parse");
runtime.app.write().unwrap().ctx.content.addons[0] = addons[0].clone();
// we did unspeakable things, now dispatch the load action
run(runtime.dispatch(&Action::Load(ActionLoad::Notifications).into()));
// ...
let model = &runtime.app.read().unwrap();
assert_eq!(model.notifs.groups.len(), 1);
let meta_items = match &model.notifs.groups[0].content {
Loadable::Ready(x) => x,
x => panic!("notifs group not ready, but instead: {:?}", x),
};
assert!(meta_items.len() > 1, "should have loaded multiple items");
// No notifications, cause neither LibItem has .last_vid_released set
assert!(meta_items.iter().all(|x| x.videos.len() == 0));
}
// Logout and expect everything to be reset
let logout_action = Action::UserOp(ActionUser::Logout);
run(runtime.dispatch(&logout_action.into()));
{
let model = &runtime.app.read().unwrap();
assert!(model.ctx.content.auth.is_none(), "logged out");
assert!(model.ctx.content.addons.len() > 0, "has addons");
if let LibraryLoadable::Ready(l) = &model.ctx.library {
assert!(l.items.is_empty(), "library must be empty");
assert!(model.lib_recent.recent.is_empty(), "is empty");
} else {
panic!("library must be Ready")
}
}
// Addon updating in anon mode works
let zero_ver = semver::Version::new(0, 0, 0);
{
let addons = &mut runtime.app.write().unwrap().ctx.content.addons;
addons[0].manifest.version = zero_ver.clone();
addons[0].flags.extra.insert("foo".into(), "bar".into());
assert_eq!(&addons[0].manifest.version, &zero_ver);
}
let update_action = Action::UserOp(ActionUser::PullAndUpdateAddons);
run(runtime.dispatch(&update_action.into()));
{
let model = &runtime.app.read().unwrap();
let first_addon = &model.ctx.content.addons[0];
let expected_val = serde_json::Value::String("bar".into());
assert_ne!(&first_addon.manifest.version, &zero_ver);
assert_eq!(first_addon.flags.extra.get("foo"), Some(&expected_val));
}
// we will now add an item for the anon user
let item = first_lib.items.values().next().unwrap().to_owned();
run(runtime.dispatch(&Msg::Action(Action::UserOp(ActionUser::LibUpdate(item)))));
// take a copy now so we can compare later
let anon_lib = runtime.app.read().unwrap().ctx.library.to_owned();
// we will load again to make sure it's persisted
let (runtime, _) = Runtime::<Env, Model>::new(Model::default(), 1000);
run(runtime.dispatch(&Msg::Action(Action::LoadCtx)));
{
let ctx = &runtime.app.read().unwrap().ctx;
assert_eq!(anon_lib, ctx.library);
if let LibraryLoadable::Ready(l) = &ctx.library {
assert_eq!(l.items.len(), 1, "library has 1 item");
} else {
panic!("library must be Ready")
}
}
}
// Storage implementation
// Uses reqwest (asynchronously) for fetch, and a BTreeMap storage
use lazy_static::*;
use std::collections::BTreeMap;
use std::sync::RwLock;
lazy_static! {
static ref STORAGE: RwLock<BTreeMap<String, String>> = { Default::default() };
}
struct Env {}
impl Environment for Env {
fn fetch_serde<IN, OUT>(in_req: Request<IN>) -> EnvFuture<OUT>
where
IN: 'static + Serialize,
OUT: 'static + DeserializeOwned,
{
let (parts, body) = in_req.into_parts();
let method = reqwest::Method::from_bytes(parts.method.as_str().as_bytes())
.expect("method is not valid for reqwest");
let mut req = reqwest::r#async::Client::new().request(method, &parts.uri.to_string());
// NOTE: both might be HeaderMap, so maybe there's a better way?
for (k, v) in parts.headers.iter() {
req = req.header(k.as_str(), v.as_ref());
}
// @TODO add content-type application/json
// @TODO: if the response code is not 200, return an error related to that
req = req.json(&body);
let fut = req
.send()
.and_then(|mut res: reqwest::r#async::Response| res.json::<OUT>())
.map_err(|e| e.into());
Box::new(fut)
}
fn exec(fut: Box<dyn Future<Item = (), Error = ()>>) {
spawn(fut);
}
fn get_storage<T: 'static + DeserializeOwned>(key: &str) -> EnvFuture<Option<T>> {
Box::new(future::ok(
STORAGE
.read()
.unwrap()
.get(key)
.map(|v| serde_json::from_str(&v).unwrap()),
))
}
fn set_storage<T: Serialize>(key: &str, value: Option<&T>) -> EnvFuture<()> {
let mut storage = STORAGE.write().unwrap();
match value {
Some(v) => storage.insert(key.to_string(), serde_json::to_string(v).unwrap()),
None => storage.remove(key),
};
Box::new(future::ok(()))
}
}
}
| 38.769874 | 98 | 0.522987 |
62cd9c64a4a7c8205af4600d1fc14fca32a1fb00
| 85,800 |
use crate::check::FnCtxt;
use rustc_ast as ast;
use rustc_data_structures::fx::FxHashMap;
use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def::{CtorKind, DefKind, Res};
use rustc_hir::pat_util::EnumerateAndAdjustIterator;
use rustc_hir::{HirId, Pat, PatKind};
use rustc_infer::infer;
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use rustc_middle::ty::subst::GenericArg;
use rustc_middle::ty::{self, Adt, BindingMode, Ty, TypeFoldable};
use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
use rustc_span::hygiene::DesugaringKind;
use rustc_span::lev_distance::find_best_match_for_name;
use rustc_span::source_map::{Span, Spanned};
use rustc_span::symbol::{sym, Ident};
use rustc_span::{BytePos, MultiSpan, DUMMY_SP};
use rustc_trait_selection::autoderef::Autoderef;
use rustc_trait_selection::traits::{ObligationCause, Pattern};
use ty::VariantDef;
use std::cmp;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use super::report_unexpected_variant_res;
const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\
This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \
pattern. Every trait defines a type, but because the size of trait implementors isn't fixed, \
this type has no compile-time size. Therefore, all accesses to trait types must be through \
pointers. If you encounter this error you should try to avoid dereferencing the pointer.
You can read more about trait objects in the Trait Objects section of the Reference: \
https://doc.rust-lang.org/reference/types.html#trait-objects";
/// Information about the expected type at the top level of type checking a pattern.
///
/// **NOTE:** This is only for use by diagnostics. Do NOT use for type checking logic!
#[derive(Copy, Clone)]
struct TopInfo<'tcx> {
/// The `expected` type at the top level of type checking a pattern.
expected: Ty<'tcx>,
/// Was the origin of the `span` from a scrutinee expression?
///
/// Otherwise there is no scrutinee and it could be e.g. from the type of a formal parameter.
origin_expr: bool,
/// The span giving rise to the `expected` type, if one could be provided.
///
/// If `origin_expr` is `true`, then this is the span of the scrutinee as in:
///
/// - `match scrutinee { ... }`
/// - `let _ = scrutinee;`
///
/// This is used to point to add context in type errors.
/// In the following example, `span` corresponds to the `a + b` expression:
///
/// ```text
/// error[E0308]: mismatched types
/// --> src/main.rs:L:C
/// |
/// L | let temp: usize = match a + b {
/// | ----- this expression has type `usize`
/// L | Ok(num) => num,
/// | ^^^^^^^ expected `usize`, found enum `std::result::Result`
/// |
/// = note: expected type `usize`
/// found type `std::result::Result<_, _>`
/// ```
span: Option<Span>,
/// This refers to the parent pattern. Used to provide extra diagnostic information on errors.
/// ```text
/// error[E0308]: mismatched types
/// --> $DIR/const-in-struct-pat.rs:8:17
/// |
/// L | struct f;
/// | --------- unit struct defined here
/// ...
/// L | let Thing { f } = t;
/// | ^
/// | |
/// | expected struct `std::string::String`, found struct `f`
/// | `f` is interpreted as a unit struct, not a new binding
/// | help: bind the struct field to a different name instead: `f: other_f`
/// ```
parent_pat: Option<&'tcx Pat<'tcx>>,
}
impl<'tcx> FnCtxt<'_, 'tcx> {
fn pattern_cause(&self, ti: TopInfo<'tcx>, cause_span: Span) -> ObligationCause<'tcx> {
let code = Pattern { span: ti.span, root_ty: ti.expected, origin_expr: ti.origin_expr };
self.cause(cause_span, code)
}
fn demand_eqtype_pat_diag(
&self,
cause_span: Span,
expected: Ty<'tcx>,
actual: Ty<'tcx>,
ti: TopInfo<'tcx>,
) -> Option<DiagnosticBuilder<'tcx>> {
self.demand_eqtype_with_origin(&self.pattern_cause(ti, cause_span), expected, actual)
}
fn demand_eqtype_pat(
&self,
cause_span: Span,
expected: Ty<'tcx>,
actual: Ty<'tcx>,
ti: TopInfo<'tcx>,
) {
if let Some(mut err) = self.demand_eqtype_pat_diag(cause_span, expected, actual, ti) {
err.emit();
}
}
}
const INITIAL_BM: BindingMode = BindingMode::BindByValue(hir::Mutability::Not);
/// Mode for adjusting the expected type and binding mode.
enum AdjustMode {
/// Peel off all immediate reference types.
Peel,
/// Reset binding mode to the initial mode.
Reset,
/// Pass on the input binding mode and expected type.
Pass,
}
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Type check the given top level pattern against the `expected` type.
///
/// If a `Some(span)` is provided and `origin_expr` holds,
/// then the `span` represents the scrutinee's span.
/// The scrutinee is found in e.g. `match scrutinee { ... }` and `let pat = scrutinee;`.
///
/// Otherwise, `Some(span)` represents the span of a type expression
/// which originated the `expected` type.
pub fn check_pat_top(
&self,
pat: &'tcx Pat<'tcx>,
expected: Ty<'tcx>,
span: Option<Span>,
origin_expr: bool,
) {
let info = TopInfo { expected, origin_expr, span, parent_pat: None };
self.check_pat(pat, expected, INITIAL_BM, info);
}
/// Type check the given `pat` against the `expected` type
/// with the provided `def_bm` (default binding mode).
///
/// Outside of this module, `check_pat_top` should always be used.
/// Conversely, inside this module, `check_pat_top` should never be used.
#[instrument(level = "debug", skip(self, ti))]
fn check_pat(
&self,
pat: &'tcx Pat<'tcx>,
expected: Ty<'tcx>,
def_bm: BindingMode,
ti: TopInfo<'tcx>,
) {
let path_res = match &pat.kind {
PatKind::Path(qpath) => {
Some(self.resolve_ty_and_res_fully_qualified_call(qpath, pat.hir_id, pat.span))
}
_ => None,
};
let adjust_mode = self.calc_adjust_mode(pat, path_res.map(|(res, ..)| res));
let (expected, def_bm) = self.calc_default_binding_mode(pat, expected, def_bm, adjust_mode);
let ty = match pat.kind {
PatKind::Wild => expected,
PatKind::Lit(lt) => self.check_pat_lit(pat.span, lt, expected, ti),
PatKind::Range(lhs, rhs, _) => self.check_pat_range(pat.span, lhs, rhs, expected, ti),
PatKind::Binding(ba, var_id, _, sub) => {
self.check_pat_ident(pat, ba, var_id, sub, expected, def_bm, ti)
}
PatKind::TupleStruct(ref qpath, subpats, ddpos) => {
self.check_pat_tuple_struct(pat, qpath, subpats, ddpos, expected, def_bm, ti)
}
PatKind::Path(_) => self.check_pat_path(pat, path_res.unwrap(), expected, ti),
PatKind::Struct(ref qpath, fields, has_rest_pat) => {
self.check_pat_struct(pat, qpath, fields, has_rest_pat, expected, def_bm, ti)
}
PatKind::Or(pats) => {
let parent_pat = Some(pat);
for pat in pats {
self.check_pat(pat, expected, def_bm, TopInfo { parent_pat, ..ti });
}
expected
}
PatKind::Tuple(elements, ddpos) => {
self.check_pat_tuple(pat.span, elements, ddpos, expected, def_bm, ti)
}
PatKind::Box(inner) => self.check_pat_box(pat.span, inner, expected, def_bm, ti),
PatKind::Ref(inner, mutbl) => {
self.check_pat_ref(pat, inner, mutbl, expected, def_bm, ti)
}
PatKind::Slice(before, slice, after) => {
self.check_pat_slice(pat.span, before, slice, after, expected, def_bm, ti)
}
};
self.write_ty(pat.hir_id, ty);
// (note_1): In most of the cases where (note_1) is referenced
// (literals and constants being the exception), we relate types
// using strict equality, even though subtyping would be sufficient.
// There are a few reasons for this, some of which are fairly subtle
// and which cost me (nmatsakis) an hour or two debugging to remember,
// so I thought I'd write them down this time.
//
// 1. There is no loss of expressiveness here, though it does
// cause some inconvenience. What we are saying is that the type
// of `x` becomes *exactly* what is expected. This can cause unnecessary
// errors in some cases, such as this one:
//
// ```
// fn foo<'x>(x: &'x i32) {
// let a = 1;
// let mut z = x;
// z = &a;
// }
// ```
//
// The reason we might get an error is that `z` might be
// assigned a type like `&'x i32`, and then we would have
// a problem when we try to assign `&a` to `z`, because
// the lifetime of `&a` (i.e., the enclosing block) is
// shorter than `'x`.
//
// HOWEVER, this code works fine. The reason is that the
// expected type here is whatever type the user wrote, not
// the initializer's type. In this case the user wrote
// nothing, so we are going to create a type variable `Z`.
// Then we will assign the type of the initializer (`&'x i32`)
// as a subtype of `Z`: `&'x i32 <: Z`. And hence we
// will instantiate `Z` as a type `&'0 i32` where `'0` is
// a fresh region variable, with the constraint that `'x : '0`.
// So basically we're all set.
//
// Note that there are two tests to check that this remains true
// (`regions-reassign-{match,let}-bound-pointer.rs`).
//
// 2. Things go horribly wrong if we use subtype. The reason for
// THIS is a fairly subtle case involving bound regions. See the
// `givens` field in `region_constraints`, as well as the test
// `regions-relate-bound-regions-on-closures-to-inference-variables.rs`,
// for details. Short version is that we must sometimes detect
// relationships between specific region variables and regions
// bound in a closure signature, and that detection gets thrown
// off when we substitute fresh region variables here to enable
// subtyping.
}
/// Compute the new expected type and default binding mode from the old ones
/// as well as the pattern form we are currently checking.
fn calc_default_binding_mode(
&self,
pat: &'tcx Pat<'tcx>,
expected: Ty<'tcx>,
def_bm: BindingMode,
adjust_mode: AdjustMode,
) -> (Ty<'tcx>, BindingMode) {
match adjust_mode {
AdjustMode::Pass => (expected, def_bm),
AdjustMode::Reset => (expected, INITIAL_BM),
AdjustMode::Peel => self.peel_off_references(pat, expected, def_bm),
}
}
/// How should the binding mode and expected type be adjusted?
///
/// When the pattern is a path pattern, `opt_path_res` must be `Some(res)`.
fn calc_adjust_mode(&self, pat: &'tcx Pat<'tcx>, opt_path_res: Option<Res>) -> AdjustMode {
// When we perform destructuring assignment, we disable default match bindings, which are
// unintuitive in this context.
if !pat.default_binding_modes {
return AdjustMode::Reset;
}
match &pat.kind {
// Type checking these product-like types successfully always require
// that the expected type be of those types and not reference types.
PatKind::Struct(..)
| PatKind::TupleStruct(..)
| PatKind::Tuple(..)
| PatKind::Box(_)
| PatKind::Range(..)
| PatKind::Slice(..) => AdjustMode::Peel,
// String and byte-string literals result in types `&str` and `&[u8]` respectively.
// All other literals result in non-reference types.
// As a result, we allow `if let 0 = &&0 {}` but not `if let "foo" = &&"foo {}`.
//
// Call `resolve_vars_if_possible` here for inline const blocks.
PatKind::Lit(lt) => match self.resolve_vars_if_possible(self.check_expr(lt)).kind() {
ty::Ref(..) => AdjustMode::Pass,
_ => AdjustMode::Peel,
},
PatKind::Path(_) => match opt_path_res.unwrap() {
// These constants can be of a reference type, e.g. `const X: &u8 = &0;`.
// Peeling the reference types too early will cause type checking failures.
// Although it would be possible to *also* peel the types of the constants too.
Res::Def(DefKind::Const | DefKind::AssocConst, _) => AdjustMode::Pass,
// In the `ValueNS`, we have `SelfCtor(..) | Ctor(_, Const), _)` remaining which
// could successfully compile. The former being `Self` requires a unit struct.
// In either case, and unlike constants, the pattern itself cannot be
// a reference type wherefore peeling doesn't give up any expressivity.
_ => AdjustMode::Peel,
},
// When encountering a `& mut? pat` pattern, reset to "by value".
// This is so that `x` and `y` here are by value, as they appear to be:
//
// ```
// match &(&22, &44) {
// (&x, &y) => ...
// }
// ```
//
// See issue #46688.
PatKind::Ref(..) => AdjustMode::Reset,
// A `_` pattern works with any expected type, so there's no need to do anything.
PatKind::Wild
// Bindings also work with whatever the expected type is,
// and moreover if we peel references off, that will give us the wrong binding type.
// Also, we can have a subpattern `binding @ pat`.
// Each side of the `@` should be treated independently (like with OR-patterns).
| PatKind::Binding(..)
// An OR-pattern just propagates to each individual alternative.
// This is maximally flexible, allowing e.g., `Some(mut x) | &Some(mut x)`.
// In that example, `Some(mut x)` results in `Peel` whereas `&Some(mut x)` in `Reset`.
| PatKind::Or(_) => AdjustMode::Pass,
}
}
/// Peel off as many immediately nested `& mut?` from the expected type as possible
/// and return the new expected type and binding default binding mode.
/// The adjustments vector, if non-empty is stored in a table.
fn peel_off_references(
&self,
pat: &'tcx Pat<'tcx>,
expected: Ty<'tcx>,
mut def_bm: BindingMode,
) -> (Ty<'tcx>, BindingMode) {
let mut expected = self.resolve_vars_with_obligations(expected);
// Peel off as many `&` or `&mut` from the scrutinee type as possible. For example,
// for `match &&&mut Some(5)` the loop runs three times, aborting when it reaches
// the `Some(5)` which is not of type Ref.
//
// For each ampersand peeled off, update the binding mode and push the original
// type into the adjustments vector.
//
// See the examples in `ui/match-defbm*.rs`.
let mut pat_adjustments = vec![];
while let ty::Ref(_, inner_ty, inner_mutability) = *expected.kind() {
debug!("inspecting {:?}", expected);
debug!("current discriminant is Ref, inserting implicit deref");
// Preserve the reference type. We'll need it later during THIR lowering.
pat_adjustments.push(expected);
expected = inner_ty;
def_bm = ty::BindByReference(match def_bm {
// If default binding mode is by value, make it `ref` or `ref mut`
// (depending on whether we observe `&` or `&mut`).
ty::BindByValue(_) |
// When `ref mut`, stay a `ref mut` (on `&mut`) or downgrade to `ref` (on `&`).
ty::BindByReference(hir::Mutability::Mut) => inner_mutability,
// Once a `ref`, always a `ref`.
// This is because a `& &mut` cannot mutate the underlying value.
ty::BindByReference(m @ hir::Mutability::Not) => m,
});
}
if !pat_adjustments.is_empty() {
debug!("default binding mode is now {:?}", def_bm);
self.inh
.typeck_results
.borrow_mut()
.pat_adjustments_mut()
.insert(pat.hir_id, pat_adjustments);
}
(expected, def_bm)
}
fn check_pat_lit(
&self,
span: Span,
lt: &hir::Expr<'tcx>,
expected: Ty<'tcx>,
ti: TopInfo<'tcx>,
) -> Ty<'tcx> {
// We've already computed the type above (when checking for a non-ref pat),
// so avoid computing it again.
let ty = self.node_ty(lt.hir_id);
// Byte string patterns behave the same way as array patterns
// They can denote both statically and dynamically-sized byte arrays.
let mut pat_ty = ty;
if let hir::ExprKind::Lit(Spanned { node: ast::LitKind::ByteStr(_), .. }) = lt.kind {
let expected = self.structurally_resolved_type(span, expected);
if let ty::Ref(_, inner_ty, _) = expected.kind() {
if matches!(inner_ty.kind(), ty::Slice(_)) {
let tcx = self.tcx;
trace!(?lt.hir_id.local_id, "polymorphic byte string lit");
self.typeck_results
.borrow_mut()
.treat_byte_string_as_slice
.insert(lt.hir_id.local_id);
pat_ty = tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_slice(tcx.types.u8));
}
}
}
// Somewhat surprising: in this case, the subtyping relation goes the
// opposite way as the other cases. Actually what we really want is not
// a subtyping relation at all but rather that there exists a LUB
// (so that they can be compared). However, in practice, constants are
// always scalars or strings. For scalars subtyping is irrelevant,
// and for strings `ty` is type is `&'static str`, so if we say that
//
// &'static str <: expected
//
// then that's equivalent to there existing a LUB.
let cause = self.pattern_cause(ti, span);
if let Some(mut err) = self.demand_suptype_with_origin(&cause, expected, pat_ty) {
err.emit_unless(
ti.span
.filter(|&s| {
// In the case of `if`- and `while`-expressions we've already checked
// that `scrutinee: bool`. We know that the pattern is `true`,
// so an error here would be a duplicate and from the wrong POV.
s.is_desugaring(DesugaringKind::CondTemporary)
})
.is_some(),
);
}
pat_ty
}
fn check_pat_range(
&self,
span: Span,
lhs: Option<&'tcx hir::Expr<'tcx>>,
rhs: Option<&'tcx hir::Expr<'tcx>>,
expected: Ty<'tcx>,
ti: TopInfo<'tcx>,
) -> Ty<'tcx> {
let calc_side = |opt_expr: Option<&'tcx hir::Expr<'tcx>>| match opt_expr {
None => None,
Some(expr) => {
let ty = self.check_expr(expr);
// Check that the end-point is possibly of numeric or char type.
// The early check here is not for correctness, but rather better
// diagnostics (e.g. when `&str` is being matched, `expected` will
// be peeled to `str` while ty here is still `&str`, if we don't
// err ealy here, a rather confusing unification error will be
// emitted instead).
let fail =
!(ty.is_numeric() || ty.is_char() || ty.is_ty_var() || ty.references_error());
Some((fail, ty, expr.span))
}
};
let mut lhs = calc_side(lhs);
let mut rhs = calc_side(rhs);
if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
// There exists a side that didn't meet our criteria that the end-point
// be of a numeric or char type, as checked in `calc_side` above.
self.emit_err_pat_range(span, lhs, rhs);
return self.tcx.ty_error();
}
// Unify each side with `expected`.
// Subtyping doesn't matter here, as the value is some kind of scalar.
let demand_eqtype = |x: &mut _, y| {
if let Some((ref mut fail, x_ty, x_span)) = *x {
if let Some(mut err) = self.demand_eqtype_pat_diag(x_span, expected, x_ty, ti) {
if let Some((_, y_ty, y_span)) = y {
self.endpoint_has_type(&mut err, y_span, y_ty);
}
err.emit();
*fail = true;
};
}
};
demand_eqtype(&mut lhs, rhs);
demand_eqtype(&mut rhs, lhs);
if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
return self.tcx.ty_error();
}
// Find the unified type and check if it's of numeric or char type again.
// This check is needed if both sides are inference variables.
// We require types to be resolved here so that we emit inference failure
// rather than "_ is not a char or numeric".
let ty = self.structurally_resolved_type(span, expected);
if !(ty.is_numeric() || ty.is_char() || ty.references_error()) {
if let Some((ref mut fail, _, _)) = lhs {
*fail = true;
}
if let Some((ref mut fail, _, _)) = rhs {
*fail = true;
}
self.emit_err_pat_range(span, lhs, rhs);
return self.tcx.ty_error();
}
ty
}
fn endpoint_has_type(&self, err: &mut DiagnosticBuilder<'_>, span: Span, ty: Ty<'_>) {
if !ty.references_error() {
err.span_label(span, &format!("this is of type `{}`", ty));
}
}
fn emit_err_pat_range(
&self,
span: Span,
lhs: Option<(bool, Ty<'tcx>, Span)>,
rhs: Option<(bool, Ty<'tcx>, Span)>,
) {
let span = match (lhs, rhs) {
(Some((true, ..)), Some((true, ..))) => span,
(Some((true, _, sp)), _) => sp,
(_, Some((true, _, sp))) => sp,
_ => span_bug!(span, "emit_err_pat_range: no side failed or exists but still error?"),
};
let mut err = struct_span_err!(
self.tcx.sess,
span,
E0029,
"only `char` and numeric types are allowed in range patterns"
);
let msg = |ty| {
let ty = self.resolve_vars_if_possible(ty);
format!("this is of type `{}` but it should be `char` or numeric", ty)
};
let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| {
err.span_label(first_span, &msg(first_ty));
if let Some((_, ty, sp)) = second {
let ty = self.resolve_vars_if_possible(ty);
self.endpoint_has_type(&mut err, sp, ty);
}
};
match (lhs, rhs) {
(Some((true, lhs_ty, lhs_sp)), Some((true, rhs_ty, rhs_sp))) => {
err.span_label(lhs_sp, &msg(lhs_ty));
err.span_label(rhs_sp, &msg(rhs_ty));
}
(Some((true, lhs_ty, lhs_sp)), rhs) => one_side_err(lhs_sp, lhs_ty, rhs),
(lhs, Some((true, rhs_ty, rhs_sp))) => one_side_err(rhs_sp, rhs_ty, lhs),
_ => span_bug!(span, "Impossible, verified above."),
}
if self.tcx.sess.teach(&err.get_code().unwrap()) {
err.note(
"In a match expression, only numbers and characters can be matched \
against a range. This is because the compiler checks that the range \
is non-empty at compile-time, and is unable to evaluate arbitrary \
comparison functions. If you want to capture values of an orderable \
type between two end-points, you can use a guard.",
);
}
err.emit();
}
fn check_pat_ident(
&self,
pat: &'tcx Pat<'tcx>,
ba: hir::BindingAnnotation,
var_id: HirId,
sub: Option<&'tcx Pat<'tcx>>,
expected: Ty<'tcx>,
def_bm: BindingMode,
ti: TopInfo<'tcx>,
) -> Ty<'tcx> {
// Determine the binding mode...
let bm = match ba {
hir::BindingAnnotation::Unannotated => def_bm,
_ => BindingMode::convert(ba),
};
// ...and store it in a side table:
self.inh.typeck_results.borrow_mut().pat_binding_modes_mut().insert(pat.hir_id, bm);
debug!("check_pat_ident: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
let local_ty = self.local_ty(pat.span, pat.hir_id).decl_ty;
let eq_ty = match bm {
ty::BindByReference(mutbl) => {
// If the binding is like `ref x | ref mut x`,
// then `x` is assigned a value of type `&M T` where M is the
// mutability and T is the expected type.
//
// `x` is assigned a value of type `&M T`, hence `&M T <: typeof(x)`
// is required. However, we use equality, which is stronger.
// See (note_1) for an explanation.
self.new_ref_ty(pat.span, mutbl, expected)
}
// Otherwise, the type of x is the expected type `T`.
ty::BindByValue(_) => {
// As above, `T <: typeof(x)` is required, but we use equality, see (note_1).
expected
}
};
self.demand_eqtype_pat(pat.span, eq_ty, local_ty, ti);
// If there are multiple arms, make sure they all agree on
// what the type of the binding `x` ought to be.
if var_id != pat.hir_id {
self.check_binding_alt_eq_ty(pat.span, var_id, local_ty, ti);
}
if let Some(p) = sub {
self.check_pat(p, expected, def_bm, TopInfo { parent_pat: Some(pat), ..ti });
}
local_ty
}
fn check_binding_alt_eq_ty(&self, span: Span, var_id: HirId, ty: Ty<'tcx>, ti: TopInfo<'tcx>) {
let var_ty = self.local_ty(span, var_id).decl_ty;
if let Some(mut err) = self.demand_eqtype_pat_diag(span, var_ty, ty, ti) {
let hir = self.tcx.hir();
let var_ty = self.resolve_vars_with_obligations(var_ty);
let msg = format!("first introduced with type `{}` here", var_ty);
err.span_label(hir.span(var_id), msg);
let in_match = hir.parent_iter(var_id).any(|(_, n)| {
matches!(
n,
hir::Node::Expr(hir::Expr {
kind: hir::ExprKind::Match(.., hir::MatchSource::Normal),
..
})
)
});
let pre = if in_match { "in the same arm, " } else { "" };
err.note(&format!("{}a binding must have the same type in all alternatives", pre));
err.emit();
}
}
fn borrow_pat_suggestion(
&self,
err: &mut DiagnosticBuilder<'_>,
pat: &Pat<'_>,
inner: &Pat<'_>,
expected: Ty<'tcx>,
) {
let tcx = self.tcx;
if let PatKind::Binding(..) = inner.kind {
let binding_parent_id = tcx.hir().get_parent_node(pat.hir_id);
let binding_parent = tcx.hir().get(binding_parent_id);
debug!("inner {:?} pat {:?} parent {:?}", inner, pat, binding_parent);
match binding_parent {
hir::Node::Param(hir::Param { span, .. })
if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) =>
{
err.span_suggestion(
*span,
&format!("did you mean `{}`", snippet),
format!(" &{}", expected),
Applicability::MachineApplicable,
);
}
hir::Node::Arm(_) | hir::Node::Pat(_) => {
// rely on match ergonomics or it might be nested `&&pat`
if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) {
err.span_suggestion(
pat.span,
"you can probably remove the explicit borrow",
snippet,
Applicability::MaybeIncorrect,
);
}
}
_ => {} // don't provide suggestions in other cases #55175
}
}
}
pub fn check_dereferenceable(&self, span: Span, expected: Ty<'tcx>, inner: &Pat<'_>) -> bool {
if let PatKind::Binding(..) = inner.kind {
if let Some(mt) = self.shallow_resolve(expected).builtin_deref(true) {
if let ty::Dynamic(..) = mt.ty.kind() {
// This is "x = SomeTrait" being reduced from
// "let &x = &SomeTrait" or "let box x = Box<SomeTrait>", an error.
let type_str = self.ty_to_string(expected);
let mut err = struct_span_err!(
self.tcx.sess,
span,
E0033,
"type `{}` cannot be dereferenced",
type_str
);
err.span_label(span, format!("type `{}` cannot be dereferenced", type_str));
if self.tcx.sess.teach(&err.get_code().unwrap()) {
err.note(CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ);
}
err.emit();
return false;
}
}
}
true
}
fn check_pat_struct(
&self,
pat: &'tcx Pat<'tcx>,
qpath: &hir::QPath<'_>,
fields: &'tcx [hir::PatField<'tcx>],
has_rest_pat: bool,
expected: Ty<'tcx>,
def_bm: BindingMode,
ti: TopInfo<'tcx>,
) -> Ty<'tcx> {
// Resolve the path and check the definition for errors.
let Some((variant, pat_ty)) = self.check_struct_path(qpath, pat.hir_id) else {
let err = self.tcx.ty_error();
for field in fields {
let ti = TopInfo { parent_pat: Some(pat), ..ti };
self.check_pat(field.pat, err, def_bm, ti);
}
return err;
};
// Type-check the path.
self.demand_eqtype_pat(pat.span, expected, pat_ty, ti);
// Type-check subpatterns.
if self.check_struct_pat_fields(pat_ty, &pat, variant, fields, has_rest_pat, def_bm, ti) {
pat_ty
} else {
self.tcx.ty_error()
}
}
fn check_pat_path<'b>(
&self,
pat: &Pat<'_>,
path_resolution: (Res, Option<Ty<'tcx>>, &'b [hir::PathSegment<'b>]),
expected: Ty<'tcx>,
ti: TopInfo<'tcx>,
) -> Ty<'tcx> {
let tcx = self.tcx;
// We have already resolved the path.
let (res, opt_ty, segments) = path_resolution;
match res {
Res::Err => {
self.set_tainted_by_errors();
return tcx.ty_error();
}
Res::Def(DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fictive | CtorKind::Fn), _) => {
report_unexpected_variant_res(tcx, res, pat.span);
return tcx.ty_error();
}
Res::SelfCtor(..)
| Res::Def(
DefKind::Ctor(_, CtorKind::Const)
| DefKind::Const
| DefKind::AssocConst
| DefKind::ConstParam,
_,
) => {} // OK
_ => bug!("unexpected pattern resolution: {:?}", res),
}
// Type-check the path.
let (pat_ty, pat_res) =
self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.hir_id);
if let Some(err) =
self.demand_suptype_with_origin(&self.pattern_cause(ti, pat.span), expected, pat_ty)
{
self.emit_bad_pat_path(err, pat.span, res, pat_res, pat_ty, segments, ti.parent_pat);
}
pat_ty
}
fn maybe_suggest_range_literal(
&self,
e: &mut DiagnosticBuilder<'_>,
opt_def_id: Option<hir::def_id::DefId>,
ident: Ident,
) -> bool {
match opt_def_id {
Some(def_id) => match self.tcx.hir().get_if_local(def_id) {
Some(hir::Node::Item(hir::Item {
kind: hir::ItemKind::Const(_, body_id), ..
})) => match self.tcx.hir().get(body_id.hir_id) {
hir::Node::Expr(expr) => {
if hir::is_range_literal(expr) {
let span = self.tcx.hir().span(body_id.hir_id);
if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span) {
e.span_suggestion_verbose(
ident.span,
"you may want to move the range into the match block",
snip,
Applicability::MachineApplicable,
);
return true;
}
}
}
_ => (),
},
_ => (),
},
_ => (),
}
false
}
fn emit_bad_pat_path<'b>(
&self,
mut e: DiagnosticBuilder<'_>,
pat_span: Span,
res: Res,
pat_res: Res,
pat_ty: Ty<'tcx>,
segments: &'b [hir::PathSegment<'b>],
parent_pat: Option<&Pat<'_>>,
) {
if let Some(span) = self.tcx.hir().res_span(pat_res) {
e.span_label(span, &format!("{} defined here", res.descr()));
if let [hir::PathSegment { ident, .. }] = &*segments {
e.span_label(
pat_span,
&format!(
"`{}` is interpreted as {} {}, not a new binding",
ident,
res.article(),
res.descr(),
),
);
match parent_pat {
Some(Pat { kind: hir::PatKind::Struct(..), .. }) => {
e.span_suggestion_verbose(
ident.span.shrink_to_hi(),
"bind the struct field to a different name instead",
format!(": other_{}", ident.as_str().to_lowercase()),
Applicability::HasPlaceholders,
);
}
_ => {
let (type_def_id, item_def_id) = match pat_ty.kind() {
Adt(def, _) => match res {
Res::Def(DefKind::Const, def_id) => (Some(def.did), Some(def_id)),
_ => (None, None),
},
_ => (None, None),
};
let ranges = &[
self.tcx.lang_items().range_struct(),
self.tcx.lang_items().range_from_struct(),
self.tcx.lang_items().range_to_struct(),
self.tcx.lang_items().range_full_struct(),
self.tcx.lang_items().range_inclusive_struct(),
self.tcx.lang_items().range_to_inclusive_struct(),
];
if type_def_id != None && ranges.contains(&type_def_id) {
if !self.maybe_suggest_range_literal(&mut e, item_def_id, *ident) {
let msg = "constants only support matching by type, \
if you meant to match against a range of values, \
consider using a range pattern like `min ..= max` in the match block";
e.note(msg);
}
} else {
let msg = "introduce a new binding instead";
let sugg = format!("other_{}", ident.as_str().to_lowercase());
e.span_suggestion(
ident.span,
msg,
sugg,
Applicability::HasPlaceholders,
);
}
}
};
}
}
e.emit();
}
fn check_pat_tuple_struct(
&self,
pat: &'tcx Pat<'tcx>,
qpath: &'tcx hir::QPath<'tcx>,
subpats: &'tcx [Pat<'tcx>],
ddpos: Option<usize>,
expected: Ty<'tcx>,
def_bm: BindingMode,
ti: TopInfo<'tcx>,
) -> Ty<'tcx> {
let tcx = self.tcx;
let on_error = || {
let parent_pat = Some(pat);
for pat in subpats {
self.check_pat(pat, tcx.ty_error(), def_bm, TopInfo { parent_pat, ..ti });
}
};
let report_unexpected_res = |res: Res| {
let sm = tcx.sess.source_map();
let path_str = sm
.span_to_snippet(sm.span_until_char(pat.span, '('))
.map_or_else(|_| String::new(), |s| format!(" `{}`", s.trim_end()));
let msg = format!(
"expected tuple struct or tuple variant, found {}{}",
res.descr(),
path_str
);
let mut err = struct_span_err!(tcx.sess, pat.span, E0164, "{}", msg);
match res {
Res::Def(DefKind::Fn | DefKind::AssocFn, _) => {
err.span_label(pat.span, "`fn` calls are not allowed in patterns");
err.help(
"for more information, visit \
https://doc.rust-lang.org/book/ch18-00-patterns.html",
);
}
_ => {
err.span_label(pat.span, "not a tuple variant or struct");
}
}
err.emit();
on_error();
};
// Resolve the path and check the definition for errors.
let (res, opt_ty, segments) =
self.resolve_ty_and_res_fully_qualified_call(qpath, pat.hir_id, pat.span);
if res == Res::Err {
self.set_tainted_by_errors();
on_error();
return self.tcx.ty_error();
}
// Type-check the path.
let (pat_ty, res) =
self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.hir_id);
if !pat_ty.is_fn() {
report_unexpected_res(res);
return tcx.ty_error();
}
let variant = match res {
Res::Err => {
self.set_tainted_by_errors();
on_error();
return tcx.ty_error();
}
Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) => {
report_unexpected_res(res);
return tcx.ty_error();
}
Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) => tcx.expect_variant_res(res),
_ => bug!("unexpected pattern resolution: {:?}", res),
};
// Replace constructor type with constructed type for tuple struct patterns.
let pat_ty = pat_ty.fn_sig(tcx).output();
let pat_ty = pat_ty.no_bound_vars().expect("expected fn type");
// Type-check the tuple struct pattern against the expected type.
let diag = self.demand_eqtype_pat_diag(pat.span, expected, pat_ty, ti);
let had_err = if let Some(mut err) = diag {
err.emit();
true
} else {
false
};
// Type-check subpatterns.
if subpats.len() == variant.fields.len()
|| subpats.len() < variant.fields.len() && ddpos.is_some()
{
let substs = match pat_ty.kind() {
ty::Adt(_, substs) => substs,
_ => bug!("unexpected pattern type {:?}", pat_ty),
};
for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) {
let field_ty = self.field_ty(subpat.span, &variant.fields[i], substs);
self.check_pat(subpat, field_ty, def_bm, TopInfo { parent_pat: Some(pat), ..ti });
self.tcx.check_stability(
variant.fields[i].did,
Some(pat.hir_id),
subpat.span,
None,
);
}
} else {
// Pattern has wrong number of fields.
self.e0023(pat.span, res, qpath, subpats, &variant.fields, expected, had_err);
on_error();
return tcx.ty_error();
}
pat_ty
}
fn e0023(
&self,
pat_span: Span,
res: Res,
qpath: &hir::QPath<'_>,
subpats: &'tcx [Pat<'tcx>],
fields: &'tcx [ty::FieldDef],
expected: Ty<'tcx>,
had_err: bool,
) {
let subpats_ending = pluralize!(subpats.len());
let fields_ending = pluralize!(fields.len());
let subpat_spans = if subpats.is_empty() {
vec![pat_span]
} else {
subpats.iter().map(|p| p.span).collect()
};
let last_subpat_span = *subpat_spans.last().unwrap();
let res_span = self.tcx.def_span(res.def_id());
let def_ident_span = self.tcx.def_ident_span(res.def_id()).unwrap_or(res_span);
let field_def_spans = if fields.is_empty() {
vec![res_span]
} else {
fields.iter().map(|f| f.ident(self.tcx).span).collect()
};
let last_field_def_span = *field_def_spans.last().unwrap();
let mut err = struct_span_err!(
self.tcx.sess,
MultiSpan::from_spans(subpat_spans),
E0023,
"this pattern has {} field{}, but the corresponding {} has {} field{}",
subpats.len(),
subpats_ending,
res.descr(),
fields.len(),
fields_ending,
);
err.span_label(
last_subpat_span,
&format!("expected {} field{}, found {}", fields.len(), fields_ending, subpats.len()),
);
if self.tcx.sess.source_map().is_multiline(qpath.span().between(last_subpat_span)) {
err.span_label(qpath.span(), "");
}
if self.tcx.sess.source_map().is_multiline(def_ident_span.between(last_field_def_span)) {
err.span_label(def_ident_span, format!("{} defined here", res.descr()));
}
for span in &field_def_spans[..field_def_spans.len() - 1] {
err.span_label(*span, "");
}
err.span_label(
last_field_def_span,
&format!("{} has {} field{}", res.descr(), fields.len(), fields_ending),
);
// Identify the case `Some(x, y)` where the expected type is e.g. `Option<(T, U)>`.
// More generally, the expected type wants a tuple variant with one field of an
// N-arity-tuple, e.g., `V_i((p_0, .., p_N))`. Meanwhile, the user supplied a pattern
// with the subpatterns directly in the tuple variant pattern, e.g., `V_i(p_0, .., p_N)`.
let missing_parentheses = match (&expected.kind(), fields, had_err) {
// #67037: only do this if we could successfully type-check the expected type against
// the tuple struct pattern. Otherwise the substs could get out of range on e.g.,
// `let P() = U;` where `P != U` with `struct P<T>(T);`.
(ty::Adt(_, substs), [field], false) => {
let field_ty = self.field_ty(pat_span, field, substs);
match field_ty.kind() {
ty::Tuple(_) => field_ty.tuple_fields().count() == subpats.len(),
_ => false,
}
}
_ => false,
};
if missing_parentheses {
let (left, right) = match subpats {
// This is the zero case; we aim to get the "hi" part of the `QPath`'s
// span as the "lo" and then the "hi" part of the pattern's span as the "hi".
// This looks like:
//
// help: missing parentheses
// |
// L | let A(()) = A(());
// | ^ ^
[] => (qpath.span().shrink_to_hi(), pat_span),
// Easy case. Just take the "lo" of the first sub-pattern and the "hi" of the
// last sub-pattern. In the case of `A(x)` the first and last may coincide.
// This looks like:
//
// help: missing parentheses
// |
// L | let A((x, y)) = A((1, 2));
// | ^ ^
[first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span),
};
err.multipart_suggestion(
"missing parentheses",
vec![(left, "(".to_string()), (right.shrink_to_hi(), ")".to_string())],
Applicability::MachineApplicable,
);
} else if fields.len() > subpats.len() && pat_span != DUMMY_SP {
let after_fields_span = pat_span.with_hi(pat_span.hi() - BytePos(1)).shrink_to_hi();
let all_fields_span = match subpats {
[] => after_fields_span,
[field] => field.span,
[first, .., last] => first.span.to(last.span),
};
// Check if all the fields in the pattern are wildcards.
let all_wildcards = subpats.iter().all(|pat| matches!(pat.kind, PatKind::Wild));
let first_tail_wildcard =
subpats.iter().enumerate().fold(None, |acc, (pos, pat)| match (acc, &pat.kind) {
(None, PatKind::Wild) => Some(pos),
(Some(_), PatKind::Wild) => acc,
_ => None,
});
let tail_span = match first_tail_wildcard {
None => after_fields_span,
Some(0) => subpats[0].span.to(after_fields_span),
Some(pos) => subpats[pos - 1].span.shrink_to_hi().to(after_fields_span),
};
// FIXME: heuristic-based suggestion to check current types for where to add `_`.
let mut wildcard_sugg = vec!["_"; fields.len() - subpats.len()].join(", ");
if !subpats.is_empty() {
wildcard_sugg = String::from(", ") + &wildcard_sugg;
}
err.span_suggestion_verbose(
after_fields_span,
"use `_` to explicitly ignore each field",
wildcard_sugg,
Applicability::MaybeIncorrect,
);
// Only suggest `..` if more than one field is missing
// or the pattern consists of all wildcards.
if fields.len() - subpats.len() > 1 || all_wildcards {
if subpats.is_empty() || all_wildcards {
err.span_suggestion_verbose(
all_fields_span,
"use `..` to ignore all fields",
String::from(".."),
Applicability::MaybeIncorrect,
);
} else {
err.span_suggestion_verbose(
tail_span,
"use `..` to ignore the rest of the fields",
String::from(", .."),
Applicability::MaybeIncorrect,
);
}
}
}
err.emit();
}
fn check_pat_tuple(
&self,
span: Span,
elements: &'tcx [Pat<'tcx>],
ddpos: Option<usize>,
expected: Ty<'tcx>,
def_bm: BindingMode,
ti: TopInfo<'tcx>,
) -> Ty<'tcx> {
let tcx = self.tcx;
let mut expected_len = elements.len();
if ddpos.is_some() {
// Require known type only when `..` is present.
if let ty::Tuple(tys) = self.structurally_resolved_type(span, expected).kind() {
expected_len = tys.len();
}
}
let max_len = cmp::max(expected_len, elements.len());
let element_tys_iter = (0..max_len).map(|_| {
GenericArg::from(self.next_ty_var(
// FIXME: `MiscVariable` for now -- obtaining the span and name information
// from all tuple elements isn't trivial.
TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span },
))
});
let element_tys = tcx.mk_substs(element_tys_iter);
let pat_ty = tcx.mk_ty(ty::Tuple(element_tys));
if let Some(mut err) = self.demand_eqtype_pat_diag(span, expected, pat_ty, ti) {
err.emit();
// Walk subpatterns with an expected type of `err` in this case to silence
// further errors being emitted when using the bindings. #50333
let element_tys_iter = (0..max_len).map(|_| tcx.ty_error());
for (_, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
self.check_pat(elem, tcx.ty_error(), def_bm, ti);
}
tcx.mk_tup(element_tys_iter)
} else {
for (i, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
self.check_pat(elem, element_tys[i].expect_ty(), def_bm, ti);
}
pat_ty
}
}
fn check_struct_pat_fields(
&self,
adt_ty: Ty<'tcx>,
pat: &'tcx Pat<'tcx>,
variant: &'tcx ty::VariantDef,
fields: &'tcx [hir::PatField<'tcx>],
has_rest_pat: bool,
def_bm: BindingMode,
ti: TopInfo<'tcx>,
) -> bool {
let tcx = self.tcx;
let (substs, adt) = match adt_ty.kind() {
ty::Adt(adt, substs) => (substs, adt),
_ => span_bug!(pat.span, "struct pattern is not an ADT"),
};
// Index the struct fields' types.
let field_map = variant
.fields
.iter()
.enumerate()
.map(|(i, field)| (field.ident(self.tcx).normalize_to_macros_2_0(), (i, field)))
.collect::<FxHashMap<_, _>>();
// Keep track of which fields have already appeared in the pattern.
let mut used_fields = FxHashMap::default();
let mut no_field_errors = true;
let mut inexistent_fields = vec![];
// Typecheck each field.
for field in fields {
let span = field.span;
let ident = tcx.adjust_ident(field.ident, variant.def_id);
let field_ty = match used_fields.entry(ident) {
Occupied(occupied) => {
self.error_field_already_bound(span, field.ident, *occupied.get());
no_field_errors = false;
tcx.ty_error()
}
Vacant(vacant) => {
vacant.insert(span);
field_map
.get(&ident)
.map(|(i, f)| {
self.write_field_index(field.hir_id, *i);
self.tcx.check_stability(f.did, Some(pat.hir_id), span, None);
self.field_ty(span, f, substs)
})
.unwrap_or_else(|| {
inexistent_fields.push(field.ident);
no_field_errors = false;
tcx.ty_error()
})
}
};
self.check_pat(field.pat, field_ty, def_bm, TopInfo { parent_pat: Some(pat), ..ti });
}
let mut unmentioned_fields = variant
.fields
.iter()
.map(|field| (field, field.ident(self.tcx).normalize_to_macros_2_0()))
.filter(|(_, ident)| !used_fields.contains_key(ident))
.collect::<Vec<_>>();
let inexistent_fields_err = if !(inexistent_fields.is_empty() || variant.is_recovered()) {
Some(self.error_inexistent_fields(
adt.variant_descr(),
&inexistent_fields,
&mut unmentioned_fields,
variant,
))
} else {
None
};
// Require `..` if struct has non_exhaustive attribute.
let non_exhaustive = variant.is_field_list_non_exhaustive() && !adt.did.is_local();
if non_exhaustive && !has_rest_pat {
self.error_foreign_non_exhaustive_spat(pat, adt.variant_descr(), fields.is_empty());
}
let mut unmentioned_err = None;
// Report an error if an incorrect number of fields was specified.
if adt.is_union() {
if fields.len() != 1 {
tcx.sess
.struct_span_err(pat.span, "union patterns should have exactly one field")
.emit();
}
if has_rest_pat {
tcx.sess.struct_span_err(pat.span, "`..` cannot be used in union patterns").emit();
}
} else if !unmentioned_fields.is_empty() {
let accessible_unmentioned_fields: Vec<_> = unmentioned_fields
.iter()
.copied()
.filter(|(field, _)| {
field.vis.is_accessible_from(tcx.parent_module(pat.hir_id).to_def_id(), tcx)
})
.collect();
if !has_rest_pat {
if accessible_unmentioned_fields.is_empty() {
unmentioned_err = Some(self.error_no_accessible_fields(pat, fields));
} else {
unmentioned_err = Some(self.error_unmentioned_fields(
pat,
&accessible_unmentioned_fields,
accessible_unmentioned_fields.len() != unmentioned_fields.len(),
fields,
));
}
} else if non_exhaustive && !accessible_unmentioned_fields.is_empty() {
self.lint_non_exhaustive_omitted_patterns(
pat,
&accessible_unmentioned_fields,
adt_ty,
)
}
}
match (inexistent_fields_err, unmentioned_err) {
(Some(mut i), Some(mut u)) => {
if let Some(mut e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
// We don't want to show the inexistent fields error when this was
// `Foo { a, b }` when it should have been `Foo(a, b)`.
i.delay_as_bug();
u.delay_as_bug();
e.emit();
} else {
i.emit();
u.emit();
}
}
(None, Some(mut u)) => {
if let Some(mut e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
u.delay_as_bug();
e.emit();
} else {
u.emit();
}
}
(Some(mut err), None) => {
err.emit();
}
(None, None) if let Some(mut err) =
self.error_tuple_variant_index_shorthand(variant, pat, fields) =>
{
err.emit();
}
(None, None) => {}
}
no_field_errors
}
fn error_tuple_variant_index_shorthand(
&self,
variant: &VariantDef,
pat: &'_ Pat<'_>,
fields: &[hir::PatField<'_>],
) -> Option<DiagnosticBuilder<'_>> {
// if this is a tuple struct, then all field names will be numbers
// so if any fields in a struct pattern use shorthand syntax, they will
// be invalid identifiers (for example, Foo { 0, 1 }).
if let (CtorKind::Fn, PatKind::Struct(qpath, field_patterns, ..)) =
(variant.ctor_kind, &pat.kind)
{
let has_shorthand_field_name = field_patterns.iter().any(|field| field.is_shorthand);
if has_shorthand_field_name {
let path = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| {
s.print_qpath(qpath, false)
});
let mut err = struct_span_err!(
self.tcx.sess,
pat.span,
E0769,
"tuple variant `{}` written as struct variant",
path
);
err.span_suggestion_verbose(
qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
"use the tuple variant pattern syntax instead",
format!("({})", self.get_suggested_tuple_struct_pattern(fields, variant)),
Applicability::MaybeIncorrect,
);
return Some(err);
}
}
None
}
fn error_foreign_non_exhaustive_spat(&self, pat: &Pat<'_>, descr: &str, no_fields: bool) {
let sess = self.tcx.sess;
let sm = sess.source_map();
let sp_brace = sm.end_point(pat.span);
let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi()));
let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" };
let mut err = struct_span_err!(
sess,
pat.span,
E0638,
"`..` required with {} marked as non-exhaustive",
descr
);
err.span_suggestion_verbose(
sp_comma,
"add `..` at the end of the field list to ignore all other fields",
sugg.to_string(),
Applicability::MachineApplicable,
);
err.emit();
}
fn error_field_already_bound(&self, span: Span, ident: Ident, other_field: Span) {
struct_span_err!(
self.tcx.sess,
span,
E0025,
"field `{}` bound multiple times in the pattern",
ident
)
.span_label(span, format!("multiple uses of `{}` in pattern", ident))
.span_label(other_field, format!("first use of `{}`", ident))
.emit();
}
fn error_inexistent_fields(
&self,
kind_name: &str,
inexistent_fields: &[Ident],
unmentioned_fields: &mut Vec<(&ty::FieldDef, Ident)>,
variant: &ty::VariantDef,
) -> DiagnosticBuilder<'tcx> {
let tcx = self.tcx;
let (field_names, t, plural) = if inexistent_fields.len() == 1 {
(format!("a field named `{}`", inexistent_fields[0]), "this", "")
} else {
(
format!(
"fields named {}",
inexistent_fields
.iter()
.map(|ident| format!("`{}`", ident))
.collect::<Vec<String>>()
.join(", ")
),
"these",
"s",
)
};
let spans = inexistent_fields.iter().map(|ident| ident.span).collect::<Vec<_>>();
let mut err = struct_span_err!(
tcx.sess,
spans,
E0026,
"{} `{}` does not have {}",
kind_name,
tcx.def_path_str(variant.def_id),
field_names
);
if let Some(ident) = inexistent_fields.last() {
err.span_label(
ident.span,
format!(
"{} `{}` does not have {} field{}",
kind_name,
tcx.def_path_str(variant.def_id),
t,
plural
),
);
if unmentioned_fields.len() == 1 {
let input =
unmentioned_fields.iter().map(|(_, field)| field.name).collect::<Vec<_>>();
let suggested_name = find_best_match_for_name(&input, ident.name, None);
if let Some(suggested_name) = suggested_name {
err.span_suggestion(
ident.span,
"a field with a similar name exists",
suggested_name.to_string(),
Applicability::MaybeIncorrect,
);
// When we have a tuple struct used with struct we don't want to suggest using
// the (valid) struct syntax with numeric field names. Instead we want to
// suggest the expected syntax. We infer that this is the case by parsing the
// `Ident` into an unsized integer. The suggestion will be emitted elsewhere in
// `smart_resolve_context_dependent_help`.
if suggested_name.to_ident_string().parse::<usize>().is_err() {
// We don't want to throw `E0027` in case we have thrown `E0026` for them.
unmentioned_fields.retain(|&(_, x)| x.name != suggested_name);
}
} else if inexistent_fields.len() == 1 {
let unmentioned_field = unmentioned_fields[0].1.name;
err.span_suggestion_short(
ident.span,
&format!(
"`{}` has a field named `{}`",
tcx.def_path_str(variant.def_id),
unmentioned_field
),
unmentioned_field.to_string(),
Applicability::MaybeIncorrect,
);
}
}
}
if tcx.sess.teach(&err.get_code().unwrap()) {
err.note(
"This error indicates that a struct pattern attempted to \
extract a non-existent field from a struct. Struct fields \
are identified by the name used before the colon : so struct \
patterns should resemble the declaration of the struct type \
being matched.\n\n\
If you are using shorthand field patterns but want to refer \
to the struct field by a different name, you should rename \
it explicitly.",
);
}
err
}
fn error_tuple_variant_as_struct_pat(
&self,
pat: &Pat<'_>,
fields: &'tcx [hir::PatField<'tcx>],
variant: &ty::VariantDef,
) -> Option<DiagnosticBuilder<'tcx>> {
if let (CtorKind::Fn, PatKind::Struct(qpath, ..)) = (variant.ctor_kind, &pat.kind) {
let path = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| {
s.print_qpath(qpath, false)
});
let mut err = struct_span_err!(
self.tcx.sess,
pat.span,
E0769,
"tuple variant `{}` written as struct variant",
path
);
let (sugg, appl) = if fields.len() == variant.fields.len() {
(
self.get_suggested_tuple_struct_pattern(fields, variant),
Applicability::MachineApplicable,
)
} else {
(
variant.fields.iter().map(|_| "_").collect::<Vec<&str>>().join(", "),
Applicability::MaybeIncorrect,
)
};
err.span_suggestion_verbose(
qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
"use the tuple variant pattern syntax instead",
format!("({})", sugg),
appl,
);
return Some(err);
}
None
}
fn get_suggested_tuple_struct_pattern(
&self,
fields: &[hir::PatField<'_>],
variant: &VariantDef,
) -> String {
let variant_field_idents =
variant.fields.iter().map(|f| f.ident(self.tcx)).collect::<Vec<Ident>>();
fields
.iter()
.map(|field| {
match self.tcx.sess.source_map().span_to_snippet(field.pat.span) {
Ok(f) => {
// Field names are numbers, but numbers
// are not valid identifiers
if variant_field_idents.contains(&field.ident) {
String::from("_")
} else {
f
}
}
Err(_) => rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| {
s.print_pat(field.pat)
}),
}
})
.collect::<Vec<String>>()
.join(", ")
}
/// Returns a diagnostic reporting a struct pattern which is missing an `..` due to
/// inaccessible fields.
///
/// ```text
/// error: pattern requires `..` due to inaccessible fields
/// --> src/main.rs:10:9
/// |
/// LL | let foo::Foo {} = foo::Foo::default();
/// | ^^^^^^^^^^^
/// |
/// help: add a `..`
/// |
/// LL | let foo::Foo { .. } = foo::Foo::default();
/// | ^^^^^^
/// ```
fn error_no_accessible_fields(
&self,
pat: &Pat<'_>,
fields: &'tcx [hir::PatField<'tcx>],
) -> DiagnosticBuilder<'tcx> {
let mut err = self
.tcx
.sess
.struct_span_err(pat.span, "pattern requires `..` due to inaccessible fields");
if let Some(field) = fields.last() {
err.span_suggestion_verbose(
field.span.shrink_to_hi(),
"ignore the inaccessible and unused fields",
", ..".to_string(),
Applicability::MachineApplicable,
);
} else {
let qpath_span = if let PatKind::Struct(qpath, ..) = &pat.kind {
qpath.span()
} else {
bug!("`error_no_accessible_fields` called on non-struct pattern");
};
// Shrink the span to exclude the `foo:Foo` in `foo::Foo { }`.
let span = pat.span.with_lo(qpath_span.shrink_to_hi().hi());
err.span_suggestion_verbose(
span,
"ignore the inaccessible and unused fields",
" { .. }".to_string(),
Applicability::MachineApplicable,
);
}
err
}
/// Report that a pattern for a `#[non_exhaustive]` struct marked with `non_exhaustive_omitted_patterns`
/// is not exhaustive enough.
///
/// Nb: the partner lint for enums lives in `compiler/rustc_mir_build/src/thir/pattern/usefulness.rs`.
fn lint_non_exhaustive_omitted_patterns(
&self,
pat: &Pat<'_>,
unmentioned_fields: &[(&ty::FieldDef, Ident)],
ty: Ty<'tcx>,
) {
fn joined_uncovered_patterns(witnesses: &[&Ident]) -> String {
const LIMIT: usize = 3;
match witnesses {
[] => bug!(),
[witness] => format!("`{}`", witness),
[head @ .., tail] if head.len() < LIMIT => {
let head: Vec<_> = head.iter().map(<_>::to_string).collect();
format!("`{}` and `{}`", head.join("`, `"), tail)
}
_ => {
let (head, tail) = witnesses.split_at(LIMIT);
let head: Vec<_> = head.iter().map(<_>::to_string).collect();
format!("`{}` and {} more", head.join("`, `"), tail.len())
}
}
}
let joined_patterns = joined_uncovered_patterns(
&unmentioned_fields.iter().map(|(_, i)| i).collect::<Vec<_>>(),
);
self.tcx.struct_span_lint_hir(NON_EXHAUSTIVE_OMITTED_PATTERNS, pat.hir_id, pat.span, |build| {
let mut lint = build.build("some fields are not explicitly listed");
lint.span_label(pat.span, format!("field{} {} not listed", rustc_errors::pluralize!(unmentioned_fields.len()), joined_patterns));
lint.help(
"ensure that all fields are mentioned explicitly by adding the suggested fields",
);
lint.note(&format!(
"the pattern is of type `{}` and the `non_exhaustive_omitted_patterns` attribute was found",
ty,
));
lint.emit();
});
}
/// Returns a diagnostic reporting a struct pattern which does not mention some fields.
///
/// ```text
/// error[E0027]: pattern does not mention field `bar`
/// --> src/main.rs:15:9
/// |
/// LL | let foo::Foo {} = foo::Foo::new();
/// | ^^^^^^^^^^^ missing field `bar`
/// ```
fn error_unmentioned_fields(
&self,
pat: &Pat<'_>,
unmentioned_fields: &[(&ty::FieldDef, Ident)],
have_inaccessible_fields: bool,
fields: &'tcx [hir::PatField<'tcx>],
) -> DiagnosticBuilder<'tcx> {
let inaccessible = if have_inaccessible_fields { " and inaccessible fields" } else { "" };
let field_names = if unmentioned_fields.len() == 1 {
format!("field `{}`{}", unmentioned_fields[0].1, inaccessible)
} else {
let fields = unmentioned_fields
.iter()
.map(|(_, name)| format!("`{}`", name))
.collect::<Vec<String>>()
.join(", ");
format!("fields {}{}", fields, inaccessible)
};
let mut err = struct_span_err!(
self.tcx.sess,
pat.span,
E0027,
"pattern does not mention {}",
field_names
);
err.span_label(pat.span, format!("missing {}", field_names));
let len = unmentioned_fields.len();
let (prefix, postfix, sp) = match fields {
[] => match &pat.kind {
PatKind::Struct(path, [], false) => {
(" { ", " }", path.span().shrink_to_hi().until(pat.span.shrink_to_hi()))
}
_ => return err,
},
[.., field] => {
// Account for last field having a trailing comma or parse recovery at the tail of
// the pattern to avoid invalid suggestion (#78511).
let tail = field.span.shrink_to_hi().with_hi(pat.span.hi());
match &pat.kind {
PatKind::Struct(..) => (", ", " }", tail),
_ => return err,
}
}
};
err.span_suggestion(
sp,
&format!(
"include the missing field{} in the pattern{}",
if len == 1 { "" } else { "s" },
if have_inaccessible_fields { " and ignore the inaccessible fields" } else { "" }
),
format!(
"{}{}{}{}",
prefix,
unmentioned_fields
.iter()
.map(|(_, name)| name.to_string())
.collect::<Vec<_>>()
.join(", "),
if have_inaccessible_fields { ", .." } else { "" },
postfix,
),
Applicability::MachineApplicable,
);
err.span_suggestion(
sp,
&format!(
"if you don't care about {} missing field{}, you can explicitly ignore {}",
if len == 1 { "this" } else { "these" },
if len == 1 { "" } else { "s" },
if len == 1 { "it" } else { "them" },
),
format!("{}..{}", prefix, postfix),
Applicability::MachineApplicable,
);
err
}
fn check_pat_box(
&self,
span: Span,
inner: &'tcx Pat<'tcx>,
expected: Ty<'tcx>,
def_bm: BindingMode,
ti: TopInfo<'tcx>,
) -> Ty<'tcx> {
let tcx = self.tcx;
let (box_ty, inner_ty) = if self.check_dereferenceable(span, expected, inner) {
// Here, `demand::subtype` is good enough, but I don't
// think any errors can be introduced by using `demand::eqtype`.
let inner_ty = self.next_ty_var(TypeVariableOrigin {
kind: TypeVariableOriginKind::TypeInference,
span: inner.span,
});
let box_ty = tcx.mk_box(inner_ty);
self.demand_eqtype_pat(span, expected, box_ty, ti);
(box_ty, inner_ty)
} else {
let err = tcx.ty_error();
(err, err)
};
self.check_pat(inner, inner_ty, def_bm, ti);
box_ty
}
fn check_pat_ref(
&self,
pat: &'tcx Pat<'tcx>,
inner: &'tcx Pat<'tcx>,
mutbl: hir::Mutability,
expected: Ty<'tcx>,
def_bm: BindingMode,
ti: TopInfo<'tcx>,
) -> Ty<'tcx> {
let tcx = self.tcx;
let expected = self.shallow_resolve(expected);
let (rptr_ty, inner_ty) = if self.check_dereferenceable(pat.span, expected, inner) {
// `demand::subtype` would be good enough, but using `eqtype` turns
// out to be equally general. See (note_1) for details.
// Take region, inner-type from expected type if we can,
// to avoid creating needless variables. This also helps with
// the bad interactions of the given hack detailed in (note_1).
debug!("check_pat_ref: expected={:?}", expected);
match *expected.kind() {
ty::Ref(_, r_ty, r_mutbl) if r_mutbl == mutbl => (expected, r_ty),
_ => {
let inner_ty = self.next_ty_var(TypeVariableOrigin {
kind: TypeVariableOriginKind::TypeInference,
span: inner.span,
});
let rptr_ty = self.new_ref_ty(pat.span, mutbl, inner_ty);
debug!("check_pat_ref: demanding {:?} = {:?}", expected, rptr_ty);
let err = self.demand_eqtype_pat_diag(pat.span, expected, rptr_ty, ti);
// Look for a case like `fn foo(&foo: u32)` and suggest
// `fn foo(foo: &u32)`
if let Some(mut err) = err {
self.borrow_pat_suggestion(&mut err, pat, inner, expected);
err.emit();
}
(rptr_ty, inner_ty)
}
}
} else {
let err = tcx.ty_error();
(err, err)
};
self.check_pat(inner, inner_ty, def_bm, TopInfo { parent_pat: Some(pat), ..ti });
rptr_ty
}
/// Create a reference type with a fresh region variable.
fn new_ref_ty(&self, span: Span, mutbl: hir::Mutability, ty: Ty<'tcx>) -> Ty<'tcx> {
let region = self.next_region_var(infer::PatternRegion(span));
let mt = ty::TypeAndMut { ty, mutbl };
self.tcx.mk_ref(region, mt)
}
/// Type check a slice pattern.
///
/// Syntactically, these look like `[pat_0, ..., pat_n]`.
/// Semantically, we are type checking a pattern with structure:
/// ```
/// [before_0, ..., before_n, (slice, after_0, ... after_n)?]
/// ```
/// The type of `slice`, if it is present, depends on the `expected` type.
/// If `slice` is missing, then so is `after_i`.
/// If `slice` is present, it can still represent 0 elements.
fn check_pat_slice(
&self,
span: Span,
before: &'tcx [Pat<'tcx>],
slice: Option<&'tcx Pat<'tcx>>,
after: &'tcx [Pat<'tcx>],
expected: Ty<'tcx>,
def_bm: BindingMode,
ti: TopInfo<'tcx>,
) -> Ty<'tcx> {
let expected = self.structurally_resolved_type(span, expected);
let (element_ty, opt_slice_ty, inferred) = match *expected.kind() {
// An array, so we might have something like `let [a, b, c] = [0, 1, 2];`.
ty::Array(element_ty, len) => {
let min = before.len() as u64 + after.len() as u64;
let (opt_slice_ty, expected) =
self.check_array_pat_len(span, element_ty, expected, slice, len, min);
// `opt_slice_ty.is_none()` => `slice.is_none()`.
// Note, though, that opt_slice_ty could be `Some(error_ty)`.
assert!(opt_slice_ty.is_some() || slice.is_none());
(element_ty, opt_slice_ty, expected)
}
ty::Slice(element_ty) => (element_ty, Some(expected), expected),
// The expected type must be an array or slice, but was neither, so error.
_ => {
if !expected.references_error() {
self.error_expected_array_or_slice(span, expected, ti);
}
let err = self.tcx.ty_error();
(err, Some(err), err)
}
};
// Type check all the patterns before `slice`.
for elt in before {
self.check_pat(elt, element_ty, def_bm, ti);
}
// Type check the `slice`, if present, against its expected type.
if let Some(slice) = slice {
self.check_pat(slice, opt_slice_ty.unwrap(), def_bm, ti);
}
// Type check the elements after `slice`, if present.
for elt in after {
self.check_pat(elt, element_ty, def_bm, ti);
}
inferred
}
/// Type check the length of an array pattern.
///
/// Returns both the type of the variable length pattern (or `None`), and the potentially
/// inferred array type. We only return `None` for the slice type if `slice.is_none()`.
fn check_array_pat_len(
&self,
span: Span,
element_ty: Ty<'tcx>,
arr_ty: Ty<'tcx>,
slice: Option<&'tcx Pat<'tcx>>,
len: &ty::Const<'tcx>,
min_len: u64,
) -> (Option<Ty<'tcx>>, Ty<'tcx>) {
if let Some(len) = len.try_eval_usize(self.tcx, self.param_env) {
// Now we know the length...
if slice.is_none() {
// ...and since there is no variable-length pattern,
// we require an exact match between the number of elements
// in the array pattern and as provided by the matched type.
if min_len == len {
return (None, arr_ty);
}
self.error_scrutinee_inconsistent_length(span, min_len, len);
} else if let Some(pat_len) = len.checked_sub(min_len) {
// The variable-length pattern was there,
// so it has an array type with the remaining elements left as its size...
return (Some(self.tcx.mk_array(element_ty, pat_len)), arr_ty);
} else {
// ...however, in this case, there were no remaining elements.
// That is, the slice pattern requires more than the array type offers.
self.error_scrutinee_with_rest_inconsistent_length(span, min_len, len);
}
} else if slice.is_none() {
// We have a pattern with a fixed length,
// which we can use to infer the length of the array.
let updated_arr_ty = self.tcx.mk_array(element_ty, min_len);
self.demand_eqtype(span, updated_arr_ty, arr_ty);
return (None, updated_arr_ty);
} else {
// We have a variable-length pattern and don't know the array length.
// This happens if we have e.g.,
// `let [a, b, ..] = arr` where `arr: [T; N]` where `const N: usize`.
self.error_scrutinee_unfixed_length(span);
}
// If we get here, we must have emitted an error.
(Some(self.tcx.ty_error()), arr_ty)
}
fn error_scrutinee_inconsistent_length(&self, span: Span, min_len: u64, size: u64) {
struct_span_err!(
self.tcx.sess,
span,
E0527,
"pattern requires {} element{} but array has {}",
min_len,
pluralize!(min_len),
size,
)
.span_label(span, format!("expected {} element{}", size, pluralize!(size)))
.emit();
}
fn error_scrutinee_with_rest_inconsistent_length(&self, span: Span, min_len: u64, size: u64) {
struct_span_err!(
self.tcx.sess,
span,
E0528,
"pattern requires at least {} element{} but array has {}",
min_len,
pluralize!(min_len),
size,
)
.span_label(
span,
format!("pattern cannot match array of {} element{}", size, pluralize!(size),),
)
.emit();
}
fn error_scrutinee_unfixed_length(&self, span: Span) {
struct_span_err!(
self.tcx.sess,
span,
E0730,
"cannot pattern-match on an array without a fixed length",
)
.emit();
}
fn error_expected_array_or_slice(&self, span: Span, expected_ty: Ty<'tcx>, ti: TopInfo<'tcx>) {
let mut err = struct_span_err!(
self.tcx.sess,
span,
E0529,
"expected an array or slice, found `{}`",
expected_ty
);
if let ty::Ref(_, ty, _) = expected_ty.kind() {
if let ty::Array(..) | ty::Slice(..) = ty.kind() {
err.help("the semantics of slice patterns changed recently; see issue #62254");
}
} else if Autoderef::new(&self.infcx, self.param_env, self.body_id, span, expected_ty, span)
.any(|(ty, _)| matches!(ty.kind(), ty::Slice(..)))
{
if let (Some(span), true) = (ti.span, ti.origin_expr) {
if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
let applicability = match self.resolve_vars_if_possible(ti.expected).kind() {
ty::Adt(adt_def, _)
if self.tcx.is_diagnostic_item(sym::Option, adt_def.did)
|| self.tcx.is_diagnostic_item(sym::Result, adt_def.did) =>
{
// Slicing won't work here, but `.as_deref()` might (issue #91328).
err.span_suggestion(
span,
"consider using `as_deref` here",
format!("{}.as_deref()", snippet),
Applicability::MaybeIncorrect,
);
None
}
// FIXME: instead of checking for Vec only, we could check whether the
// type implements `Deref<Target=X>`; see
// https://github.com/rust-lang/rust/pull/91343#discussion_r761466979
ty::Adt(adt_def, _)
if self.tcx.is_diagnostic_item(sym::Vec, adt_def.did) =>
{
Some(Applicability::MachineApplicable)
}
_ => Some(Applicability::MaybeIncorrect),
};
if let Some(applicability) = applicability {
err.span_suggestion(
span,
"consider slicing here",
format!("{}[..]", snippet),
applicability,
);
}
}
}
}
err.span_label(span, format!("pattern cannot match with input type `{}`", expected_ty));
err.emit();
}
}
| 41.32948 | 137 | 0.502855 |
9c780f05bde76f8a90bdeff38d8db7d22606f3db
| 12,326 |
//! Metadata: key-value pairs that can be attached to accounts,
//! transactions and assets.
#[cfg(not(feature = "std"))]
use alloc::{collections::btree_map, fmt, format, string::String, vec::Vec};
use core::borrow::Borrow;
#[cfg(feature = "std")]
use std::{collections::btree_map, fmt};
use derive_more::Display;
use iroha_schema::IntoSchema;
use parity_scale_codec::{Decode, Encode};
use serde::{Deserialize, Serialize};
use crate::{Name, Value};
/// Collection of parameters by their names.
pub type UnlimitedMetadata = btree_map::BTreeMap<Name, Value>;
/// Limits for [`Metadata`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Decode, Encode, Deserialize, Serialize)]
pub struct Limits {
/// Maximum number of entries
pub max_len: u32,
/// Maximum length of entry
pub max_entry_byte_size: u32,
}
impl fmt::Display for Limits {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
/// Metadata related errors.
#[derive(Debug, Clone, Display)]
pub enum Error {
/// Metadata entry too big.
#[display(fmt = "Metadata entry too big {} - {}", limits, actual)]
EntrySize {
/// The limits that were set for this entry
limits: Limits,
/// The actual *entry* size in bytes
actual: usize,
},
/// Metadata exceeds overall length limit
#[display(fmt = "Metadata exceeds overall length limit {} - {}", limits, actual)]
OverallSize {
/// The limits that were set for this entry
limits: Limits,
/// The actual *overall* size of metadata
actual: usize,
},
/// Empty path
#[display(fmt = "Path specification empty")]
EmptyPath,
/// Middle path segment is missing. I.e. nothing was found at that key
#[display(fmt = "{}: path segment not found", _0)]
MissingSegment(Name),
/// Middle path segment is not nested metadata. I.e. something was found, but isn't an instance of [`Metadata`]
#[display(fmt = "{}: path segment not an instance of metadata", _0)]
InvalidSegment(Name),
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
impl Limits {
/// Constructor.
pub const fn new(max_len: u32, max_entry_byte_size: u32) -> Limits {
Limits {
max_len,
max_entry_byte_size,
}
}
}
/// Collection of parameters by their names with checked insertion.
#[derive(
Debug,
Clone,
Default,
PartialEq,
Eq,
PartialOrd,
Ord,
Decode,
Encode,
Deserialize,
Serialize,
IntoSchema,
)]
#[serde(transparent)]
pub struct Metadata {
map: btree_map::BTreeMap<Name, Value>,
}
/// A path slice, composed of [`Name`]s.
pub type Path = [Name];
impl Metadata {
/// Constructor.
#[inline]
pub fn new() -> Self {
Self {
map: btree_map::BTreeMap::new(),
}
}
/// Get the (expensive) cumulative length of all [`Value`]s housed
/// in this map.
pub fn nested_len(&self) -> usize {
self.map.iter().map(|(_, v)| 1 + v.len()).sum()
}
/// Get metadata given path. If the path is malformed, or
/// incorrect (if e.g. any of interior path segments are not
/// [`Metadata`] instances return `None`. Else borrow the value
/// corresponding to that path.
pub fn nested_get(&self, path: &Path) -> Option<&Value> {
let key = path.last()?;
let mut map = &self.map;
for k in path.iter().take(path.len() - 1) {
map = match map.get(k)? {
Value::LimitedMetadata(data) => &data.map,
_ => return None,
};
}
map.get(key)
}
/// Remove leaf node in metadata, given path. If the path is
/// malformed, or incorrect (if e.g. any of interior path segments
/// are not [`Metadata`] instances) return `None`. Else return the
/// owned value corresponding to that path.
pub fn nested_remove(&mut self, path: &Path) -> Option<Value> {
let key = path.last()?;
let mut map = &mut self.map;
for k in path.iter().take(path.len() - 1) {
map = match map.get_mut(k)? {
Value::LimitedMetadata(data) => &mut data.map,
_ => return None,
};
}
map.remove(key)
}
/// Insert the given [`Value`] into the given path. If the path is
/// complete, check the limits and only then insert. The creation
/// of the path is the responsibility of the user.
///
/// # Errors
/// - If the path is empty.
/// - If one of the intermediate keys is absent.
/// - If some intermediate key is a leaf node.
pub fn nested_insert_with_limits(
&mut self,
path: &Path,
value: Value,
limits: Limits,
) -> Result<Option<Value>, Error> {
if self.map.len() >= limits.max_len as usize {
return Err(Error::OverallSize {
limits,
actual: self.map.len(),
});
}
let key = path.last().ok_or(Error::EmptyPath)?;
let mut layer = self;
for k in path.iter().take(path.len() - 1) {
layer = match layer
.map
.get_mut(k)
.ok_or_else(|| Error::MissingSegment(k.clone()))?
{
Value::LimitedMetadata(data) => data,
_ => return Err(Error::InvalidSegment(k.clone())),
};
}
check_size_limits(key, value.clone(), limits)?;
layer.insert_with_limits(key.clone(), value, limits)
}
/// Insert [`Value`] under the given key. Returns `Some(value)`
/// if the value was already present, `None` otherwise.
///
/// # Errors
/// Fails if `max_entry_byte_size` or `max_len` from `limits` are exceeded.
pub fn insert_with_limits(
&mut self,
key: Name,
value: Value,
limits: Limits,
) -> Result<Option<Value>, Error> {
if self.map.len() >= limits.max_len as usize && !self.map.contains_key(&key) {
return Err(Error::OverallSize {
limits,
actual: self.map.len(),
});
}
check_size_limits(&key, value.clone(), limits)?;
Ok(self.map.insert(key, value))
}
/// Returns a `Some(reference)` to the value corresponding to
/// the key, and `None` if not found.
#[inline]
pub fn get<K: Ord + ?Sized>(&self, key: &K) -> Option<&Value>
where
Name: Borrow<K>,
{
self.map.get(key)
}
/// Removes a key from the map, returning the owned
/// `Some(value)` at the key if the key was previously in the
/// map, else `None`.
#[inline]
pub fn remove<K: Ord + ?Sized>(&mut self, key: &K) -> Option<Value>
where
Name: Borrow<K>,
{
self.map.remove(key)
}
}
fn check_size_limits(key: &Name, value: Value, limits: Limits) -> Result<(), Error> {
let entry_bytes: Vec<u8> = (key, value).encode();
let byte_size = entry_bytes.len();
if byte_size > limits.max_entry_byte_size as usize {
return Err(Error::EntrySize {
limits,
actual: byte_size,
});
}
Ok(())
}
pub mod prelude {
//! Prelude: re-export most commonly used traits, structs and macros from this module.
pub use super::{Limits as MetadataLimits, Metadata, UnlimitedMetadata};
}
#[cfg(test)]
mod tests {
#![allow(clippy::restriction)]
#[cfg(not(feature = "std"))]
use alloc::{borrow::ToOwned as _, vec};
use iroha_macro::FromVariant;
use super::*;
use crate::ParseError;
/// Error used in testing to make text more readable using the `?` operator.
#[derive(Debug, Display, Clone, FromVariant)]
pub enum TestError {
Parse(ParseError),
Metadata(Error),
}
#[test]
fn nested_fns_ignore_empty_path() {
let mut metadata = Metadata::new();
let empty_path = vec![];
assert!(metadata.nested_get(&empty_path).is_none());
assert!(metadata
.nested_insert_with_limits(&empty_path, "0".to_owned().into(), Limits::new(12, 12))
.is_err());
assert!(metadata.nested_remove(&empty_path).is_none());
}
#[test]
#[allow(clippy::unwrap_used)]
fn nesting_inserts_removes() -> Result<(), TestError> {
let mut metadata = Metadata::new();
let limits = Limits::new(1024, 1024);
// TODO: If we allow a `unsafe`, we could create the path.
metadata
.insert_with_limits(Name::new("0")?, Metadata::new().into(), limits)
.unwrap();
metadata
.nested_insert_with_limits(
&[Name::new("0")?, Name::new("1")?],
Metadata::new().into(),
limits,
)
.unwrap();
let path = [Name::new("0")?, Name::new("1")?, Name::new("2")?];
metadata
.nested_insert_with_limits(&path, "Hello World".to_owned().into(), limits)
.unwrap();
assert_eq!(
*metadata.nested_get(&path).unwrap(),
Value::from("Hello World".to_owned())
);
assert_eq!(metadata.nested_len(), 6); // Three nested path segments.
metadata.nested_remove(&path);
assert!(metadata.nested_get(&path).is_none());
Ok(())
}
#[test]
fn non_existent_path_segment_fails() -> Result<(), TestError> {
let mut metadata = Metadata::new();
let limits = Limits::new(10, 15);
metadata.insert_with_limits(Name::new("0")?, Metadata::new().into(), limits)?;
metadata.nested_insert_with_limits(
&[Name::new("0")?, Name::new("1")?],
Metadata::new().into(),
limits,
)?;
let path = vec![Name::new("0")?, Name::new("1")?, Name::new("2")?];
metadata.nested_insert_with_limits(&path, "Hello World".to_owned().into(), limits)?;
let bad_path = vec![Name::new("0")?, Name::new("3")?, Name::new("2")?];
assert!(metadata
.nested_insert_with_limits(&bad_path, "Hello World".to_owned().into(), limits)
.is_err());
assert!(metadata.nested_get(&bad_path).is_none());
assert!(metadata.nested_remove(&bad_path).is_none());
Ok(())
}
#[test]
fn nesting_respects_limits() -> Result<(), TestError> {
let mut metadata = Metadata::new();
let limits = Limits::new(10, 14);
// TODO: If we allow a `unsafe`, we could create the path.
metadata.insert_with_limits(Name::new("0")?, Metadata::new().into(), limits)?;
metadata
.nested_insert_with_limits(
&[Name::new("0")?, Name::new("1")?],
Metadata::new().into(),
limits,
)
.unwrap();
let path = vec![Name::new("0")?, Name::new("1")?, Name::new("2")?];
let failing_insert =
metadata.nested_insert_with_limits(&path, "Hello World".to_owned().into(), limits);
assert!(failing_insert.is_err());
Ok(())
}
#[test]
fn insert_exceeds_entry_size() -> Result<(), TestError> {
let mut metadata = Metadata::new();
let limits = Limits::new(10, 5);
assert!(metadata
.insert_with_limits(Name::new("1")?, "2".to_owned().into(), limits)
.is_ok());
assert!(metadata
.insert_with_limits(Name::new("1")?, "23456".to_owned().into(), limits)
.is_err());
Ok(())
}
#[test]
// This test is a good candidate for both property-based and parameterised testing
fn insert_exceeds_len() -> Result<(), TestError> {
let mut metadata = Metadata::new();
let limits = Limits::new(2, 5);
assert!(metadata
.insert_with_limits(Name::new("1")?, "0".to_owned().into(), limits)
.is_ok());
assert!(metadata
.insert_with_limits(Name::new("2")?, "0".to_owned().into(), limits)
.is_ok());
assert!(metadata
.insert_with_limits(Name::new("2")?, "1".to_owned().into(), limits)
.is_ok());
assert!(metadata
.insert_with_limits(Name::new("3")?, "0".to_owned().into(), limits)
.is_err());
Ok(())
}
}
| 32.522427 | 115 | 0.561739 |
91d22e5afd04f518a717981c922f49bfbdeeec03
| 1,252 |
/* Copyright (c) Fortanix, Inc.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![cfg_attr(not(feature="crypto-openssl"),allow(unused))]
use super::*;
const N: &'static [u8] = include_bytes!("../../tests/data/sig1.key_n.bin");
const KEY: &'static [u8] = include_bytes!("../../tests/data/sig1.key.pem");
const H: &'static [u8] = include_bytes!("../../tests/data/sig1.data.bin");
const S: &'static [u8] = include_bytes!("../../tests/data/sig1.sig.bin");
const Q1: &'static [u8] = include_bytes!("../../tests/data/sig1.q1.bin");
const Q2: &'static [u8] = include_bytes!("../../tests/data/sig1.q2.bin");
fn test_rsa<K: SgxRsaOps>(key: &K) {
assert_eq!(key.len(), 3072);
assert_eq!(&key.n()[..], N);
assert_eq!(&key.e()[..], [3]);
let (sig, q1, q2) = key.sign_sha256_pkcs1v1_5_with_q1_q2(H).unwrap();
assert_eq!(&sig[..], S);
assert_eq!(&q1[..], Q1);
assert_eq!(&q2[..], Q2);
}
#[cfg(feature = "crypto-openssl")]
#[test]
fn openssl_rsa() {
use openssl::pkey::PKey;
let key = PKey::private_key_from_pem(KEY).unwrap();
test_rsa(&*key.rsa().unwrap())
}
| 34.777778 | 75 | 0.619808 |
90f7ecf66d33b5f7773a0ea4be077fd76a5fff1f
| 65 |
pub use crate::sync::GsFence;
pub use crate::sync::GsSemaphore;
| 16.25 | 33 | 0.738462 |
f5af9fcc7a0d9067839063a59f6faeaa48cb72fc
| 12,106 |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use failure::prelude::*;
use ir_to_bytecode_syntax::ast::QualifiedModuleIdent;
use libra_types::account_address::AccountAddress;
use libra_types::identifier::Identifier;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::ops::Bound;
use vm::file_format::{
CodeOffset, FieldDefinitionIndex, FunctionDefinitionIndex, StructDefinitionIndex, TableIndex,
};
use vm::internals::ModuleIndex;
//***************************************************************************
// Source location mapping
//***************************************************************************
pub type SourceMap<Location> = Vec<ModuleSourceMap<Location>>;
pub type SourceName<Location> = (Identifier, Location);
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct StructSourceMap<Location: Clone + Eq> {
/// The source declaration location of the struct
pub decl_location: Location,
/// Important: type parameters need to be added in the order of their declaration
pub type_parameters: Vec<SourceName<Location>>,
/// Note that fields to a struct source map need to be added in the order of the fields in the
/// struct definition.
pub fields: Vec<Location>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FunctionSourceMap<Location: Clone + Eq> {
/// The source location for the definition of this entire function. Note that in certain
/// instances this will have no valid source location e.g. the "main" function for modules that
/// are treated as programs are synthesized and therefore have no valid source location.
pub decl_location: Location,
/// Note that type parameters need to be added in the order of their declaration
pub type_parameters: Vec<SourceName<Location>>,
/// The index into the vector is the locals index. The corresponding `(Identifier, Location)` tuple
/// is the name and location of the local.
pub locals: Vec<SourceName<Location>>,
/// The source location map for the function body.
pub code_map: BTreeMap<CodeOffset, Location>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ModuleSourceMap<Location: Clone + Eq> {
/// The name <address.module_name> for module that this source map is for
pub module_name: (AccountAddress, Identifier),
// A mapping of StructDefinitionIndex to source map for each struct/resource
struct_map: BTreeMap<TableIndex, StructSourceMap<Location>>,
// A mapping of FunctionDefinitionIndex to the soure map for that function.
function_map: BTreeMap<TableIndex, FunctionSourceMap<Location>>,
}
impl<Location: Clone + Eq> StructSourceMap<Location> {
pub fn new(decl_location: Location) -> Self {
Self {
decl_location,
type_parameters: Vec::new(),
fields: Vec::new(),
}
}
pub fn add_type_parameter(&mut self, type_name: SourceName<Location>) {
self.type_parameters.push(type_name)
}
pub fn get_type_parameter_name(
&self,
type_parameter_idx: usize,
) -> Option<SourceName<Location>> {
self.type_parameters.get(type_parameter_idx).cloned()
}
pub fn add_field_location(&mut self, field_loc: Location) {
self.fields.push(field_loc)
}
pub fn get_field_location(&self, field_index: FieldDefinitionIndex) -> Option<Location> {
self.fields.get(field_index.into_index()).cloned()
}
}
impl<Location: Clone + Eq> FunctionSourceMap<Location> {
pub fn new(decl_location: Location) -> Self {
Self {
decl_location,
type_parameters: Vec::new(),
locals: Vec::new(),
code_map: BTreeMap::new(),
}
}
pub fn add_type_parameter(&mut self, type_name: SourceName<Location>) {
self.type_parameters.push(type_name)
}
pub fn get_type_parameter_name(
&self,
type_parameter_idx: usize,
) -> Option<SourceName<Location>> {
self.type_parameters.get(type_parameter_idx).cloned()
}
/// A single source-level instruction may possibly map to a number of bytecode instructions. In
/// order to not store a location for each instruction, we instead use a BTreeMap to represent
/// a segment map (holding the left-hand-sides of each segment). Thus, an instruction
/// sequence is always marked from its starting point. To determine what part of the source
/// code corresponds to a given `CodeOffset` we query to find the element that is the largest
/// number less than or equal to the query. This will give us the location for that bytecode
/// range.
pub fn add_code_mapping(&mut self, start_offset: CodeOffset, location: Location) {
let possible_segment = self.get_code_location(start_offset);
match possible_segment.map(|other_location| other_location != location) {
Some(true) | None => {
self.code_map.insert(start_offset, location);
}
_ => (),
};
}
// Not that it is important that locations be added in order.
pub fn add_local_mapping(&mut self, name: SourceName<Location>) {
self.locals.push(name);
}
/// Recall that we are using a segment tree. We therefore lookup the location for the code
/// offset by performing a range query for the largest number less than or equal to the code
/// offset passed in.
pub fn get_code_location(&self, code_offset: CodeOffset) -> Option<Location> {
self.code_map
.range((Bound::Unbounded, Bound::Included(&code_offset)))
.next_back()
.map(|(_, vl)| vl.clone())
}
pub fn get_local_name(&self, local_index: u64) -> Option<SourceName<Location>> {
self.locals.get(local_index as usize).cloned()
}
}
impl<Location: Clone + Eq> ModuleSourceMap<Location> {
pub fn new(module_name: QualifiedModuleIdent) -> Self {
Self {
module_name: (module_name.address, module_name.name.into_inner()),
struct_map: BTreeMap::new(),
function_map: BTreeMap::new(),
}
}
pub fn add_top_level_function_mapping(
&mut self,
fdef_idx: FunctionDefinitionIndex,
location: Location,
) -> Result<()> {
match self.function_map.insert(fdef_idx.0, FunctionSourceMap::new(location)) {
None => Ok(()),
Some(_) => Err(format_err!(
"Multiple functions at same function definition index encountered when constructing source map"
)),
}
}
pub fn add_function_type_parameter_mapping(
&mut self,
fdef_idx: FunctionDefinitionIndex,
name: SourceName<Location>,
) -> Result<()> {
let func_entry = self.function_map.get_mut(&fdef_idx.0).ok_or_else(|| {
format_err!("Tried to add function type parameter mapping to undefined function index")
})?;
func_entry.add_type_parameter(name);
Ok(())
}
pub fn get_function_type_parameter_name(
&self,
fdef_idx: FunctionDefinitionIndex,
type_parameter_idx: usize,
) -> Result<SourceName<Location>> {
self.function_map
.get(&fdef_idx.0)
.and_then(|function_source_map| {
function_source_map.get_type_parameter_name(type_parameter_idx)
})
.ok_or_else(|| format_err!("Unable to get function type parameter name"))
}
pub fn add_code_mapping(
&mut self,
function_definition_index: FunctionDefinitionIndex,
start_offset: CodeOffset,
location: Location,
) -> Result<()> {
let func_entry = self
.function_map
.get_mut(&function_definition_index.0)
.ok_or_else(|| format_err!("Tried to add code mapping to undefined function index"))?;
func_entry.add_code_mapping(start_offset, location);
Ok(())
}
/// Given a function definition and a code offset within that function definition, this returns
/// the location in the source code associated with the instruction at that offset.
pub fn get_code_location(
&self,
function_definition_index: FunctionDefinitionIndex,
offset: CodeOffset,
) -> Result<Location> {
self.function_map
.get(&function_definition_index.0)
.and_then(|function_source_map| function_source_map.get_code_location(offset))
.ok_or_else(|| format_err!("Tried to get code location from undefined function index"))
}
pub fn add_local_mapping(
&mut self,
fdef_idx: FunctionDefinitionIndex,
name: SourceName<Location>,
) -> Result<()> {
let func_entry = self
.function_map
.get_mut(&fdef_idx.0)
.ok_or_else(|| format_err!("Tried to add local mapping to undefined function index"))?;
func_entry.add_local_mapping(name);
Ok(())
}
pub fn get_local_name(
&self,
fdef_idx: FunctionDefinitionIndex,
index: u64,
) -> Result<SourceName<Location>> {
self.function_map
.get(&fdef_idx.0)
.and_then(|function_source_map| function_source_map.get_local_name(index))
.ok_or_else(|| format_err!("Tried to get local name at undefined function index"))
}
pub fn add_top_level_struct_mapping(
&mut self,
struct_def_idx: StructDefinitionIndex,
location: Location,
) -> Result<()> {
match self.struct_map.insert(struct_def_idx.0, StructSourceMap::new(location)) {
None => Ok(()),
Some(_) => Err(format_err!(
"Multiple structs at same struct definition index encountered when constructing source map"
)),
}
}
pub fn add_struct_field_mapping(
&mut self,
struct_def_idx: StructDefinitionIndex,
location: Location,
) -> Result<()> {
let struct_entry = self
.struct_map
.get_mut(&struct_def_idx.0)
.ok_or_else(|| format_err!("Tried to add file mapping to undefined struct index"))?;
struct_entry.add_field_location(location);
Ok(())
}
pub fn get_struct_field_name(
&self,
struct_def_idx: StructDefinitionIndex,
field_idx: FieldDefinitionIndex,
) -> Option<Location> {
self.struct_map
.get(&struct_def_idx.0)
.and_then(|struct_source_map| struct_source_map.get_field_location(field_idx))
}
pub fn add_struct_type_parameter_mapping(
&mut self,
fdef_idx: StructDefinitionIndex,
name: SourceName<Location>,
) -> Result<()> {
let struct_entry = self.struct_map.get_mut(&fdef_idx.0).ok_or_else(|| {
format_err!("Tried to add function type parameter mapping to undefined function index")
})?;
struct_entry.add_type_parameter(name);
Ok(())
}
pub fn get_struct_type_parameter_name(
&self,
fdef_idx: StructDefinitionIndex,
type_parameter_idx: usize,
) -> Result<SourceName<Location>> {
self.struct_map
.get(&fdef_idx.0)
.and_then(|struct_source_map| {
struct_source_map.get_type_parameter_name(type_parameter_idx)
})
.ok_or_else(|| format_err!("Unable to get function type parameter name"))
}
pub fn get_function_source_map(
&self,
fdef_idx: FunctionDefinitionIndex,
) -> Result<&FunctionSourceMap<Location>> {
self.function_map
.get(&fdef_idx.0)
.ok_or_else(|| format_err!("Unable to get function source map"))
}
pub fn get_struct_source_map(
&self,
fdef_idx: StructDefinitionIndex,
) -> Result<&StructSourceMap<Location>> {
self.struct_map
.get(&fdef_idx.0)
.ok_or_else(|| format_err!("Unable to get struct source map"))
}
}
| 36.684848 | 115 | 0.639352 |
0e14e2196caf00a47d3de713f8a3ba46cd153053
| 28,550 |
// Error messages for EXXXX errors. Each message should start and end with a
// new line, and be wrapped to 80 characters. In vim you can `:set tw=80` and
// use `gq` to wrap paragraphs. Use `:set tw=0` to disable.
//
// /!\ IMPORTANT /!\
//
// Error messages' format must follow the RFC 1567 available here:
// https://github.com/rust-lang/rfcs/pull/1567
register_diagnostics! {
E0001: include_str!("./error_codes/E0001.md"),
E0002: include_str!("./error_codes/E0002.md"),
E0004: include_str!("./error_codes/E0004.md"),
E0005: include_str!("./error_codes/E0005.md"),
E0007: include_str!("./error_codes/E0007.md"),
E0009: include_str!("./error_codes/E0009.md"),
E0010: include_str!("./error_codes/E0010.md"),
E0013: include_str!("./error_codes/E0013.md"),
E0014: include_str!("./error_codes/E0014.md"),
E0015: include_str!("./error_codes/E0015.md"),
E0019: include_str!("./error_codes/E0019.md"),
E0023: include_str!("./error_codes/E0023.md"),
E0025: include_str!("./error_codes/E0025.md"),
E0026: include_str!("./error_codes/E0026.md"),
E0027: include_str!("./error_codes/E0027.md"),
E0029: include_str!("./error_codes/E0029.md"),
E0030: include_str!("./error_codes/E0030.md"),
E0033: include_str!("./error_codes/E0033.md"),
E0034: include_str!("./error_codes/E0034.md"),
E0038: include_str!("./error_codes/E0038.md"),
E0040: include_str!("./error_codes/E0040.md"),
E0044: include_str!("./error_codes/E0044.md"),
E0045: include_str!("./error_codes/E0045.md"),
E0046: include_str!("./error_codes/E0046.md"),
E0049: include_str!("./error_codes/E0049.md"),
E0050: include_str!("./error_codes/E0050.md"),
E0053: include_str!("./error_codes/E0053.md"),
E0054: include_str!("./error_codes/E0054.md"),
E0055: include_str!("./error_codes/E0055.md"),
E0057: include_str!("./error_codes/E0057.md"),
E0059: include_str!("./error_codes/E0059.md"),
E0060: include_str!("./error_codes/E0060.md"),
E0061: include_str!("./error_codes/E0061.md"),
E0062: include_str!("./error_codes/E0062.md"),
E0063: include_str!("./error_codes/E0063.md"),
E0067: include_str!("./error_codes/E0067.md"),
E0069: include_str!("./error_codes/E0069.md"),
E0070: include_str!("./error_codes/E0070.md"),
E0071: include_str!("./error_codes/E0071.md"),
E0072: include_str!("./error_codes/E0072.md"),
E0073: include_str!("./error_codes/E0073.md"),
E0074: include_str!("./error_codes/E0074.md"),
E0075: include_str!("./error_codes/E0075.md"),
E0076: include_str!("./error_codes/E0076.md"),
E0077: include_str!("./error_codes/E0077.md"),
E0080: include_str!("./error_codes/E0080.md"),
E0081: include_str!("./error_codes/E0081.md"),
E0084: include_str!("./error_codes/E0084.md"),
E0087: include_str!("./error_codes/E0087.md"),
E0088: include_str!("./error_codes/E0088.md"),
E0089: include_str!("./error_codes/E0089.md"),
E0090: include_str!("./error_codes/E0090.md"),
E0091: include_str!("./error_codes/E0091.md"),
E0092: include_str!("./error_codes/E0092.md"),
E0093: include_str!("./error_codes/E0093.md"),
E0094: include_str!("./error_codes/E0094.md"),
E0106: include_str!("./error_codes/E0106.md"),
E0107: include_str!("./error_codes/E0107.md"),
E0109: include_str!("./error_codes/E0109.md"),
E0110: include_str!("./error_codes/E0110.md"),
E0116: include_str!("./error_codes/E0116.md"),
E0117: include_str!("./error_codes/E0117.md"),
E0118: include_str!("./error_codes/E0118.md"),
E0119: include_str!("./error_codes/E0119.md"),
E0120: include_str!("./error_codes/E0120.md"),
E0121: include_str!("./error_codes/E0121.md"),
E0124: include_str!("./error_codes/E0124.md"),
E0128: include_str!("./error_codes/E0128.md"),
E0130: include_str!("./error_codes/E0130.md"),
E0131: include_str!("./error_codes/E0131.md"),
E0132: include_str!("./error_codes/E0132.md"),
E0133: include_str!("./error_codes/E0133.md"),
E0136: include_str!("./error_codes/E0136.md"),
E0137: include_str!("./error_codes/E0137.md"),
E0138: include_str!("./error_codes/E0138.md"),
E0139: include_str!("./error_codes/E0139.md"),
E0152: include_str!("./error_codes/E0152.md"),
E0154: include_str!("./error_codes/E0154.md"),
E0158: include_str!("./error_codes/E0158.md"),
E0161: include_str!("./error_codes/E0161.md"),
E0162: include_str!("./error_codes/E0162.md"),
E0164: include_str!("./error_codes/E0164.md"),
E0165: include_str!("./error_codes/E0165.md"),
E0170: include_str!("./error_codes/E0170.md"),
E0178: include_str!("./error_codes/E0178.md"),
E0184: include_str!("./error_codes/E0184.md"),
E0185: include_str!("./error_codes/E0185.md"),
E0186: include_str!("./error_codes/E0186.md"),
E0191: include_str!("./error_codes/E0191.md"),
E0192: include_str!("./error_codes/E0192.md"),
E0193: include_str!("./error_codes/E0193.md"),
E0195: include_str!("./error_codes/E0195.md"),
E0197: include_str!("./error_codes/E0197.md"),
E0198: include_str!("./error_codes/E0198.md"),
E0199: include_str!("./error_codes/E0199.md"),
E0200: include_str!("./error_codes/E0200.md"),
E0201: include_str!("./error_codes/E0201.md"),
E0202: include_str!("./error_codes/E0202.md"),
E0203: include_str!("./error_codes/E0203.md"),
E0204: include_str!("./error_codes/E0204.md"),
E0205: include_str!("./error_codes/E0205.md"),
E0206: include_str!("./error_codes/E0206.md"),
E0207: include_str!("./error_codes/E0207.md"),
E0210: include_str!("./error_codes/E0210.md"),
E0211: include_str!("./error_codes/E0211.md"),
E0214: include_str!("./error_codes/E0214.md"),
E0220: include_str!("./error_codes/E0220.md"),
E0221: include_str!("./error_codes/E0221.md"),
E0222: include_str!("./error_codes/E0222.md"),
E0223: include_str!("./error_codes/E0223.md"),
E0225: include_str!("./error_codes/E0225.md"),
E0229: include_str!("./error_codes/E0229.md"),
E0230: include_str!("./error_codes/E0230.md"),
E0231: include_str!("./error_codes/E0231.md"),
E0232: include_str!("./error_codes/E0232.md"),
E0243: include_str!("./error_codes/E0243.md"),
E0244: include_str!("./error_codes/E0244.md"),
E0251: include_str!("./error_codes/E0251.md"),
E0252: include_str!("./error_codes/E0252.md"),
E0253: include_str!("./error_codes/E0253.md"),
E0254: include_str!("./error_codes/E0254.md"),
E0255: include_str!("./error_codes/E0255.md"),
E0256: include_str!("./error_codes/E0256.md"),
E0259: include_str!("./error_codes/E0259.md"),
E0260: include_str!("./error_codes/E0260.md"),
E0261: include_str!("./error_codes/E0261.md"),
E0262: include_str!("./error_codes/E0262.md"),
E0263: include_str!("./error_codes/E0263.md"),
E0264: include_str!("./error_codes/E0264.md"),
E0267: include_str!("./error_codes/E0267.md"),
E0268: include_str!("./error_codes/E0268.md"),
E0271: include_str!("./error_codes/E0271.md"),
E0275: include_str!("./error_codes/E0275.md"),
E0276: include_str!("./error_codes/E0276.md"),
E0277: include_str!("./error_codes/E0277.md"),
E0281: include_str!("./error_codes/E0281.md"),
E0282: include_str!("./error_codes/E0282.md"),
E0283: include_str!("./error_codes/E0283.md"),
E0284: include_str!("./error_codes/E0284.md"),
E0297: include_str!("./error_codes/E0297.md"),
E0301: include_str!("./error_codes/E0301.md"),
E0302: include_str!("./error_codes/E0302.md"),
E0303: include_str!("./error_codes/E0303.md"),
E0307: include_str!("./error_codes/E0307.md"),
E0308: include_str!("./error_codes/E0308.md"),
E0309: include_str!("./error_codes/E0309.md"),
E0310: include_str!("./error_codes/E0310.md"),
E0312: include_str!("./error_codes/E0312.md"),
E0317: include_str!("./error_codes/E0317.md"),
E0321: include_str!("./error_codes/E0321.md"),
E0322: include_str!("./error_codes/E0322.md"),
E0323: include_str!("./error_codes/E0323.md"),
E0324: include_str!("./error_codes/E0324.md"),
E0325: include_str!("./error_codes/E0325.md"),
E0326: include_str!("./error_codes/E0326.md"),
E0328: include_str!("./error_codes/E0328.md"),
E0329: include_str!("./error_codes/E0329.md"),
E0364: include_str!("./error_codes/E0364.md"),
E0365: include_str!("./error_codes/E0365.md"),
E0366: include_str!("./error_codes/E0366.md"),
E0367: include_str!("./error_codes/E0367.md"),
E0368: include_str!("./error_codes/E0368.md"),
E0369: include_str!("./error_codes/E0369.md"),
E0370: include_str!("./error_codes/E0370.md"),
E0371: include_str!("./error_codes/E0371.md"),
E0373: include_str!("./error_codes/E0373.md"),
E0374: include_str!("./error_codes/E0374.md"),
E0375: include_str!("./error_codes/E0375.md"),
E0376: include_str!("./error_codes/E0376.md"),
E0378: include_str!("./error_codes/E0378.md"),
E0379: include_str!("./error_codes/E0379.md"),
E0380: include_str!("./error_codes/E0380.md"),
E0381: include_str!("./error_codes/E0381.md"),
E0382: include_str!("./error_codes/E0382.md"),
E0383: include_str!("./error_codes/E0383.md"),
E0384: include_str!("./error_codes/E0384.md"),
E0386: include_str!("./error_codes/E0386.md"),
E0387: include_str!("./error_codes/E0387.md"),
E0388: include_str!("./error_codes/E0388.md"),
E0389: include_str!("./error_codes/E0389.md"),
E0390: include_str!("./error_codes/E0390.md"),
E0391: include_str!("./error_codes/E0391.md"),
E0392: include_str!("./error_codes/E0392.md"),
E0393: include_str!("./error_codes/E0393.md"),
E0398: include_str!("./error_codes/E0398.md"),
E0399: include_str!("./error_codes/E0399.md"),
E0401: include_str!("./error_codes/E0401.md"),
E0403: include_str!("./error_codes/E0403.md"),
E0404: include_str!("./error_codes/E0404.md"),
E0405: include_str!("./error_codes/E0405.md"),
E0407: include_str!("./error_codes/E0407.md"),
E0408: include_str!("./error_codes/E0408.md"),
E0409: include_str!("./error_codes/E0409.md"),
E0411: include_str!("./error_codes/E0411.md"),
E0412: include_str!("./error_codes/E0412.md"),
E0415: include_str!("./error_codes/E0415.md"),
E0416: include_str!("./error_codes/E0416.md"),
E0422: include_str!("./error_codes/E0422.md"),
E0423: include_str!("./error_codes/E0423.md"),
E0424: include_str!("./error_codes/E0424.md"),
E0425: include_str!("./error_codes/E0425.md"),
E0426: include_str!("./error_codes/E0426.md"),
E0428: include_str!("./error_codes/E0428.md"),
E0429: include_str!("./error_codes/E0429.md"),
E0430: include_str!("./error_codes/E0430.md"),
E0431: include_str!("./error_codes/E0431.md"),
E0432: include_str!("./error_codes/E0432.md"),
E0433: include_str!("./error_codes/E0433.md"),
E0434: include_str!("./error_codes/E0434.md"),
E0435: include_str!("./error_codes/E0435.md"),
E0436: include_str!("./error_codes/E0436.md"),
E0437: include_str!("./error_codes/E0437.md"),
E0438: include_str!("./error_codes/E0438.md"),
E0439: include_str!("./error_codes/E0439.md"),
E0445: include_str!("./error_codes/E0445.md"),
E0446: include_str!("./error_codes/E0446.md"),
E0447: include_str!("./error_codes/E0447.md"),
E0448: include_str!("./error_codes/E0448.md"),
E0449: include_str!("./error_codes/E0449.md"),
E0451: include_str!("./error_codes/E0451.md"),
E0452: include_str!("./error_codes/E0452.md"),
E0453: include_str!("./error_codes/E0453.md"),
E0454: include_str!("./error_codes/E0454.md"),
E0455: include_str!("./error_codes/E0455.md"),
E0458: include_str!("./error_codes/E0458.md"),
E0459: include_str!("./error_codes/E0459.md"),
E0463: include_str!("./error_codes/E0463.md"),
E0466: include_str!("./error_codes/E0466.md"),
E0468: include_str!("./error_codes/E0468.md"),
E0469: include_str!("./error_codes/E0469.md"),
E0477: include_str!("./error_codes/E0477.md"),
E0478: include_str!("./error_codes/E0478.md"),
E0491: include_str!("./error_codes/E0491.md"),
E0492: include_str!("./error_codes/E0492.md"),
E0493: include_str!("./error_codes/E0493.md"),
E0495: include_str!("./error_codes/E0495.md"),
E0496: include_str!("./error_codes/E0496.md"),
E0497: include_str!("./error_codes/E0497.md"),
E0499: include_str!("./error_codes/E0499.md"),
E0500: include_str!("./error_codes/E0500.md"),
E0501: include_str!("./error_codes/E0501.md"),
E0502: include_str!("./error_codes/E0502.md"),
E0503: include_str!("./error_codes/E0503.md"),
E0504: include_str!("./error_codes/E0504.md"),
E0505: include_str!("./error_codes/E0505.md"),
E0506: include_str!("./error_codes/E0506.md"),
E0507: include_str!("./error_codes/E0507.md"),
E0508: include_str!("./error_codes/E0508.md"),
E0509: include_str!("./error_codes/E0509.md"),
E0510: include_str!("./error_codes/E0510.md"),
E0511: include_str!("./error_codes/E0511.md"),
E0512: include_str!("./error_codes/E0512.md"),
E0515: include_str!("./error_codes/E0515.md"),
E0516: include_str!("./error_codes/E0516.md"),
E0517: include_str!("./error_codes/E0517.md"),
E0518: include_str!("./error_codes/E0518.md"),
E0520: include_str!("./error_codes/E0520.md"),
E0522: include_str!("./error_codes/E0522.md"),
E0524: include_str!("./error_codes/E0524.md"),
E0525: include_str!("./error_codes/E0525.md"),
E0527: include_str!("./error_codes/E0527.md"),
E0528: include_str!("./error_codes/E0528.md"),
E0529: include_str!("./error_codes/E0529.md"),
E0530: include_str!("./error_codes/E0530.md"),
E0531: include_str!("./error_codes/E0531.md"),
E0532: include_str!("./error_codes/E0532.md"),
E0533: include_str!("./error_codes/E0533.md"),
E0534: include_str!("./error_codes/E0534.md"),
E0535: include_str!("./error_codes/E0535.md"),
E0536: include_str!("./error_codes/E0536.md"),
E0537: include_str!("./error_codes/E0537.md"),
E0538: include_str!("./error_codes/E0538.md"),
E0541: include_str!("./error_codes/E0541.md"),
E0550: include_str!("./error_codes/E0550.md"),
E0551: include_str!("./error_codes/E0551.md"),
E0552: include_str!("./error_codes/E0552.md"),
E0554: include_str!("./error_codes/E0554.md"),
E0556: include_str!("./error_codes/E0556.md"),
E0557: include_str!("./error_codes/E0557.md"),
E0559: include_str!("./error_codes/E0559.md"),
E0560: include_str!("./error_codes/E0560.md"),
E0561: include_str!("./error_codes/E0561.md"),
E0562: include_str!("./error_codes/E0562.md"),
E0565: include_str!("./error_codes/E0565.md"),
E0566: include_str!("./error_codes/E0566.md"),
E0567: include_str!("./error_codes/E0567.md"),
E0568: include_str!("./error_codes/E0568.md"),
E0569: include_str!("./error_codes/E0569.md"),
E0570: include_str!("./error_codes/E0570.md"),
E0571: include_str!("./error_codes/E0571.md"),
E0572: include_str!("./error_codes/E0572.md"),
E0573: include_str!("./error_codes/E0573.md"),
E0574: include_str!("./error_codes/E0574.md"),
E0575: include_str!("./error_codes/E0575.md"),
E0576: include_str!("./error_codes/E0576.md"),
E0577: include_str!("./error_codes/E0577.md"),
E0578: include_str!("./error_codes/E0578.md"),
E0579: include_str!("./error_codes/E0579.md"),
E0580: include_str!("./error_codes/E0580.md"),
E0581: include_str!("./error_codes/E0581.md"),
E0582: include_str!("./error_codes/E0582.md"),
E0583: include_str!("./error_codes/E0583.md"),
E0584: include_str!("./error_codes/E0584.md"),
E0585: include_str!("./error_codes/E0585.md"),
E0586: include_str!("./error_codes/E0586.md"),
E0587: include_str!("./error_codes/E0587.md"),
E0588: include_str!("./error_codes/E0588.md"),
E0589: include_str!("./error_codes/E0589.md"),
E0590: include_str!("./error_codes/E0590.md"),
E0591: include_str!("./error_codes/E0591.md"),
E0592: include_str!("./error_codes/E0592.md"),
E0593: include_str!("./error_codes/E0593.md"),
E0594: include_str!("./error_codes/E0594.md"),
E0595: include_str!("./error_codes/E0595.md"),
E0596: include_str!("./error_codes/E0596.md"),
E0597: include_str!("./error_codes/E0597.md"),
E0599: include_str!("./error_codes/E0599.md"),
E0600: include_str!("./error_codes/E0600.md"),
E0601: include_str!("./error_codes/E0601.md"),
E0602: include_str!("./error_codes/E0602.md"),
E0603: include_str!("./error_codes/E0603.md"),
E0604: include_str!("./error_codes/E0604.md"),
E0605: include_str!("./error_codes/E0605.md"),
E0606: include_str!("./error_codes/E0606.md"),
E0607: include_str!("./error_codes/E0607.md"),
E0608: include_str!("./error_codes/E0608.md"),
E0609: include_str!("./error_codes/E0609.md"),
E0610: include_str!("./error_codes/E0610.md"),
E0614: include_str!("./error_codes/E0614.md"),
E0615: include_str!("./error_codes/E0615.md"),
E0616: include_str!("./error_codes/E0616.md"),
E0617: include_str!("./error_codes/E0617.md"),
E0618: include_str!("./error_codes/E0618.md"),
E0619: include_str!("./error_codes/E0619.md"),
E0620: include_str!("./error_codes/E0620.md"),
E0621: include_str!("./error_codes/E0621.md"),
E0622: include_str!("./error_codes/E0622.md"),
E0623: include_str!("./error_codes/E0623.md"),
E0624: include_str!("./error_codes/E0624.md"),
E0626: include_str!("./error_codes/E0626.md"),
E0627: include_str!("./error_codes/E0627.md"),
E0631: include_str!("./error_codes/E0631.md"),
E0633: include_str!("./error_codes/E0633.md"),
E0635: include_str!("./error_codes/E0635.md"),
E0636: include_str!("./error_codes/E0636.md"),
E0637: include_str!("./error_codes/E0637.md"),
E0638: include_str!("./error_codes/E0638.md"),
E0639: include_str!("./error_codes/E0639.md"),
E0641: include_str!("./error_codes/E0641.md"),
E0642: include_str!("./error_codes/E0642.md"),
E0643: include_str!("./error_codes/E0643.md"),
E0644: include_str!("./error_codes/E0644.md"),
E0646: include_str!("./error_codes/E0646.md"),
E0647: include_str!("./error_codes/E0647.md"),
E0648: include_str!("./error_codes/E0648.md"),
E0658: include_str!("./error_codes/E0658.md"),
E0659: include_str!("./error_codes/E0659.md"),
E0660: include_str!("./error_codes/E0660.md"),
E0661: include_str!("./error_codes/E0661.md"),
E0662: include_str!("./error_codes/E0662.md"),
E0663: include_str!("./error_codes/E0663.md"),
E0664: include_str!("./error_codes/E0664.md"),
E0665: include_str!("./error_codes/E0665.md"),
E0666: include_str!("./error_codes/E0666.md"),
E0668: include_str!("./error_codes/E0668.md"),
E0669: include_str!("./error_codes/E0669.md"),
E0670: include_str!("./error_codes/E0670.md"),
E0671: include_str!("./error_codes/E0671.md"),
E0689: include_str!("./error_codes/E0689.md"),
E0690: include_str!("./error_codes/E0690.md"),
E0691: include_str!("./error_codes/E0691.md"),
E0692: include_str!("./error_codes/E0692.md"),
E0695: include_str!("./error_codes/E0695.md"),
E0697: include_str!("./error_codes/E0697.md"),
E0698: include_str!("./error_codes/E0698.md"),
E0699: include_str!("./error_codes/E0699.md"),
E0700: include_str!("./error_codes/E0700.md"),
E0701: include_str!("./error_codes/E0701.md"),
E0704: include_str!("./error_codes/E0704.md"),
E0705: include_str!("./error_codes/E0705.md"),
E0706: include_str!("./error_codes/E0706.md"),
E0712: include_str!("./error_codes/E0712.md"),
E0713: include_str!("./error_codes/E0713.md"),
E0714: include_str!("./error_codes/E0714.md"),
E0715: include_str!("./error_codes/E0715.md"),
E0716: include_str!("./error_codes/E0716.md"),
E0718: include_str!("./error_codes/E0718.md"),
E0719: include_str!("./error_codes/E0719.md"),
E0720: include_str!("./error_codes/E0720.md"),
E0723: include_str!("./error_codes/E0723.md"),
E0725: include_str!("./error_codes/E0725.md"),
E0727: include_str!("./error_codes/E0727.md"),
E0728: include_str!("./error_codes/E0728.md"),
E0729: include_str!("./error_codes/E0729.md"),
E0730: include_str!("./error_codes/E0730.md"),
E0731: include_str!("./error_codes/E0731.md"),
E0732: include_str!("./error_codes/E0732.md"),
E0733: include_str!("./error_codes/E0733.md"),
E0734: include_str!("./error_codes/E0734.md"),
E0735: include_str!("./error_codes/E0735.md"),
E0736: include_str!("./error_codes/E0736.md"),
E0737: include_str!("./error_codes/E0737.md"),
E0738: include_str!("./error_codes/E0738.md"),
E0739: include_str!("./error_codes/E0739.md"),
E0740: include_str!("./error_codes/E0740.md"),
E0741: include_str!("./error_codes/E0741.md"),
E0742: include_str!("./error_codes/E0742.md"),
E0743: include_str!("./error_codes/E0743.md"),
E0744: include_str!("./error_codes/E0744.md"),
E0745: include_str!("./error_codes/E0745.md"),
E0746: include_str!("./error_codes/E0746.md"),
E0747: include_str!("./error_codes/E0747.md"),
E0748: include_str!("./error_codes/E0748.md"),
;
// E0006, // merged with E0005
// E0008, // cannot bind by-move into a pattern guard
// E0035, merged into E0087/E0089
// E0036, merged into E0087/E0089
// E0068,
// E0085,
// E0086,
// E0101, // replaced with E0282
// E0102, // replaced with E0282
// E0103,
// E0104,
// E0122, // bounds in type aliases are ignored, turned into proper lint
// E0123,
// E0127,
// E0129,
// E0134,
// E0135,
// E0141,
// E0153, unused error code
// E0157, unused error code
// E0159, // use of trait `{}` as struct constructor
// E0163, // merged into E0071
// E0167,
// E0168,
// E0172, // non-trait found in a type sum, moved to resolve
// E0173, // manual implementations of unboxed closure traits are experimental
// E0174,
// E0182, // merged into E0229
E0183,
// E0187, // cannot infer the kind of the closure
// E0188, // can not cast an immutable reference to a mutable pointer
// E0189, // deprecated: can only cast a boxed pointer to a boxed object
// E0190, // deprecated: can only cast a &-pointer to an &-object
// E0194, // merged into E0403
// E0196, // cannot determine a type for this closure
E0208,
// E0209, // builtin traits can only be implemented on structs or enums
E0212, // cannot extract an associated type from a higher-ranked trait bound
// E0213, // associated types are not accepted in this context
// E0215, // angle-bracket notation is not stable with `Fn`
// E0216, // parenthetical notation is only stable with `Fn`
// E0217, // ambiguous associated type, defined in multiple supertraits
// E0218, // no associated type defined
// E0219, // associated type defined in higher-ranked supertrait
E0224, // at least one non-builtin train is required for an object type
E0226, // only a single explicit lifetime bound is permitted
E0227, // ambiguous lifetime bound, explicit lifetime bound required
E0228, // explicit lifetime bound required
// E0233,
// E0234,
// E0235, // structure constructor specifies a structure of type but
// E0236, // no lang item for range syntax
// E0237, // no lang item for range syntax
// E0238, // parenthesized parameters may only be used with a trait
// E0239, // `next` method of `Iterator` trait has unexpected type
// E0240,
// E0241,
// E0242,
// E0245, // not a trait
// E0246, // invalid recursive type
// E0247,
// E0248, // value used as a type, now reported earlier during resolution
// as E0412
// E0249,
// E0257,
// E0258,
// E0272, // on_unimplemented #0
// E0273, // on_unimplemented #1
// E0274, // on_unimplemented #2
// E0278, // requirement is not satisfied
E0279, // requirement is not satisfied
E0280, // requirement is not satisfied
// E0285, // overflow evaluation builtin bounds
// E0296, // replaced with a generic attribute input check
// E0298, // cannot compare constants
// E0299, // mismatched types between arms
// E0300, // unexpanded macro
// E0304, // expected signed integer constant
// E0305, // expected constant
E0311, // thing may not live long enough
E0313, // lifetime of borrowed pointer outlives lifetime of captured
// variable
E0314, // closure outlives stack frame
E0315, // cannot invoke closure outside of its lifetime
E0316, // nested quantification of lifetimes
// E0319, // trait impls for defaulted traits allowed just for structs/enums
E0320, // recursive overflow during dropck
// E0372, // coherence not object safe
E0377, // the trait `CoerceUnsized` may only be implemented for a coercion
// between structures with the same definition
// E0385, // {} in an aliasable location
// E0402, // cannot use an outer type parameter in this context
// E0406, merged into 420
// E0410, merged into 408
// E0413, merged into 530
// E0414, merged into 530
// E0417, merged into 532
// E0418, merged into 532
// E0419, merged into 531
// E0420, merged into 532
// E0421, merged into 531
// E0427, merged into 530
E0456, // plugin `..` is not available for triple `..`
E0457, // plugin `..` only found in rlib format, but must be available...
E0460, // found possibly newer version of crate `..`
E0461, // couldn't find crate `..` with expected target triple ..
E0462, // found staticlib `..` instead of rlib or dylib
E0464, // multiple matching crates for `..`
E0465, // multiple .. candidates for `..` found
// E0467, removed
// E0470, removed
// E0471, // constant evaluation error (in pattern)
E0472, // asm! is unsupported on this target
E0473, // dereference of reference outside its lifetime
E0474, // captured variable `..` does not outlive the enclosing closure
E0475, // index of slice outside its lifetime
E0476, // lifetime of the source pointer does not outlive lifetime bound...
E0479, // the type `..` (provided as the value of a type parameter) is...
E0480, // lifetime of method receiver does not outlive the method call
E0481, // lifetime of function argument does not outlive the function call
E0482, // lifetime of return value does not outlive the function call
E0483, // lifetime of operand does not outlive the operation
E0484, // reference is not valid at the time of borrow
E0485, // automatically reference is not valid at the time of borrow
E0486, // type of expression contains references that are not valid during..
E0487, // unsafe use of destructor: destructor might be called while...
E0488, // lifetime of variable does not enclose its declaration
E0489, // type/lifetime parameter not in scope here
E0490, // a value of type `..` is borrowed for too long
E0498, // malformed plugin attribute
E0514, // metadata version mismatch
E0519, // local crate and dependency have same (crate-name, disambiguator)
// two dependencies have same (crate-name, disambiguator) but different SVH
E0521, // borrowed data escapes outside of closure
E0523,
// E0526, // shuffle indices are not constant
E0539, // incorrect meta item
E0540, // multiple rustc_deprecated attributes
E0542, // missing 'since'
E0543, // missing 'reason'
E0544, // multiple stability levels
E0545, // incorrect 'issue'
E0546, // missing 'feature'
E0547, // missing 'issue'
// E0548, // replaced with a generic attribute input check
// rustc_deprecated attribute must be paired with either stable or unstable
// attribute
E0549,
E0553, // multiple rustc_const_unstable attributes
// E0555, // replaced with a generic attribute input check
// E0558, // replaced with a generic attribute input check
// E0563, // cannot determine a type for this `impl Trait` removed in 6383de15
// E0564, // only named lifetimes are allowed in `impl Trait`,
// but `{}` was found in the type `{}`
// E0598, // lifetime of {} is too short to guarantee its contents can be...
// E0611, // merged into E0616
// E0612, // merged into E0609
// E0613, // Removed (merged with E0609)
E0625, // thread-local statics cannot be accessed at compile-time
E0628, // generators cannot have explicit parameters
E0629, // missing 'feature' (rustc_const_unstable)
// rustc_const_unstable attribute must be paired with stable/unstable
// attribute
E0630,
E0632, // cannot provide explicit generic arguments when `impl Trait` is
// used in argument position
E0634, // type has conflicting packed representaton hints
E0640, // infer outlives requirements
// E0645, // trait aliases not finished
E0657, // `impl Trait` can only capture lifetimes bound at the fn level
E0667, // `impl Trait` in projections
E0687, // in-band lifetimes cannot be used in `fn`/`Fn` syntax
E0688, // in-band lifetimes cannot be mixed with explicit lifetime binders
E0693, // incorrect `repr(align)` attribute format
// E0694, // an unknown tool name found in scoped attributes
E0696, // `continue` pointing to a labeled block
// E0702, // replaced with a generic attribute input check
E0703, // invalid ABI
// E0707, // multiple elided lifetimes used in arguments of `async fn`
E0708, // `async` non-`move` closures with parameters are not currently
// supported
// E0709, // multiple different lifetimes used in arguments of `async fn`
E0710, // an unknown tool name found in scoped lint
E0711, // a feature has been declared with conflicting stability attributes
E0717, // rustc_promotable without stability attribute
// E0721, // `await` keyword
E0722, // Malformed `#[optimize]` attribute
E0724, // `#[ffi_returns_twice]` is only allowed in foreign functions
E0726, // non-explicit (not `'_`) elided lifetime in unsupported position
}
| 46.422764 | 80 | 0.712364 |
5bf01167bffdc31994b4f8eb0d55f0e4948f2194
| 1,712 |
/*!
This crate is where extra tests which don't belong in examples go.
*/
use testing_interface_0::{
TestingMod,TestingMod_Ref,ForTests,PrefixTypeMod0,
};
use abi_stable::{
export_root_module,
extern_fn_panic_handling,
prefix_type::PrefixTypeTrait,
traits::{IntoReprC},
std_types::{RStr,RBox,RVec,RArc, RString},
};
#[allow(unused_imports)]
use core_extensions::{SelfOps};
///////////////////////////////////////////////////////////////////////////////////
/// Exports the root module of this library.
///
/// LibHeader is used to check that the layout of `TextOpsMod` in this dynamic library
/// is compatible with the layout of it in the binary that loads this library.
#[export_root_module]
pub fn get_library() -> TestingMod_Ref {
TestingMod{
greeter,
for_tests,
prefix_types_tests:PrefixTypeMod0{
field_a:123,
}.leak_into_prefix(),
}.leak_into_prefix()
}
pub extern "C" fn greeter(name:RStr<'_>){
extern_fn_panic_handling!{
println!("Hello, {}!", name);
}
}
pub extern "C" fn for_tests()->ForTests{
extern_fn_panic_handling!{
let arc=RArc::new(RString::from("hello"));
::std::mem::forget(arc.clone());
let box_=RBox::new(10);
let vec_=RVec::from(vec!["world".into_c()]);
let string=RString::from("what the foo.");
ForTests{
arc_address:(&*arc) as *const _ as usize,
arc,
box_address:(&*box_) as *const _ as usize,
box_,
vec_address:vec_.as_ptr() as usize,
vec_,
string_address:string.as_ptr() as usize,
string,
}
}
}
| 25.552239 | 86 | 0.578855 |
f5004c0e406ff140d91147b329c70005969de460
| 24,609 |
//! A scheduler is initialized with a fixed number of workers. Each worker is
//! driven by a thread. Each worker has a "core" which contains data such as the
//! run queue and other state. When `block_in_place` is called, the worker's
//! "core" is handed off to a new thread allowing the scheduler to continue to
//! make progress while the originating thread blocks.
//!
//! # Shutdown
//!
//! Shutting down the runtime involves the following steps:
//!
//! 1. The Shared::close method is called. This closes the inject queue and
//! OwnedTasks instance and wakes up all worker threads.
//!
//! 2. Each worker thread observes the close signal next time it runs
//! Core::maintenance by checking whether the inject queue is closed.
//! The Core::is_shutdown flag is set to true.
//!
//! 3. The worker thread calls `pre_shutdown` in parallel. Here, the worker
//! will keep removing tasks from OwnedTasks until it is empty. No new
//! tasks can be pushed to the OwnedTasks during or after this step as it
//! was closed in step 1.
//!
//! 5. The workers call Shared::shutdown to enter the single-threaded phase of
//! shutdown. These calls will push their core to Shared::shutdown_cores,
//! and the last thread to push its core will finish the shutdown procedure.
//!
//! 6. The local run queue of each core is emptied, then the inject queue is
//! emptied.
//!
//! At this point, shutdown has completed. It is not possible for any of the
//! collections to contain any tasks at this point, as each collection was
//! closed first, then emptied afterwards.
//!
//! ## Spawns during shutdown
//!
//! When spawning tasks during shutdown, there are two cases:
//!
//! * The spawner observes the OwnedTasks being open, and the inject queue is
//! closed.
//! * The spawner observes the OwnedTasks being closed and doesn't check the
//! inject queue.
//!
//! The first case can only happen if the OwnedTasks::bind call happens before
//! or during step 1 of shutdown. In this case, the runtime will clean up the
//! task in step 3 of shutdown.
//!
//! In the latter case, the task was not spawned and the task is immediately
//! cancelled by the spawner.
//!
//! The correctness of shutdown requires both the inject queue and OwnedTasks
//! collection to have a closed bit. With a close bit on only the inject queue,
//! spawning could run in to a situation where a task is successfully bound long
//! after the runtime has shut down. With a close bit on only the OwnedTasks,
//! the first spawning situation could result in the notification being pushed
//! to the inject queue after step 6 of shutdown, which would leave a task in
//! the inject queue indefinitely. This would be a ref-count cycle and a memory
//! leak.
use crate::coop;
use crate::future::Future;
use crate::loom::rand::seed;
use crate::loom::sync::{Arc, Mutex};
use crate::park::{Park, Unpark};
use crate::runtime;
use crate::runtime::enter::EnterContext;
use crate::runtime::park::{Parker, Unparker};
use crate::runtime::task::{Inject, JoinHandle, OwnedTasks};
use crate::runtime::thread_pool::{AtomicCell, Idle};
use crate::runtime::{queue, task};
use crate::util::FastRand;
use std::cell::RefCell;
use std::time::Duration;
/// A scheduler worker
pub(super) struct Worker {
/// Reference to shared state
shared: Arc<Shared>,
/// Index holding this worker's remote state
index: usize,
/// Used to hand-off a worker's core to another thread.
core: AtomicCell<Core>,
}
/// Core data
struct Core {
/// Used to schedule bookkeeping tasks every so often.
tick: u8,
/// When a task is scheduled from a worker, it is stored in this slot. The
/// worker will check this slot for a task **before** checking the run
/// queue. This effectively results in the **last** scheduled task to be run
/// next (LIFO). This is an optimization for message passing patterns and
/// helps to reduce latency.
lifo_slot: Option<Notified>,
/// The worker-local run queue.
run_queue: queue::Local<Arc<Shared>>,
/// True if the worker is currently searching for more work. Searching
/// involves attempting to steal from other workers.
is_searching: bool,
/// True if the scheduler is being shutdown
is_shutdown: bool,
/// Parker
///
/// Stored in an `Option` as the parker is added / removed to make the
/// borrow checker happy.
park: Option<Parker>,
/// Fast random number generator.
rand: FastRand,
}
/// State shared across all workers
pub(super) struct Shared {
/// Per-worker remote state. All other workers have access to this and is
/// how they communicate between each other.
remotes: Box<[Remote]>,
/// Submit work to the scheduler while **not** currently on a worker thread.
inject: Inject<Arc<Shared>>,
/// Coordinates idle workers
idle: Idle,
/// Collection of all active tasks spawned onto this executor.
owned: OwnedTasks<Arc<Shared>>,
/// Cores that have observed the shutdown signal
///
/// The core is **not** placed back in the worker to avoid it from being
/// stolen by a thread that was spawned as part of `block_in_place`.
#[allow(clippy::vec_box)] // we're moving an already-boxed value
shutdown_cores: Mutex<Vec<Box<Core>>>,
}
/// Used to communicate with a worker from other threads.
struct Remote {
/// Steal tasks from this worker.
steal: queue::Steal<Arc<Shared>>,
/// Unparks the associated worker thread
unpark: Unparker,
}
/// Thread-local context
struct Context {
/// Worker
worker: Arc<Worker>,
/// Core data
core: RefCell<Option<Box<Core>>>,
}
/// Starts the workers
pub(crate) struct Launch(Vec<Arc<Worker>>);
/// Running a task may consume the core. If the core is still available when
/// running the task completes, it is returned. Otherwise, the worker will need
/// to stop processing.
type RunResult = Result<Box<Core>, ()>;
/// A task handle
type Task = task::Task<Arc<Shared>>;
/// A notified task handle
type Notified = task::Notified<Arc<Shared>>;
// Tracks thread-local state
scoped_thread_local!(static CURRENT: Context);
pub(super) fn create(size: usize, park: Parker) -> (Arc<Shared>, Launch) {
let mut cores = vec![];
let mut remotes = vec![];
// Create the local queues
for _ in 0..size {
let (steal, run_queue) = queue::local();
let park = park.clone();
let unpark = park.unpark();
cores.push(Box::new(Core {
tick: 0,
lifo_slot: None,
run_queue,
is_searching: false,
is_shutdown: false,
park: Some(park),
rand: FastRand::new(seed()),
}));
remotes.push(Remote { steal, unpark });
}
let shared = Arc::new(Shared {
remotes: remotes.into_boxed_slice(),
inject: Inject::new(),
idle: Idle::new(size),
owned: OwnedTasks::new(),
shutdown_cores: Mutex::new(vec![]),
});
let mut launch = Launch(vec![]);
for (index, core) in cores.drain(..).enumerate() {
launch.0.push(Arc::new(Worker {
shared: shared.clone(),
index,
core: AtomicCell::new(Some(core)),
}));
}
(shared, launch)
}
pub(crate) fn block_in_place<F, R>(f: F) -> R
where
F: FnOnce() -> R,
{
// Try to steal the worker core back
struct Reset(coop::Budget);
impl Drop for Reset {
fn drop(&mut self) {
CURRENT.with(|maybe_cx| {
if let Some(cx) = maybe_cx {
let core = cx.worker.core.take();
let mut cx_core = cx.core.borrow_mut();
assert!(cx_core.is_none());
*cx_core = core;
// Reset the task budget as we are re-entering the
// runtime.
coop::set(self.0);
}
});
}
}
let mut had_entered = false;
CURRENT.with(|maybe_cx| {
match (crate::runtime::enter::context(), maybe_cx.is_some()) {
(EnterContext::Entered { .. }, true) => {
// We are on a thread pool runtime thread, so we just need to
// set up blocking.
had_entered = true;
}
(EnterContext::Entered { allow_blocking }, false) => {
// We are on an executor, but _not_ on the thread pool. That is
// _only_ okay if we are in a thread pool runtime's block_on
// method:
if allow_blocking {
had_entered = true;
return;
} else {
// This probably means we are on the basic_scheduler or in a
// LocalSet, where it is _not_ okay to block.
panic!("can call blocking only when running on the multi-threaded runtime");
}
}
(EnterContext::NotEntered, true) => {
// This is a nested call to block_in_place (we already exited).
// All the necessary setup has already been done.
return;
}
(EnterContext::NotEntered, false) => {
// We are outside of the tokio runtime, so blocking is fine.
// We can also skip all of the thread pool blocking setup steps.
return;
}
}
let cx = maybe_cx.expect("no .is_some() == false cases above should lead here");
// Get the worker core. If none is set, then blocking is fine!
let core = match cx.core.borrow_mut().take() {
Some(core) => core,
None => return,
};
// The parker should be set here
assert!(core.park.is_some());
// In order to block, the core must be sent to another thread for
// execution.
//
// First, move the core back into the worker's shared core slot.
cx.worker.core.set(core);
// Next, clone the worker handle and send it to a new thread for
// processing.
//
// Once the blocking task is done executing, we will attempt to
// steal the core back.
let worker = cx.worker.clone();
runtime::spawn_blocking(move || run(worker));
});
if had_entered {
// Unset the current task's budget. Blocking sections are not
// constrained by task budgets.
let _reset = Reset(coop::stop());
crate::runtime::enter::exit(f)
} else {
f()
}
}
/// After how many ticks is the global queue polled. This helps to ensure
/// fairness.
///
/// The number is fairly arbitrary. I believe this value was copied from golang.
const GLOBAL_POLL_INTERVAL: u8 = 61;
impl Launch {
pub(crate) fn launch(mut self) {
for worker in self.0.drain(..) {
runtime::spawn_blocking(move || run(worker));
}
}
}
fn run(worker: Arc<Worker>) {
// Acquire a core. If this fails, then another thread is running this
// worker and there is nothing further to do.
let core = match worker.core.take() {
Some(core) => core,
None => return,
};
// Set the worker context.
let cx = Context {
worker,
core: RefCell::new(None),
};
let _enter = crate::runtime::enter(true);
CURRENT.set(&cx, || {
// This should always be an error. It only returns a `Result` to support
// using `?` to short circuit.
assert!(cx.run(core).is_err());
});
}
impl Context {
fn run(&self, mut core: Box<Core>) -> RunResult {
while !core.is_shutdown {
// Increment the tick
core.tick();
// Run maintenance, if needed
core = self.maintenance(core);
// First, check work available to the current worker.
if let Some(task) = core.next_task(&self.worker) {
core = self.run_task(task, core)?;
continue;
}
// There is no more **local** work to process, try to steal work
// from other workers.
if let Some(task) = core.steal_work(&self.worker) {
core = self.run_task(task, core)?;
} else {
// Wait for work
core = self.park(core);
}
}
core.pre_shutdown(&self.worker);
// Signal shutdown
self.worker.shared.shutdown(core);
Err(())
}
fn run_task(&self, task: Notified, mut core: Box<Core>) -> RunResult {
let task = self.worker.shared.owned.assert_owner(task);
// Make sure the worker is not in the **searching** state. This enables
// another idle worker to try to steal work.
core.transition_from_searching(&self.worker);
// Make the core available to the runtime context
*self.core.borrow_mut() = Some(core);
// Run the task
coop::budget(|| {
task.run();
// As long as there is budget remaining and a task exists in the
// `lifo_slot`, then keep running.
loop {
// Check if we still have the core. If not, the core was stolen
// by another worker.
let mut core = match self.core.borrow_mut().take() {
Some(core) => core,
None => return Err(()),
};
// Check for a task in the LIFO slot
let task = match core.lifo_slot.take() {
Some(task) => task,
None => return Ok(core),
};
if coop::has_budget_remaining() {
// Run the LIFO task, then loop
*self.core.borrow_mut() = Some(core);
let task = self.worker.shared.owned.assert_owner(task);
task.run();
} else {
// Not enough budget left to run the LIFO task, push it to
// the back of the queue and return.
core.run_queue.push_back(task, self.worker.inject());
return Ok(core);
}
}
})
}
fn maintenance(&self, mut core: Box<Core>) -> Box<Core> {
if core.tick % GLOBAL_POLL_INTERVAL == 0 {
// Call `park` with a 0 timeout. This enables the I/O driver, timer, ...
// to run without actually putting the thread to sleep.
core = self.park_timeout(core, Some(Duration::from_millis(0)));
// Run regularly scheduled maintenance
core.maintenance(&self.worker);
}
core
}
fn park(&self, mut core: Box<Core>) -> Box<Core> {
core.transition_to_parked(&self.worker);
while !core.is_shutdown {
core = self.park_timeout(core, None);
// Run regularly scheduled maintenance
core.maintenance(&self.worker);
if core.transition_from_parked(&self.worker) {
return core;
}
}
core
}
fn park_timeout(&self, mut core: Box<Core>, duration: Option<Duration>) -> Box<Core> {
// Take the parker out of core
let mut park = core.park.take().expect("park missing");
// Store `core` in context
*self.core.borrow_mut() = Some(core);
// Park thread
if let Some(timeout) = duration {
park.park_timeout(timeout).expect("park failed");
} else {
park.park().expect("park failed");
}
// Remove `core` from context
core = self.core.borrow_mut().take().expect("core missing");
// Place `park` back in `core`
core.park = Some(park);
// If there are tasks available to steal, notify a worker
if core.run_queue.is_stealable() {
self.worker.shared.notify_parked();
}
core
}
}
impl Core {
/// Increment the tick
fn tick(&mut self) {
self.tick = self.tick.wrapping_add(1);
}
/// Return the next notified task available to this worker.
fn next_task(&mut self, worker: &Worker) -> Option<Notified> {
if self.tick % GLOBAL_POLL_INTERVAL == 0 {
worker.inject().pop().or_else(|| self.next_local_task())
} else {
self.next_local_task().or_else(|| worker.inject().pop())
}
}
fn next_local_task(&mut self) -> Option<Notified> {
self.lifo_slot.take().or_else(|| self.run_queue.pop())
}
fn steal_work(&mut self, worker: &Worker) -> Option<Notified> {
if !self.transition_to_searching(worker) {
return None;
}
let num = worker.shared.remotes.len();
// Start from a random worker
let start = self.rand.fastrand_n(num as u32) as usize;
for i in 0..num {
let i = (start + i) % num;
// Don't steal from ourself! We know we don't have work.
if i == worker.index {
continue;
}
let target = &worker.shared.remotes[i];
if let Some(task) = target.steal.steal_into(&mut self.run_queue) {
return Some(task);
}
}
// Fallback on checking the global queue
worker.shared.inject.pop()
}
fn transition_to_searching(&mut self, worker: &Worker) -> bool {
if !self.is_searching {
self.is_searching = worker.shared.idle.transition_worker_to_searching();
}
self.is_searching
}
fn transition_from_searching(&mut self, worker: &Worker) {
if !self.is_searching {
return;
}
self.is_searching = false;
worker.shared.transition_worker_from_searching();
}
/// Prepare the worker state for parking
fn transition_to_parked(&mut self, worker: &Worker) {
// When the final worker transitions **out** of searching to parked, it
// must check all the queues one last time in case work materialized
// between the last work scan and transitioning out of searching.
let is_last_searcher = worker
.shared
.idle
.transition_worker_to_parked(worker.index, self.is_searching);
// The worker is no longer searching. Setting this is the local cache
// only.
self.is_searching = false;
if is_last_searcher {
worker.shared.notify_if_work_pending();
}
}
/// Returns `true` if the transition happened.
fn transition_from_parked(&mut self, worker: &Worker) -> bool {
// If a task is in the lifo slot, then we must unpark regardless of
// being notified
if self.lifo_slot.is_some() {
worker.shared.idle.unpark_worker_by_id(worker.index);
self.is_searching = true;
return true;
}
if worker.shared.idle.is_parked(worker.index) {
return false;
}
// When unparked, the worker is in the searching state.
self.is_searching = true;
true
}
/// Runs maintenance work such as checking the pool's state.
fn maintenance(&mut self, worker: &Worker) {
if !self.is_shutdown {
// Check if the scheduler has been shutdown
self.is_shutdown = worker.inject().is_closed();
}
}
/// Signals all tasks to shut down, and waits for them to complete. Must run
/// before we enter the single-threaded phase of shutdown processing.
fn pre_shutdown(&mut self, worker: &Worker) {
// Signal to all tasks to shut down.
worker.shared.owned.close_and_shutdown_all();
}
/// Shutdown the core
fn shutdown(&mut self) {
// Take the core
let mut park = self.park.take().expect("park missing");
// Drain the queue
while self.next_local_task().is_some() {}
park.shutdown();
}
}
impl Worker {
/// Returns a reference to the scheduler's injection queue
fn inject(&self) -> &Inject<Arc<Shared>> {
&self.shared.inject
}
}
impl task::Schedule for Arc<Shared> {
fn release(&self, task: &Task) -> Option<Task> {
self.owned.remove(task)
}
fn schedule(&self, task: Notified) {
(**self).schedule(task, false);
}
fn yield_now(&self, task: Notified) {
(**self).schedule(task, true);
}
}
impl Shared {
pub(super) fn bind_new_task<T>(me: &Arc<Self>, future: T) -> JoinHandle<T::Output>
where
T: Future + Send + 'static,
T::Output: Send + 'static,
{
let (handle, notified) = me.owned.bind(future, me.clone());
if let Some(notified) = notified {
me.schedule(notified, false);
}
handle
}
pub(super) fn schedule(&self, task: Notified, is_yield: bool) {
CURRENT.with(|maybe_cx| {
if let Some(cx) = maybe_cx {
// Make sure the task is part of the **current** scheduler.
if self.ptr_eq(&cx.worker.shared) {
// And the current thread still holds a core
if let Some(core) = cx.core.borrow_mut().as_mut() {
self.schedule_local(core, task, is_yield);
return;
}
}
}
// Otherwise, use the inject queue.
self.inject.push(task);
self.notify_parked();
})
}
fn schedule_local(&self, core: &mut Core, task: Notified, is_yield: bool) {
// Spawning from the worker thread. If scheduling a "yield" then the
// task must always be pushed to the back of the queue, enabling other
// tasks to be executed. If **not** a yield, then there is more
// flexibility and the task may go to the front of the queue.
let should_notify = if is_yield {
core.run_queue.push_back(task, &self.inject);
true
} else {
// Push to the LIFO slot
let prev = core.lifo_slot.take();
let ret = prev.is_some();
if let Some(prev) = prev {
core.run_queue.push_back(prev, &self.inject);
}
core.lifo_slot = Some(task);
ret
};
// Only notify if not currently parked. If `park` is `None`, then the
// scheduling is from a resource driver. As notifications often come in
// batches, the notification is delayed until the park is complete.
if should_notify && core.park.is_some() {
self.notify_parked();
}
}
pub(super) fn close(&self) {
if self.inject.close() {
self.notify_all();
}
}
fn notify_parked(&self) {
if let Some(index) = self.idle.worker_to_notify() {
self.remotes[index].unpark.unpark();
}
}
fn notify_all(&self) {
for remote in &self.remotes[..] {
remote.unpark.unpark();
}
}
fn notify_if_work_pending(&self) {
for remote in &self.remotes[..] {
if !remote.steal.is_empty() {
self.notify_parked();
return;
}
}
if !self.inject.is_empty() {
self.notify_parked();
}
}
fn transition_worker_from_searching(&self) {
if self.idle.transition_worker_from_searching() {
// We are the final searching worker. Because work was found, we
// need to notify another worker.
self.notify_parked();
}
}
/// Signals that a worker has observed the shutdown signal and has replaced
/// its core back into its handle.
///
/// If all workers have reached this point, the final cleanup is performed.
fn shutdown(&self, core: Box<Core>) {
let mut cores = self.shutdown_cores.lock();
cores.push(core);
if cores.len() != self.remotes.len() {
return;
}
debug_assert!(self.owned.is_empty());
for mut core in cores.drain(..) {
core.shutdown();
}
// Drain the injection queue
//
// We already shut down every task, so we can simply drop the tasks.
while let Some(task) = self.inject.pop() {
drop(task);
}
}
fn ptr_eq(&self, other: &Shared) -> bool {
std::ptr::eq(self, other)
}
}
| 31.876943 | 96 | 0.5767 |
db88072150a603f2ef49f5847f51065e7abbd4dc
| 95,471 |
// Copyright 2012-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.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(trivial_casts)]
#![crate_name = "rustc_llvm"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(associated_consts)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(libc)]
#![feature(link_args)]
#![feature(staged_api)]
extern crate libc;
#[macro_use] #[no_link] extern crate rustc_bitflags;
pub use self::OtherAttribute::*;
pub use self::SpecialAttribute::*;
pub use self::AttributeSet::*;
pub use self::IntPredicate::*;
pub use self::RealPredicate::*;
pub use self::TypeKind::*;
pub use self::AtomicBinOp::*;
pub use self::AtomicOrdering::*;
pub use self::SynchronizationScope::*;
pub use self::FileType::*;
pub use self::MetadataType::*;
pub use self::AsmDialect::*;
pub use self::CodeGenOptLevel::*;
pub use self::RelocMode::*;
pub use self::CodeGenModel::*;
pub use self::DiagnosticKind::*;
pub use self::CallConv::*;
pub use self::Visibility::*;
pub use self::DiagnosticSeverity::*;
pub use self::Linkage::*;
use std::ffi::CString;
use std::cell::RefCell;
use std::{slice, mem};
use libc::{c_uint, c_ushort, uint64_t, c_int, size_t, c_char};
use libc::{c_longlong, c_ulonglong, c_void};
use debuginfo::{DIBuilderRef, DIDescriptor,
DIFile, DILexicalBlock, DISubprogram, DIType,
DIBasicType, DIDerivedType, DICompositeType, DIScope,
DIVariable, DIGlobalVariable, DIArray, DISubrange,
DITemplateTypeParameter, DIEnumerator, DINameSpace};
pub mod archive_ro;
pub mod diagnostic;
pub type Opcode = u32;
pub type Bool = c_uint;
pub const True: Bool = 1 as Bool;
pub const False: Bool = 0 as Bool;
// Consts for the LLVM CallConv type, pre-cast to usize.
#[derive(Copy, Clone, PartialEq)]
pub enum CallConv {
CCallConv = 0,
FastCallConv = 8,
ColdCallConv = 9,
X86StdcallCallConv = 64,
X86FastcallCallConv = 65,
X86_64_Win64 = 79,
}
#[derive(Copy, Clone)]
pub enum Visibility {
LLVMDefaultVisibility = 0,
HiddenVisibility = 1,
ProtectedVisibility = 2,
}
// This enum omits the obsolete (and no-op) linkage types DLLImportLinkage,
// DLLExportLinkage, GhostLinkage and LinkOnceODRAutoHideLinkage.
// LinkerPrivateLinkage and LinkerPrivateWeakLinkage are not included either;
// they've been removed in upstream LLVM commit r203866.
#[derive(Copy, Clone)]
pub enum Linkage {
ExternalLinkage = 0,
AvailableExternallyLinkage = 1,
LinkOnceAnyLinkage = 2,
LinkOnceODRLinkage = 3,
WeakAnyLinkage = 5,
WeakODRLinkage = 6,
AppendingLinkage = 7,
InternalLinkage = 8,
PrivateLinkage = 9,
ExternalWeakLinkage = 12,
CommonLinkage = 14,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub enum DiagnosticSeverity {
Error,
Warning,
Remark,
Note,
}
bitflags! {
flags Attribute : u32 {
const ZExtAttribute = 1 << 0,
const SExtAttribute = 1 << 1,
const NoReturnAttribute = 1 << 2,
const InRegAttribute = 1 << 3,
const StructRetAttribute = 1 << 4,
const NoUnwindAttribute = 1 << 5,
const NoAliasAttribute = 1 << 6,
const ByValAttribute = 1 << 7,
const NestAttribute = 1 << 8,
const ReadNoneAttribute = 1 << 9,
const ReadOnlyAttribute = 1 << 10,
const NoInlineAttribute = 1 << 11,
const AlwaysInlineAttribute = 1 << 12,
const OptimizeForSizeAttribute = 1 << 13,
const StackProtectAttribute = 1 << 14,
const StackProtectReqAttribute = 1 << 15,
const AlignmentAttribute = 1 << 16,
const NoCaptureAttribute = 1 << 21,
const NoRedZoneAttribute = 1 << 22,
const NoImplicitFloatAttribute = 1 << 23,
const NakedAttribute = 1 << 24,
const InlineHintAttribute = 1 << 25,
const StackAttribute = 7 << 26,
const ReturnsTwiceAttribute = 1 << 29,
const UWTableAttribute = 1 << 30,
const NonLazyBindAttribute = 1 << 31,
}
}
#[repr(u64)]
#[derive(Copy, Clone)]
pub enum OtherAttribute {
// The following are not really exposed in
// the LLVM C api so instead to add these
// we call a wrapper function in RustWrapper
// that uses the C++ api.
SanitizeAddressAttribute = 1 << 32,
MinSizeAttribute = 1 << 33,
NoDuplicateAttribute = 1 << 34,
StackProtectStrongAttribute = 1 << 35,
SanitizeThreadAttribute = 1 << 36,
SanitizeMemoryAttribute = 1 << 37,
NoBuiltinAttribute = 1 << 38,
ReturnedAttribute = 1 << 39,
ColdAttribute = 1 << 40,
BuiltinAttribute = 1 << 41,
OptimizeNoneAttribute = 1 << 42,
InAllocaAttribute = 1 << 43,
NonNullAttribute = 1 << 44,
}
#[derive(Copy, Clone)]
pub enum SpecialAttribute {
DereferenceableAttribute(u64)
}
#[repr(C)]
#[derive(Copy, Clone)]
pub enum AttributeSet {
ReturnIndex = 0,
FunctionIndex = !0
}
pub trait AttrHelper {
fn apply_llfn(&self, idx: c_uint, llfn: ValueRef);
fn apply_callsite(&self, idx: c_uint, callsite: ValueRef);
}
impl AttrHelper for Attribute {
fn apply_llfn(&self, idx: c_uint, llfn: ValueRef) {
unsafe {
LLVMAddFunctionAttribute(llfn, idx, self.bits() as uint64_t);
}
}
fn apply_callsite(&self, idx: c_uint, callsite: ValueRef) {
unsafe {
LLVMAddCallSiteAttribute(callsite, idx, self.bits() as uint64_t);
}
}
}
impl AttrHelper for OtherAttribute {
fn apply_llfn(&self, idx: c_uint, llfn: ValueRef) {
unsafe {
LLVMAddFunctionAttribute(llfn, idx, *self as uint64_t);
}
}
fn apply_callsite(&self, idx: c_uint, callsite: ValueRef) {
unsafe {
LLVMAddCallSiteAttribute(callsite, idx, *self as uint64_t);
}
}
}
impl AttrHelper for SpecialAttribute {
fn apply_llfn(&self, idx: c_uint, llfn: ValueRef) {
match *self {
DereferenceableAttribute(bytes) => unsafe {
LLVMAddDereferenceableAttr(llfn, idx, bytes as uint64_t);
}
}
}
fn apply_callsite(&self, idx: c_uint, callsite: ValueRef) {
match *self {
DereferenceableAttribute(bytes) => unsafe {
LLVMAddDereferenceableCallSiteAttr(callsite, idx, bytes as uint64_t);
}
}
}
}
pub struct AttrBuilder {
attrs: Vec<(usize, Box<AttrHelper+'static>)>
}
impl AttrBuilder {
pub fn new() -> AttrBuilder {
AttrBuilder {
attrs: Vec::new()
}
}
pub fn arg<'a, T: AttrHelper + 'static>(&'a mut self, idx: usize, a: T) -> &'a mut AttrBuilder {
self.attrs.push((idx, box a as Box<AttrHelper+'static>));
self
}
pub fn ret<'a, T: AttrHelper + 'static>(&'a mut self, a: T) -> &'a mut AttrBuilder {
self.attrs.push((ReturnIndex as usize, box a as Box<AttrHelper+'static>));
self
}
pub fn apply_llfn(&self, llfn: ValueRef) {
for &(idx, ref attr) in &self.attrs {
attr.apply_llfn(idx as c_uint, llfn);
}
}
pub fn apply_callsite(&self, callsite: ValueRef) {
for &(idx, ref attr) in &self.attrs {
attr.apply_callsite(idx as c_uint, callsite);
}
}
}
// enum for the LLVM IntPredicate type
#[derive(Copy, Clone)]
pub enum IntPredicate {
IntEQ = 32,
IntNE = 33,
IntUGT = 34,
IntUGE = 35,
IntULT = 36,
IntULE = 37,
IntSGT = 38,
IntSGE = 39,
IntSLT = 40,
IntSLE = 41,
}
// enum for the LLVM RealPredicate type
#[derive(Copy, Clone)]
pub enum RealPredicate {
RealPredicateFalse = 0,
RealOEQ = 1,
RealOGT = 2,
RealOGE = 3,
RealOLT = 4,
RealOLE = 5,
RealONE = 6,
RealORD = 7,
RealUNO = 8,
RealUEQ = 9,
RealUGT = 10,
RealUGE = 11,
RealULT = 12,
RealULE = 13,
RealUNE = 14,
RealPredicateTrue = 15,
}
// The LLVM TypeKind type - must stay in sync with the def of
// LLVMTypeKind in llvm/include/llvm-c/Core.h
#[derive(Copy, Clone, PartialEq, Debug)]
#[repr(C)]
pub enum TypeKind {
Void = 0,
Half = 1,
Float = 2,
Double = 3,
X86_FP80 = 4,
FP128 = 5,
PPC_FP128 = 6,
Label = 7,
Integer = 8,
Function = 9,
Struct = 10,
Array = 11,
Pointer = 12,
Vector = 13,
Metadata = 14,
X86_MMX = 15,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub enum AtomicBinOp {
AtomicXchg = 0,
AtomicAdd = 1,
AtomicSub = 2,
AtomicAnd = 3,
AtomicNand = 4,
AtomicOr = 5,
AtomicXor = 6,
AtomicMax = 7,
AtomicMin = 8,
AtomicUMax = 9,
AtomicUMin = 10,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub enum AtomicOrdering {
NotAtomic = 0,
Unordered = 1,
Monotonic = 2,
// Consume = 3, // Not specified yet.
Acquire = 4,
Release = 5,
AcquireRelease = 6,
SequentiallyConsistent = 7
}
#[repr(C)]
#[derive(Copy, Clone)]
pub enum SynchronizationScope {
SingleThread = 0,
CrossThread = 1
}
// Consts for the LLVMCodeGenFileType type (in include/llvm/c/TargetMachine.h)
#[repr(C)]
#[derive(Copy, Clone)]
pub enum FileType {
AssemblyFileType = 0,
ObjectFileType = 1
}
#[derive(Copy, Clone)]
pub enum MetadataType {
MD_dbg = 0,
MD_tbaa = 1,
MD_prof = 2,
MD_fpmath = 3,
MD_range = 4,
MD_tbaa_struct = 5,
MD_invariant_load = 6,
MD_alias_scope = 7,
MD_noalias = 8,
MD_nontemporal = 9,
MD_mem_parallel_loop_access = 10,
MD_nonnull = 11,
}
// Inline Asm Dialect
#[derive(Copy, Clone)]
pub enum AsmDialect {
AD_ATT = 0,
AD_Intel = 1
}
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
pub enum CodeGenOptLevel {
CodeGenLevelNone = 0,
CodeGenLevelLess = 1,
CodeGenLevelDefault = 2,
CodeGenLevelAggressive = 3,
}
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
pub enum RelocMode {
RelocDefault = 0,
RelocStatic = 1,
RelocPIC = 2,
RelocDynamicNoPic = 3,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub enum CodeGenModel {
CodeModelDefault = 0,
CodeModelJITDefault = 1,
CodeModelSmall = 2,
CodeModelKernel = 3,
CodeModelMedium = 4,
CodeModelLarge = 5,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub enum DiagnosticKind {
DK_InlineAsm = 0,
DK_StackSize,
DK_DebugMetadataVersion,
DK_SampleProfile,
DK_OptimizationRemark,
DK_OptimizationRemarkMissed,
DK_OptimizationRemarkAnalysis,
DK_OptimizationFailure,
}
// Opaque pointer types
#[allow(missing_copy_implementations)]
pub enum Module_opaque {}
pub type ModuleRef = *mut Module_opaque;
#[allow(missing_copy_implementations)]
pub enum Context_opaque {}
pub type ContextRef = *mut Context_opaque;
#[allow(missing_copy_implementations)]
pub enum Type_opaque {}
pub type TypeRef = *mut Type_opaque;
#[allow(missing_copy_implementations)]
pub enum Value_opaque {}
pub type ValueRef = *mut Value_opaque;
#[allow(missing_copy_implementations)]
pub enum Metadata_opaque {}
pub type MetadataRef = *mut Metadata_opaque;
#[allow(missing_copy_implementations)]
pub enum BasicBlock_opaque {}
pub type BasicBlockRef = *mut BasicBlock_opaque;
#[allow(missing_copy_implementations)]
pub enum Builder_opaque {}
pub type BuilderRef = *mut Builder_opaque;
#[allow(missing_copy_implementations)]
pub enum ExecutionEngine_opaque {}
pub type ExecutionEngineRef = *mut ExecutionEngine_opaque;
#[allow(missing_copy_implementations)]
pub enum RustJITMemoryManager_opaque {}
pub type RustJITMemoryManagerRef = *mut RustJITMemoryManager_opaque;
#[allow(missing_copy_implementations)]
pub enum MemoryBuffer_opaque {}
pub type MemoryBufferRef = *mut MemoryBuffer_opaque;
#[allow(missing_copy_implementations)]
pub enum PassManager_opaque {}
pub type PassManagerRef = *mut PassManager_opaque;
#[allow(missing_copy_implementations)]
pub enum PassManagerBuilder_opaque {}
pub type PassManagerBuilderRef = *mut PassManagerBuilder_opaque;
#[allow(missing_copy_implementations)]
pub enum Use_opaque {}
pub type UseRef = *mut Use_opaque;
#[allow(missing_copy_implementations)]
pub enum TargetData_opaque {}
pub type TargetDataRef = *mut TargetData_opaque;
#[allow(missing_copy_implementations)]
pub enum ObjectFile_opaque {}
pub type ObjectFileRef = *mut ObjectFile_opaque;
#[allow(missing_copy_implementations)]
pub enum SectionIterator_opaque {}
pub type SectionIteratorRef = *mut SectionIterator_opaque;
#[allow(missing_copy_implementations)]
pub enum Pass_opaque {}
pub type PassRef = *mut Pass_opaque;
#[allow(missing_copy_implementations)]
pub enum TargetMachine_opaque {}
pub type TargetMachineRef = *mut TargetMachine_opaque;
pub enum Archive_opaque {}
pub type ArchiveRef = *mut Archive_opaque;
pub enum ArchiveIterator_opaque {}
pub type ArchiveIteratorRef = *mut ArchiveIterator_opaque;
pub enum ArchiveChild_opaque {}
pub type ArchiveChildRef = *mut ArchiveChild_opaque;
#[allow(missing_copy_implementations)]
pub enum Twine_opaque {}
pub type TwineRef = *mut Twine_opaque;
#[allow(missing_copy_implementations)]
pub enum DiagnosticInfo_opaque {}
pub type DiagnosticInfoRef = *mut DiagnosticInfo_opaque;
#[allow(missing_copy_implementations)]
pub enum DebugLoc_opaque {}
pub type DebugLocRef = *mut DebugLoc_opaque;
#[allow(missing_copy_implementations)]
pub enum SMDiagnostic_opaque {}
pub type SMDiagnosticRef = *mut SMDiagnostic_opaque;
pub type DiagnosticHandler = unsafe extern "C" fn(DiagnosticInfoRef, *mut c_void);
pub type InlineAsmDiagHandler = unsafe extern "C" fn(SMDiagnosticRef, *const c_void, c_uint);
pub mod debuginfo {
pub use self::DIDescriptorFlags::*;
use super::{MetadataRef};
#[allow(missing_copy_implementations)]
pub enum DIBuilder_opaque {}
pub type DIBuilderRef = *mut DIBuilder_opaque;
pub type DIDescriptor = MetadataRef;
pub type DIScope = DIDescriptor;
pub type DILocation = DIDescriptor;
pub type DIFile = DIScope;
pub type DILexicalBlock = DIScope;
pub type DISubprogram = DIScope;
pub type DINameSpace = DIScope;
pub type DIType = DIDescriptor;
pub type DIBasicType = DIType;
pub type DIDerivedType = DIType;
pub type DICompositeType = DIDerivedType;
pub type DIVariable = DIDescriptor;
pub type DIGlobalVariable = DIDescriptor;
pub type DIArray = DIDescriptor;
pub type DISubrange = DIDescriptor;
pub type DIEnumerator = DIDescriptor;
pub type DITemplateTypeParameter = DIDescriptor;
#[derive(Copy, Clone)]
pub enum DIDescriptorFlags {
FlagPrivate = 1 << 0,
FlagProtected = 1 << 1,
FlagFwdDecl = 1 << 2,
FlagAppleBlock = 1 << 3,
FlagBlockByrefStruct = 1 << 4,
FlagVirtual = 1 << 5,
FlagArtificial = 1 << 6,
FlagExplicit = 1 << 7,
FlagPrototyped = 1 << 8,
FlagObjcClassComplete = 1 << 9,
FlagObjectPointer = 1 << 10,
FlagVector = 1 << 11,
FlagStaticMember = 1 << 12,
FlagIndirectVariable = 1 << 13,
FlagLValueReference = 1 << 14,
FlagRValueReference = 1 << 15
}
}
// Link to our native llvm bindings (things that we need to use the C++ api
// for) and because llvm is written in C++ we need to link against libstdc++
//
// You'll probably notice that there is an omission of all LLVM libraries
// from this location. This is because the set of LLVM libraries that we
// link to is mostly defined by LLVM, and the `llvm-config` tool is used to
// figure out the exact set of libraries. To do this, the build system
// generates an llvmdeps.rs file next to this one which will be
// automatically updated whenever LLVM is updated to include an up-to-date
// set of the libraries we need to link to LLVM for.
#[link(name = "rustllvm", kind = "static")]
extern {
/* Create and destroy contexts. */
pub fn LLVMContextCreate() -> ContextRef;
pub fn LLVMContextDispose(C: ContextRef);
pub fn LLVMGetMDKindIDInContext(C: ContextRef,
Name: *const c_char,
SLen: c_uint)
-> c_uint;
/* Create and destroy modules. */
pub fn LLVMModuleCreateWithNameInContext(ModuleID: *const c_char,
C: ContextRef)
-> ModuleRef;
pub fn LLVMGetModuleContext(M: ModuleRef) -> ContextRef;
pub fn LLVMDisposeModule(M: ModuleRef);
/// Data layout. See Module::getDataLayout.
pub fn LLVMGetDataLayout(M: ModuleRef) -> *const c_char;
pub fn LLVMSetDataLayout(M: ModuleRef, Triple: *const c_char);
/// Target triple. See Module::getTargetTriple.
pub fn LLVMGetTarget(M: ModuleRef) -> *const c_char;
pub fn LLVMSetTarget(M: ModuleRef, Triple: *const c_char);
/// See Module::dump.
pub fn LLVMDumpModule(M: ModuleRef);
/// See Module::setModuleInlineAsm.
pub fn LLVMSetModuleInlineAsm(M: ModuleRef, Asm: *const c_char);
/// See llvm::LLVMTypeKind::getTypeID.
pub fn LLVMGetTypeKind(Ty: TypeRef) -> TypeKind;
/// See llvm::LLVMType::getContext.
pub fn LLVMGetTypeContext(Ty: TypeRef) -> ContextRef;
/* Operations on integer types */
pub fn LLVMInt1TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMInt8TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMInt16TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMInt32TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMInt64TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMIntTypeInContext(C: ContextRef, NumBits: c_uint)
-> TypeRef;
pub fn LLVMGetIntTypeWidth(IntegerTy: TypeRef) -> c_uint;
/* Operations on real types */
pub fn LLVMFloatTypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMDoubleTypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMX86FP80TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMFP128TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMPPCFP128TypeInContext(C: ContextRef) -> TypeRef;
/* Operations on function types */
pub fn LLVMFunctionType(ReturnType: TypeRef,
ParamTypes: *const TypeRef,
ParamCount: c_uint,
IsVarArg: Bool)
-> TypeRef;
pub fn LLVMIsFunctionVarArg(FunctionTy: TypeRef) -> Bool;
pub fn LLVMGetReturnType(FunctionTy: TypeRef) -> TypeRef;
pub fn LLVMCountParamTypes(FunctionTy: TypeRef) -> c_uint;
pub fn LLVMGetParamTypes(FunctionTy: TypeRef, Dest: *mut TypeRef);
/* Operations on struct types */
pub fn LLVMStructTypeInContext(C: ContextRef,
ElementTypes: *const TypeRef,
ElementCount: c_uint,
Packed: Bool)
-> TypeRef;
pub fn LLVMCountStructElementTypes(StructTy: TypeRef) -> c_uint;
pub fn LLVMGetStructElementTypes(StructTy: TypeRef,
Dest: *mut TypeRef);
pub fn LLVMIsPackedStruct(StructTy: TypeRef) -> Bool;
/* Operations on array, pointer, and vector types (sequence types) */
pub fn LLVMRustArrayType(ElementType: TypeRef, ElementCount: u64) -> TypeRef;
pub fn LLVMPointerType(ElementType: TypeRef, AddressSpace: c_uint)
-> TypeRef;
pub fn LLVMVectorType(ElementType: TypeRef, ElementCount: c_uint)
-> TypeRef;
pub fn LLVMGetElementType(Ty: TypeRef) -> TypeRef;
pub fn LLVMGetArrayLength(ArrayTy: TypeRef) -> c_uint;
pub fn LLVMGetPointerAddressSpace(PointerTy: TypeRef) -> c_uint;
pub fn LLVMGetPointerToGlobal(EE: ExecutionEngineRef, V: ValueRef)
-> *const ();
pub fn LLVMGetVectorSize(VectorTy: TypeRef) -> c_uint;
/* Operations on other types */
pub fn LLVMVoidTypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMLabelTypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMMetadataTypeInContext(C: ContextRef) -> TypeRef;
/* Operations on all values */
pub fn LLVMTypeOf(Val: ValueRef) -> TypeRef;
pub fn LLVMGetValueName(Val: ValueRef) -> *const c_char;
pub fn LLVMSetValueName(Val: ValueRef, Name: *const c_char);
pub fn LLVMDumpValue(Val: ValueRef);
pub fn LLVMReplaceAllUsesWith(OldVal: ValueRef, NewVal: ValueRef);
pub fn LLVMHasMetadata(Val: ValueRef) -> c_int;
pub fn LLVMGetMetadata(Val: ValueRef, KindID: c_uint) -> ValueRef;
pub fn LLVMSetMetadata(Val: ValueRef, KindID: c_uint, Node: ValueRef);
/* Operations on Uses */
pub fn LLVMGetFirstUse(Val: ValueRef) -> UseRef;
pub fn LLVMGetNextUse(U: UseRef) -> UseRef;
pub fn LLVMGetUser(U: UseRef) -> ValueRef;
pub fn LLVMGetUsedValue(U: UseRef) -> ValueRef;
/* Operations on Users */
pub fn LLVMGetNumOperands(Val: ValueRef) -> c_int;
pub fn LLVMGetOperand(Val: ValueRef, Index: c_uint) -> ValueRef;
pub fn LLVMSetOperand(Val: ValueRef, Index: c_uint, Op: ValueRef);
/* Operations on constants of any type */
pub fn LLVMConstNull(Ty: TypeRef) -> ValueRef;
/* all zeroes */
pub fn LLVMConstAllOnes(Ty: TypeRef) -> ValueRef;
pub fn LLVMConstICmp(Pred: c_ushort, V1: ValueRef, V2: ValueRef)
-> ValueRef;
pub fn LLVMConstFCmp(Pred: c_ushort, V1: ValueRef, V2: ValueRef)
-> ValueRef;
/* only for isize/vector */
pub fn LLVMGetUndef(Ty: TypeRef) -> ValueRef;
pub fn LLVMIsConstant(Val: ValueRef) -> Bool;
pub fn LLVMIsNull(Val: ValueRef) -> Bool;
pub fn LLVMIsUndef(Val: ValueRef) -> Bool;
pub fn LLVMConstPointerNull(Ty: TypeRef) -> ValueRef;
/* Operations on metadata */
pub fn LLVMMDStringInContext(C: ContextRef,
Str: *const c_char,
SLen: c_uint)
-> ValueRef;
pub fn LLVMMDNodeInContext(C: ContextRef,
Vals: *const ValueRef,
Count: c_uint)
-> ValueRef;
pub fn LLVMAddNamedMetadataOperand(M: ModuleRef,
Str: *const c_char,
Val: ValueRef);
/* Operations on scalar constants */
pub fn LLVMConstInt(IntTy: TypeRef, N: c_ulonglong, SignExtend: Bool)
-> ValueRef;
pub fn LLVMConstIntOfString(IntTy: TypeRef, Text: *const c_char, Radix: u8)
-> ValueRef;
pub fn LLVMConstIntOfStringAndSize(IntTy: TypeRef,
Text: *const c_char,
SLen: c_uint,
Radix: u8)
-> ValueRef;
pub fn LLVMConstReal(RealTy: TypeRef, N: f64) -> ValueRef;
pub fn LLVMConstRealOfString(RealTy: TypeRef, Text: *const c_char)
-> ValueRef;
pub fn LLVMConstRealOfStringAndSize(RealTy: TypeRef,
Text: *const c_char,
SLen: c_uint)
-> ValueRef;
pub fn LLVMConstIntGetZExtValue(ConstantVal: ValueRef) -> c_ulonglong;
pub fn LLVMConstIntGetSExtValue(ConstantVal: ValueRef) -> c_longlong;
/* Operations on composite constants */
pub fn LLVMConstStringInContext(C: ContextRef,
Str: *const c_char,
Length: c_uint,
DontNullTerminate: Bool)
-> ValueRef;
pub fn LLVMConstStructInContext(C: ContextRef,
ConstantVals: *const ValueRef,
Count: c_uint,
Packed: Bool)
-> ValueRef;
pub fn LLVMConstArray(ElementTy: TypeRef,
ConstantVals: *const ValueRef,
Length: c_uint)
-> ValueRef;
pub fn LLVMConstVector(ScalarConstantVals: *const ValueRef, Size: c_uint)
-> ValueRef;
/* Constant expressions */
pub fn LLVMAlignOf(Ty: TypeRef) -> ValueRef;
pub fn LLVMSizeOf(Ty: TypeRef) -> ValueRef;
pub fn LLVMConstNeg(ConstantVal: ValueRef) -> ValueRef;
pub fn LLVMConstNSWNeg(ConstantVal: ValueRef) -> ValueRef;
pub fn LLVMConstNUWNeg(ConstantVal: ValueRef) -> ValueRef;
pub fn LLVMConstFNeg(ConstantVal: ValueRef) -> ValueRef;
pub fn LLVMConstNot(ConstantVal: ValueRef) -> ValueRef;
pub fn LLVMConstAdd(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNSWAdd(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNUWAdd(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstFAdd(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstSub(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNSWSub(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNUWSub(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstFSub(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstMul(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNSWMul(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNUWMul(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstFMul(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstUDiv(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstSDiv(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstExactSDiv(LHSConstant: ValueRef,
RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstFDiv(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstURem(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstSRem(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstFRem(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstAnd(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstOr(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstXor(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstShl(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstLShr(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstAShr(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstGEP(ConstantVal: ValueRef,
ConstantIndices: *const ValueRef,
NumIndices: c_uint)
-> ValueRef;
pub fn LLVMConstInBoundsGEP(ConstantVal: ValueRef,
ConstantIndices: *const ValueRef,
NumIndices: c_uint)
-> ValueRef;
pub fn LLVMConstTrunc(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstSExt(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstZExt(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstFPTrunc(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstFPExt(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstUIToFP(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstSIToFP(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstFPToUI(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstFPToSI(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstPtrToInt(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstIntToPtr(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstBitCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstZExtOrBitCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstSExtOrBitCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstTruncOrBitCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstPointerCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstIntCast(ConstantVal: ValueRef,
ToType: TypeRef,
isSigned: Bool)
-> ValueRef;
pub fn LLVMConstFPCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstSelect(ConstantCondition: ValueRef,
ConstantIfTrue: ValueRef,
ConstantIfFalse: ValueRef)
-> ValueRef;
pub fn LLVMConstExtractElement(VectorConstant: ValueRef,
IndexConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstInsertElement(VectorConstant: ValueRef,
ElementValueConstant: ValueRef,
IndexConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstShuffleVector(VectorAConstant: ValueRef,
VectorBConstant: ValueRef,
MaskConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstExtractValue(AggConstant: ValueRef,
IdxList: *const c_uint,
NumIdx: c_uint)
-> ValueRef;
pub fn LLVMConstInsertValue(AggConstant: ValueRef,
ElementValueConstant: ValueRef,
IdxList: *const c_uint,
NumIdx: c_uint)
-> ValueRef;
pub fn LLVMConstInlineAsm(Ty: TypeRef,
AsmString: *const c_char,
Constraints: *const c_char,
HasSideEffects: Bool,
IsAlignStack: Bool)
-> ValueRef;
pub fn LLVMBlockAddress(F: ValueRef, BB: BasicBlockRef) -> ValueRef;
/* Operations on global variables, functions, and aliases (globals) */
pub fn LLVMGetGlobalParent(Global: ValueRef) -> ModuleRef;
pub fn LLVMIsDeclaration(Global: ValueRef) -> Bool;
pub fn LLVMGetLinkage(Global: ValueRef) -> c_uint;
pub fn LLVMSetLinkage(Global: ValueRef, Link: c_uint);
pub fn LLVMGetSection(Global: ValueRef) -> *const c_char;
pub fn LLVMSetSection(Global: ValueRef, Section: *const c_char);
pub fn LLVMGetVisibility(Global: ValueRef) -> c_uint;
pub fn LLVMSetVisibility(Global: ValueRef, Viz: c_uint);
pub fn LLVMGetAlignment(Global: ValueRef) -> c_uint;
pub fn LLVMSetAlignment(Global: ValueRef, Bytes: c_uint);
/* Operations on global variables */
pub fn LLVMIsAGlobalVariable(GlobalVar: ValueRef) -> ValueRef;
pub fn LLVMAddGlobal(M: ModuleRef, Ty: TypeRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMAddGlobalInAddressSpace(M: ModuleRef,
Ty: TypeRef,
Name: *const c_char,
AddressSpace: c_uint)
-> ValueRef;
pub fn LLVMGetNamedGlobal(M: ModuleRef, Name: *const c_char) -> ValueRef;
pub fn LLVMGetOrInsertGlobal(M: ModuleRef, Name: *const c_char, T: TypeRef) -> ValueRef;
pub fn LLVMGetFirstGlobal(M: ModuleRef) -> ValueRef;
pub fn LLVMGetLastGlobal(M: ModuleRef) -> ValueRef;
pub fn LLVMGetNextGlobal(GlobalVar: ValueRef) -> ValueRef;
pub fn LLVMGetPreviousGlobal(GlobalVar: ValueRef) -> ValueRef;
pub fn LLVMDeleteGlobal(GlobalVar: ValueRef);
pub fn LLVMGetInitializer(GlobalVar: ValueRef) -> ValueRef;
pub fn LLVMSetInitializer(GlobalVar: ValueRef,
ConstantVal: ValueRef);
pub fn LLVMIsThreadLocal(GlobalVar: ValueRef) -> Bool;
pub fn LLVMSetThreadLocal(GlobalVar: ValueRef, IsThreadLocal: Bool);
pub fn LLVMIsGlobalConstant(GlobalVar: ValueRef) -> Bool;
pub fn LLVMSetGlobalConstant(GlobalVar: ValueRef, IsConstant: Bool);
pub fn LLVMGetNamedValue(M: ModuleRef, Name: *const c_char) -> ValueRef;
/* Operations on aliases */
pub fn LLVMAddAlias(M: ModuleRef,
Ty: TypeRef,
Aliasee: ValueRef,
Name: *const c_char)
-> ValueRef;
/* Operations on functions */
pub fn LLVMAddFunction(M: ModuleRef,
Name: *const c_char,
FunctionTy: TypeRef)
-> ValueRef;
pub fn LLVMGetNamedFunction(M: ModuleRef, Name: *const c_char) -> ValueRef;
pub fn LLVMGetFirstFunction(M: ModuleRef) -> ValueRef;
pub fn LLVMGetLastFunction(M: ModuleRef) -> ValueRef;
pub fn LLVMGetNextFunction(Fn: ValueRef) -> ValueRef;
pub fn LLVMGetPreviousFunction(Fn: ValueRef) -> ValueRef;
pub fn LLVMDeleteFunction(Fn: ValueRef);
pub fn LLVMGetOrInsertFunction(M: ModuleRef,
Name: *const c_char,
FunctionTy: TypeRef)
-> ValueRef;
pub fn LLVMGetIntrinsicID(Fn: ValueRef) -> c_uint;
pub fn LLVMGetFunctionCallConv(Fn: ValueRef) -> c_uint;
pub fn LLVMSetFunctionCallConv(Fn: ValueRef, CC: c_uint);
pub fn LLVMGetGC(Fn: ValueRef) -> *const c_char;
pub fn LLVMSetGC(Fn: ValueRef, Name: *const c_char);
pub fn LLVMAddDereferenceableAttr(Fn: ValueRef, index: c_uint, bytes: uint64_t);
pub fn LLVMAddFunctionAttribute(Fn: ValueRef, index: c_uint, PA: uint64_t);
pub fn LLVMAddFunctionAttrString(Fn: ValueRef, index: c_uint, Name: *const c_char);
pub fn LLVMRemoveFunctionAttrString(Fn: ValueRef, index: c_uint, Name: *const c_char);
pub fn LLVMGetFunctionAttr(Fn: ValueRef) -> c_ulonglong;
pub fn LLVMRemoveFunctionAttr(Fn: ValueRef, val: c_ulonglong);
/* Operations on parameters */
pub fn LLVMCountParams(Fn: ValueRef) -> c_uint;
pub fn LLVMGetParams(Fn: ValueRef, Params: *const ValueRef);
pub fn LLVMGetParam(Fn: ValueRef, Index: c_uint) -> ValueRef;
pub fn LLVMGetParamParent(Inst: ValueRef) -> ValueRef;
pub fn LLVMGetFirstParam(Fn: ValueRef) -> ValueRef;
pub fn LLVMGetLastParam(Fn: ValueRef) -> ValueRef;
pub fn LLVMGetNextParam(Arg: ValueRef) -> ValueRef;
pub fn LLVMGetPreviousParam(Arg: ValueRef) -> ValueRef;
pub fn LLVMAddAttribute(Arg: ValueRef, PA: c_uint);
pub fn LLVMRemoveAttribute(Arg: ValueRef, PA: c_uint);
pub fn LLVMGetAttribute(Arg: ValueRef) -> c_uint;
pub fn LLVMSetParamAlignment(Arg: ValueRef, align: c_uint);
/* Operations on basic blocks */
pub fn LLVMBasicBlockAsValue(BB: BasicBlockRef) -> ValueRef;
pub fn LLVMValueIsBasicBlock(Val: ValueRef) -> Bool;
pub fn LLVMValueAsBasicBlock(Val: ValueRef) -> BasicBlockRef;
pub fn LLVMGetBasicBlockParent(BB: BasicBlockRef) -> ValueRef;
pub fn LLVMCountBasicBlocks(Fn: ValueRef) -> c_uint;
pub fn LLVMGetBasicBlocks(Fn: ValueRef, BasicBlocks: *const ValueRef);
pub fn LLVMGetFirstBasicBlock(Fn: ValueRef) -> BasicBlockRef;
pub fn LLVMGetLastBasicBlock(Fn: ValueRef) -> BasicBlockRef;
pub fn LLVMGetNextBasicBlock(BB: BasicBlockRef) -> BasicBlockRef;
pub fn LLVMGetPreviousBasicBlock(BB: BasicBlockRef) -> BasicBlockRef;
pub fn LLVMGetEntryBasicBlock(Fn: ValueRef) -> BasicBlockRef;
pub fn LLVMAppendBasicBlockInContext(C: ContextRef,
Fn: ValueRef,
Name: *const c_char)
-> BasicBlockRef;
pub fn LLVMInsertBasicBlockInContext(C: ContextRef,
BB: BasicBlockRef,
Name: *const c_char)
-> BasicBlockRef;
pub fn LLVMDeleteBasicBlock(BB: BasicBlockRef);
pub fn LLVMMoveBasicBlockAfter(BB: BasicBlockRef,
MoveAfter: BasicBlockRef);
pub fn LLVMMoveBasicBlockBefore(BB: BasicBlockRef,
MoveBefore: BasicBlockRef);
/* Operations on instructions */
pub fn LLVMGetInstructionParent(Inst: ValueRef) -> BasicBlockRef;
pub fn LLVMGetFirstInstruction(BB: BasicBlockRef) -> ValueRef;
pub fn LLVMGetLastInstruction(BB: BasicBlockRef) -> ValueRef;
pub fn LLVMGetNextInstruction(Inst: ValueRef) -> ValueRef;
pub fn LLVMGetPreviousInstruction(Inst: ValueRef) -> ValueRef;
pub fn LLVMInstructionEraseFromParent(Inst: ValueRef);
/* Operations on call sites */
pub fn LLVMSetInstructionCallConv(Instr: ValueRef, CC: c_uint);
pub fn LLVMGetInstructionCallConv(Instr: ValueRef) -> c_uint;
pub fn LLVMAddInstrAttribute(Instr: ValueRef,
index: c_uint,
IA: c_uint);
pub fn LLVMRemoveInstrAttribute(Instr: ValueRef,
index: c_uint,
IA: c_uint);
pub fn LLVMSetInstrParamAlignment(Instr: ValueRef,
index: c_uint,
align: c_uint);
pub fn LLVMAddCallSiteAttribute(Instr: ValueRef,
index: c_uint,
Val: uint64_t);
pub fn LLVMAddDereferenceableCallSiteAttr(Instr: ValueRef,
index: c_uint,
bytes: uint64_t);
/* Operations on call instructions (only) */
pub fn LLVMIsTailCall(CallInst: ValueRef) -> Bool;
pub fn LLVMSetTailCall(CallInst: ValueRef, IsTailCall: Bool);
/* Operations on load/store instructions (only) */
pub fn LLVMGetVolatile(MemoryAccessInst: ValueRef) -> Bool;
pub fn LLVMSetVolatile(MemoryAccessInst: ValueRef, volatile: Bool);
/* Operations on phi nodes */
pub fn LLVMAddIncoming(PhiNode: ValueRef,
IncomingValues: *const ValueRef,
IncomingBlocks: *const BasicBlockRef,
Count: c_uint);
pub fn LLVMCountIncoming(PhiNode: ValueRef) -> c_uint;
pub fn LLVMGetIncomingValue(PhiNode: ValueRef, Index: c_uint)
-> ValueRef;
pub fn LLVMGetIncomingBlock(PhiNode: ValueRef, Index: c_uint)
-> BasicBlockRef;
/* Instruction builders */
pub fn LLVMCreateBuilderInContext(C: ContextRef) -> BuilderRef;
pub fn LLVMPositionBuilder(Builder: BuilderRef,
Block: BasicBlockRef,
Instr: ValueRef);
pub fn LLVMPositionBuilderBefore(Builder: BuilderRef,
Instr: ValueRef);
pub fn LLVMPositionBuilderAtEnd(Builder: BuilderRef,
Block: BasicBlockRef);
pub fn LLVMGetInsertBlock(Builder: BuilderRef) -> BasicBlockRef;
pub fn LLVMClearInsertionPosition(Builder: BuilderRef);
pub fn LLVMInsertIntoBuilder(Builder: BuilderRef, Instr: ValueRef);
pub fn LLVMInsertIntoBuilderWithName(Builder: BuilderRef,
Instr: ValueRef,
Name: *const c_char);
pub fn LLVMDisposeBuilder(Builder: BuilderRef);
/* Execution engine */
pub fn LLVMRustCreateJITMemoryManager(morestack: *const ())
-> RustJITMemoryManagerRef;
pub fn LLVMBuildExecutionEngine(Mod: ModuleRef,
MM: RustJITMemoryManagerRef) -> ExecutionEngineRef;
pub fn LLVMDisposeExecutionEngine(EE: ExecutionEngineRef);
pub fn LLVMExecutionEngineFinalizeObject(EE: ExecutionEngineRef);
pub fn LLVMRustLoadDynamicLibrary(path: *const c_char) -> Bool;
pub fn LLVMExecutionEngineAddModule(EE: ExecutionEngineRef, M: ModuleRef);
pub fn LLVMExecutionEngineRemoveModule(EE: ExecutionEngineRef, M: ModuleRef)
-> Bool;
/* Metadata */
pub fn LLVMSetCurrentDebugLocation(Builder: BuilderRef, L: ValueRef);
pub fn LLVMGetCurrentDebugLocation(Builder: BuilderRef) -> ValueRef;
pub fn LLVMSetInstDebugLocation(Builder: BuilderRef, Inst: ValueRef);
/* Terminators */
pub fn LLVMBuildRetVoid(B: BuilderRef) -> ValueRef;
pub fn LLVMBuildRet(B: BuilderRef, V: ValueRef) -> ValueRef;
pub fn LLVMBuildAggregateRet(B: BuilderRef,
RetVals: *const ValueRef,
N: c_uint)
-> ValueRef;
pub fn LLVMBuildBr(B: BuilderRef, Dest: BasicBlockRef) -> ValueRef;
pub fn LLVMBuildCondBr(B: BuilderRef,
If: ValueRef,
Then: BasicBlockRef,
Else: BasicBlockRef)
-> ValueRef;
pub fn LLVMBuildSwitch(B: BuilderRef,
V: ValueRef,
Else: BasicBlockRef,
NumCases: c_uint)
-> ValueRef;
pub fn LLVMBuildIndirectBr(B: BuilderRef,
Addr: ValueRef,
NumDests: c_uint)
-> ValueRef;
pub fn LLVMBuildInvoke(B: BuilderRef,
Fn: ValueRef,
Args: *const ValueRef,
NumArgs: c_uint,
Then: BasicBlockRef,
Catch: BasicBlockRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildLandingPad(B: BuilderRef,
Ty: TypeRef,
PersFn: ValueRef,
NumClauses: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildResume(B: BuilderRef, Exn: ValueRef) -> ValueRef;
pub fn LLVMBuildUnreachable(B: BuilderRef) -> ValueRef;
/* Add a case to the switch instruction */
pub fn LLVMAddCase(Switch: ValueRef,
OnVal: ValueRef,
Dest: BasicBlockRef);
/* Add a destination to the indirectbr instruction */
pub fn LLVMAddDestination(IndirectBr: ValueRef, Dest: BasicBlockRef);
/* Add a clause to the landing pad instruction */
pub fn LLVMAddClause(LandingPad: ValueRef, ClauseVal: ValueRef);
/* Set the cleanup on a landing pad instruction */
pub fn LLVMSetCleanup(LandingPad: ValueRef, Val: Bool);
/* Arithmetic */
pub fn LLVMBuildAdd(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNSWAdd(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNUWAdd(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFAdd(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSub(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNSWSub(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNUWSub(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFSub(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildMul(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNSWMul(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNUWMul(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFMul(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildUDiv(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSDiv(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildExactSDiv(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFDiv(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildURem(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSRem(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFRem(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildShl(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildLShr(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildAShr(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildAnd(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildOr(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildXor(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildBinOp(B: BuilderRef,
Op: Opcode,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNeg(B: BuilderRef, V: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNSWNeg(B: BuilderRef, V: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNUWNeg(B: BuilderRef, V: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFNeg(B: BuilderRef, V: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNot(B: BuilderRef, V: ValueRef, Name: *const c_char)
-> ValueRef;
/* Memory */
pub fn LLVMBuildMalloc(B: BuilderRef, Ty: TypeRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildArrayMalloc(B: BuilderRef,
Ty: TypeRef,
Val: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildAlloca(B: BuilderRef, Ty: TypeRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildArrayAlloca(B: BuilderRef,
Ty: TypeRef,
Val: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFree(B: BuilderRef, PointerVal: ValueRef) -> ValueRef;
pub fn LLVMBuildLoad(B: BuilderRef,
PointerVal: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildStore(B: BuilderRef, Val: ValueRef, Ptr: ValueRef)
-> ValueRef;
pub fn LLVMBuildGEP(B: BuilderRef,
Pointer: ValueRef,
Indices: *const ValueRef,
NumIndices: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildInBoundsGEP(B: BuilderRef,
Pointer: ValueRef,
Indices: *const ValueRef,
NumIndices: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildStructGEP(B: BuilderRef,
Pointer: ValueRef,
Idx: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildGlobalString(B: BuilderRef,
Str: *const c_char,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildGlobalStringPtr(B: BuilderRef,
Str: *const c_char,
Name: *const c_char)
-> ValueRef;
/* Casts */
pub fn LLVMBuildTrunc(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildZExt(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSExt(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFPToUI(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFPToSI(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildUIToFP(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSIToFP(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFPTrunc(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFPExt(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildPtrToInt(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildIntToPtr(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildBitCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildZExtOrBitCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSExtOrBitCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildTruncOrBitCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildCast(B: BuilderRef,
Op: Opcode,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char) -> ValueRef;
pub fn LLVMBuildPointerCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildIntCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFPCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
/* Comparisons */
pub fn LLVMBuildICmp(B: BuilderRef,
Op: c_uint,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFCmp(B: BuilderRef,
Op: c_uint,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
/* Miscellaneous instructions */
pub fn LLVMBuildPhi(B: BuilderRef, Ty: TypeRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildCall(B: BuilderRef,
Fn: ValueRef,
Args: *const ValueRef,
NumArgs: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSelect(B: BuilderRef,
If: ValueRef,
Then: ValueRef,
Else: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildVAArg(B: BuilderRef,
list: ValueRef,
Ty: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildExtractElement(B: BuilderRef,
VecVal: ValueRef,
Index: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildInsertElement(B: BuilderRef,
VecVal: ValueRef,
EltVal: ValueRef,
Index: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildShuffleVector(B: BuilderRef,
V1: ValueRef,
V2: ValueRef,
Mask: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildExtractValue(B: BuilderRef,
AggVal: ValueRef,
Index: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildInsertValue(B: BuilderRef,
AggVal: ValueRef,
EltVal: ValueRef,
Index: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildIsNull(B: BuilderRef, Val: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildIsNotNull(B: BuilderRef, Val: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildPtrDiff(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
/* Atomic Operations */
pub fn LLVMBuildAtomicLoad(B: BuilderRef,
PointerVal: ValueRef,
Name: *const c_char,
Order: AtomicOrdering,
Alignment: c_uint)
-> ValueRef;
pub fn LLVMBuildAtomicStore(B: BuilderRef,
Val: ValueRef,
Ptr: ValueRef,
Order: AtomicOrdering,
Alignment: c_uint)
-> ValueRef;
pub fn LLVMBuildAtomicCmpXchg(B: BuilderRef,
LHS: ValueRef,
CMP: ValueRef,
RHS: ValueRef,
Order: AtomicOrdering,
FailureOrder: AtomicOrdering)
-> ValueRef;
pub fn LLVMBuildAtomicRMW(B: BuilderRef,
Op: AtomicBinOp,
LHS: ValueRef,
RHS: ValueRef,
Order: AtomicOrdering,
SingleThreaded: Bool)
-> ValueRef;
pub fn LLVMBuildAtomicFence(B: BuilderRef,
Order: AtomicOrdering,
Scope: SynchronizationScope);
/* Selected entries from the downcasts. */
pub fn LLVMIsATerminatorInst(Inst: ValueRef) -> ValueRef;
pub fn LLVMIsAStoreInst(Inst: ValueRef) -> ValueRef;
/// Writes a module to the specified path. Returns 0 on success.
pub fn LLVMWriteBitcodeToFile(M: ModuleRef, Path: *const c_char) -> c_int;
/// Creates target data from a target layout string.
pub fn LLVMCreateTargetData(StringRep: *const c_char) -> TargetDataRef;
/// Adds the target data to the given pass manager. The pass manager
/// references the target data only weakly.
pub fn LLVMAddTargetData(TD: TargetDataRef, PM: PassManagerRef);
/// Number of bytes clobbered when doing a Store to *T.
pub fn LLVMStoreSizeOfType(TD: TargetDataRef, Ty: TypeRef)
-> c_ulonglong;
/// Number of bytes clobbered when doing a Store to *T.
pub fn LLVMSizeOfTypeInBits(TD: TargetDataRef, Ty: TypeRef)
-> c_ulonglong;
/// Distance between successive elements in an array of T. Includes ABI padding.
pub fn LLVMABISizeOfType(TD: TargetDataRef, Ty: TypeRef) -> c_ulonglong;
/// Returns the preferred alignment of a type.
pub fn LLVMPreferredAlignmentOfType(TD: TargetDataRef, Ty: TypeRef)
-> c_uint;
/// Returns the minimum alignment of a type.
pub fn LLVMABIAlignmentOfType(TD: TargetDataRef, Ty: TypeRef)
-> c_uint;
/// Computes the byte offset of the indexed struct element for a
/// target.
pub fn LLVMOffsetOfElement(TD: TargetDataRef,
StructTy: TypeRef,
Element: c_uint)
-> c_ulonglong;
/// Returns the minimum alignment of a type when part of a call frame.
pub fn LLVMCallFrameAlignmentOfType(TD: TargetDataRef, Ty: TypeRef)
-> c_uint;
/// Disposes target data.
pub fn LLVMDisposeTargetData(TD: TargetDataRef);
/// Creates a pass manager.
pub fn LLVMCreatePassManager() -> PassManagerRef;
/// Creates a function-by-function pass manager
pub fn LLVMCreateFunctionPassManagerForModule(M: ModuleRef)
-> PassManagerRef;
/// Disposes a pass manager.
pub fn LLVMDisposePassManager(PM: PassManagerRef);
/// Runs a pass manager on a module.
pub fn LLVMRunPassManager(PM: PassManagerRef, M: ModuleRef) -> Bool;
/// Runs the function passes on the provided function.
pub fn LLVMRunFunctionPassManager(FPM: PassManagerRef, F: ValueRef)
-> Bool;
/// Initializes all the function passes scheduled in the manager
pub fn LLVMInitializeFunctionPassManager(FPM: PassManagerRef) -> Bool;
/// Finalizes all the function passes scheduled in the manager
pub fn LLVMFinalizeFunctionPassManager(FPM: PassManagerRef) -> Bool;
pub fn LLVMInitializePasses();
/// Adds a verification pass.
pub fn LLVMAddVerifierPass(PM: PassManagerRef);
pub fn LLVMAddGlobalOptimizerPass(PM: PassManagerRef);
pub fn LLVMAddIPSCCPPass(PM: PassManagerRef);
pub fn LLVMAddDeadArgEliminationPass(PM: PassManagerRef);
pub fn LLVMAddInstructionCombiningPass(PM: PassManagerRef);
pub fn LLVMAddCFGSimplificationPass(PM: PassManagerRef);
pub fn LLVMAddFunctionInliningPass(PM: PassManagerRef);
pub fn LLVMAddFunctionAttrsPass(PM: PassManagerRef);
pub fn LLVMAddScalarReplAggregatesPass(PM: PassManagerRef);
pub fn LLVMAddScalarReplAggregatesPassSSA(PM: PassManagerRef);
pub fn LLVMAddJumpThreadingPass(PM: PassManagerRef);
pub fn LLVMAddConstantPropagationPass(PM: PassManagerRef);
pub fn LLVMAddReassociatePass(PM: PassManagerRef);
pub fn LLVMAddLoopRotatePass(PM: PassManagerRef);
pub fn LLVMAddLICMPass(PM: PassManagerRef);
pub fn LLVMAddLoopUnswitchPass(PM: PassManagerRef);
pub fn LLVMAddLoopDeletionPass(PM: PassManagerRef);
pub fn LLVMAddLoopUnrollPass(PM: PassManagerRef);
pub fn LLVMAddGVNPass(PM: PassManagerRef);
pub fn LLVMAddMemCpyOptPass(PM: PassManagerRef);
pub fn LLVMAddSCCPPass(PM: PassManagerRef);
pub fn LLVMAddDeadStoreEliminationPass(PM: PassManagerRef);
pub fn LLVMAddStripDeadPrototypesPass(PM: PassManagerRef);
pub fn LLVMAddConstantMergePass(PM: PassManagerRef);
pub fn LLVMAddArgumentPromotionPass(PM: PassManagerRef);
pub fn LLVMAddTailCallEliminationPass(PM: PassManagerRef);
pub fn LLVMAddIndVarSimplifyPass(PM: PassManagerRef);
pub fn LLVMAddAggressiveDCEPass(PM: PassManagerRef);
pub fn LLVMAddGlobalDCEPass(PM: PassManagerRef);
pub fn LLVMAddCorrelatedValuePropagationPass(PM: PassManagerRef);
pub fn LLVMAddPruneEHPass(PM: PassManagerRef);
pub fn LLVMAddSimplifyLibCallsPass(PM: PassManagerRef);
pub fn LLVMAddLoopIdiomPass(PM: PassManagerRef);
pub fn LLVMAddEarlyCSEPass(PM: PassManagerRef);
pub fn LLVMAddTypeBasedAliasAnalysisPass(PM: PassManagerRef);
pub fn LLVMAddBasicAliasAnalysisPass(PM: PassManagerRef);
pub fn LLVMPassManagerBuilderCreate() -> PassManagerBuilderRef;
pub fn LLVMPassManagerBuilderDispose(PMB: PassManagerBuilderRef);
pub fn LLVMPassManagerBuilderSetOptLevel(PMB: PassManagerBuilderRef,
OptimizationLevel: c_uint);
pub fn LLVMPassManagerBuilderSetSizeLevel(PMB: PassManagerBuilderRef,
Value: Bool);
pub fn LLVMPassManagerBuilderSetDisableUnitAtATime(
PMB: PassManagerBuilderRef,
Value: Bool);
pub fn LLVMPassManagerBuilderSetDisableUnrollLoops(
PMB: PassManagerBuilderRef,
Value: Bool);
pub fn LLVMPassManagerBuilderSetDisableSimplifyLibCalls(
PMB: PassManagerBuilderRef,
Value: Bool);
pub fn LLVMPassManagerBuilderUseInlinerWithThreshold(
PMB: PassManagerBuilderRef,
threshold: c_uint);
pub fn LLVMPassManagerBuilderPopulateModulePassManager(
PMB: PassManagerBuilderRef,
PM: PassManagerRef);
pub fn LLVMPassManagerBuilderPopulateFunctionPassManager(
PMB: PassManagerBuilderRef,
PM: PassManagerRef);
pub fn LLVMPassManagerBuilderPopulateLTOPassManager(
PMB: PassManagerBuilderRef,
PM: PassManagerRef,
Internalize: Bool,
RunInliner: Bool);
/// Destroys a memory buffer.
pub fn LLVMDisposeMemoryBuffer(MemBuf: MemoryBufferRef);
/* Stuff that's in rustllvm/ because it's not upstream yet. */
/// Opens an object file.
pub fn LLVMCreateObjectFile(MemBuf: MemoryBufferRef) -> ObjectFileRef;
/// Closes an object file.
pub fn LLVMDisposeObjectFile(ObjFile: ObjectFileRef);
/// Enumerates the sections in an object file.
pub fn LLVMGetSections(ObjFile: ObjectFileRef) -> SectionIteratorRef;
/// Destroys a section iterator.
pub fn LLVMDisposeSectionIterator(SI: SectionIteratorRef);
/// Returns true if the section iterator is at the end of the section
/// list:
pub fn LLVMIsSectionIteratorAtEnd(ObjFile: ObjectFileRef,
SI: SectionIteratorRef)
-> Bool;
/// Moves the section iterator to point to the next section.
pub fn LLVMMoveToNextSection(SI: SectionIteratorRef);
/// Returns the current section size.
pub fn LLVMGetSectionSize(SI: SectionIteratorRef) -> c_ulonglong;
/// Returns the current section contents as a string buffer.
pub fn LLVMGetSectionContents(SI: SectionIteratorRef) -> *const c_char;
/// Reads the given file and returns it as a memory buffer. Use
/// LLVMDisposeMemoryBuffer() to get rid of it.
pub fn LLVMRustCreateMemoryBufferWithContentsOfFile(Path: *const c_char)
-> MemoryBufferRef;
/// Borrows the contents of the memory buffer (doesn't copy it)
pub fn LLVMCreateMemoryBufferWithMemoryRange(InputData: *const c_char,
InputDataLength: size_t,
BufferName: *const c_char,
RequiresNull: Bool)
-> MemoryBufferRef;
pub fn LLVMCreateMemoryBufferWithMemoryRangeCopy(InputData: *const c_char,
InputDataLength: size_t,
BufferName: *const c_char)
-> MemoryBufferRef;
pub fn LLVMIsMultithreaded() -> Bool;
pub fn LLVMStartMultithreaded() -> Bool;
/// Returns a string describing the last error caused by an LLVMRust* call.
pub fn LLVMRustGetLastError() -> *const c_char;
/// Print the pass timings since static dtors aren't picking them up.
pub fn LLVMRustPrintPassTimings();
pub fn LLVMStructCreateNamed(C: ContextRef, Name: *const c_char) -> TypeRef;
pub fn LLVMStructSetBody(StructTy: TypeRef,
ElementTypes: *const TypeRef,
ElementCount: c_uint,
Packed: Bool);
pub fn LLVMConstNamedStruct(S: TypeRef,
ConstantVals: *const ValueRef,
Count: c_uint)
-> ValueRef;
/// Enables LLVM debug output.
pub fn LLVMSetDebug(Enabled: c_int);
/// Prepares inline assembly.
pub fn LLVMInlineAsm(Ty: TypeRef,
AsmString: *const c_char,
Constraints: *const c_char,
SideEffects: Bool,
AlignStack: Bool,
Dialect: c_uint)
-> ValueRef;
pub static LLVMRustDebugMetadataVersion: u32;
pub fn LLVMRustAddModuleFlag(M: ModuleRef,
name: *const c_char,
value: u32);
pub fn LLVMDIBuilderCreate(M: ModuleRef) -> DIBuilderRef;
pub fn LLVMDIBuilderDispose(Builder: DIBuilderRef);
pub fn LLVMDIBuilderFinalize(Builder: DIBuilderRef);
pub fn LLVMDIBuilderCreateCompileUnit(Builder: DIBuilderRef,
Lang: c_uint,
File: *const c_char,
Dir: *const c_char,
Producer: *const c_char,
isOptimized: bool,
Flags: *const c_char,
RuntimeVer: c_uint,
SplitName: *const c_char)
-> DIDescriptor;
pub fn LLVMDIBuilderCreateFile(Builder: DIBuilderRef,
Filename: *const c_char,
Directory: *const c_char)
-> DIFile;
pub fn LLVMDIBuilderCreateSubroutineType(Builder: DIBuilderRef,
File: DIFile,
ParameterTypes: DIArray)
-> DICompositeType;
pub fn LLVMDIBuilderCreateFunction(Builder: DIBuilderRef,
Scope: DIDescriptor,
Name: *const c_char,
LinkageName: *const c_char,
File: DIFile,
LineNo: c_uint,
Ty: DIType,
isLocalToUnit: bool,
isDefinition: bool,
ScopeLine: c_uint,
Flags: c_uint,
isOptimized: bool,
Fn: ValueRef,
TParam: DIArray,
Decl: DIDescriptor)
-> DISubprogram;
pub fn LLVMDIBuilderCreateBasicType(Builder: DIBuilderRef,
Name: *const c_char,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
Encoding: c_uint)
-> DIBasicType;
pub fn LLVMDIBuilderCreatePointerType(Builder: DIBuilderRef,
PointeeTy: DIType,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
Name: *const c_char)
-> DIDerivedType;
pub fn LLVMDIBuilderCreateStructType(Builder: DIBuilderRef,
Scope: DIDescriptor,
Name: *const c_char,
File: DIFile,
LineNumber: c_uint,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
Flags: c_uint,
DerivedFrom: DIType,
Elements: DIArray,
RunTimeLang: c_uint,
VTableHolder: DIType,
UniqueId: *const c_char)
-> DICompositeType;
pub fn LLVMDIBuilderCreateMemberType(Builder: DIBuilderRef,
Scope: DIDescriptor,
Name: *const c_char,
File: DIFile,
LineNo: c_uint,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
OffsetInBits: c_ulonglong,
Flags: c_uint,
Ty: DIType)
-> DIDerivedType;
pub fn LLVMDIBuilderCreateLexicalBlock(Builder: DIBuilderRef,
Scope: DIScope,
File: DIFile,
Line: c_uint,
Col: c_uint)
-> DILexicalBlock;
pub fn LLVMDIBuilderCreateStaticVariable(Builder: DIBuilderRef,
Context: DIScope,
Name: *const c_char,
LinkageName: *const c_char,
File: DIFile,
LineNo: c_uint,
Ty: DIType,
isLocalToUnit: bool,
Val: ValueRef,
Decl: DIDescriptor)
-> DIGlobalVariable;
pub fn LLVMDIBuilderCreateVariable(Builder: DIBuilderRef,
Tag: c_uint,
Scope: DIDescriptor,
Name: *const c_char,
File: DIFile,
LineNo: c_uint,
Ty: DIType,
AlwaysPreserve: bool,
Flags: c_uint,
AddrOps: *const i64,
AddrOpsCount: c_uint,
ArgNo: c_uint)
-> DIVariable;
pub fn LLVMDIBuilderCreateArrayType(Builder: DIBuilderRef,
Size: c_ulonglong,
AlignInBits: c_ulonglong,
Ty: DIType,
Subscripts: DIArray)
-> DIType;
pub fn LLVMDIBuilderCreateVectorType(Builder: DIBuilderRef,
Size: c_ulonglong,
AlignInBits: c_ulonglong,
Ty: DIType,
Subscripts: DIArray)
-> DIType;
pub fn LLVMDIBuilderGetOrCreateSubrange(Builder: DIBuilderRef,
Lo: c_longlong,
Count: c_longlong)
-> DISubrange;
pub fn LLVMDIBuilderGetOrCreateArray(Builder: DIBuilderRef,
Ptr: *const DIDescriptor,
Count: c_uint)
-> DIArray;
pub fn LLVMDIBuilderInsertDeclareAtEnd(Builder: DIBuilderRef,
Val: ValueRef,
VarInfo: DIVariable,
AddrOps: *const i64,
AddrOpsCount: c_uint,
InsertAtEnd: BasicBlockRef)
-> ValueRef;
pub fn LLVMDIBuilderInsertDeclareBefore(Builder: DIBuilderRef,
Val: ValueRef,
VarInfo: DIVariable,
AddrOps: *const i64,
AddrOpsCount: c_uint,
InsertBefore: ValueRef)
-> ValueRef;
pub fn LLVMDIBuilderCreateEnumerator(Builder: DIBuilderRef,
Name: *const c_char,
Val: c_ulonglong)
-> DIEnumerator;
pub fn LLVMDIBuilderCreateEnumerationType(Builder: DIBuilderRef,
Scope: DIScope,
Name: *const c_char,
File: DIFile,
LineNumber: c_uint,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
Elements: DIArray,
ClassType: DIType)
-> DIType;
pub fn LLVMDIBuilderCreateUnionType(Builder: DIBuilderRef,
Scope: DIScope,
Name: *const c_char,
File: DIFile,
LineNumber: c_uint,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
Flags: c_uint,
Elements: DIArray,
RunTimeLang: c_uint,
UniqueId: *const c_char)
-> DIType;
pub fn LLVMSetUnnamedAddr(GlobalVar: ValueRef, UnnamedAddr: Bool);
pub fn LLVMDIBuilderCreateTemplateTypeParameter(Builder: DIBuilderRef,
Scope: DIScope,
Name: *const c_char,
Ty: DIType,
File: DIFile,
LineNo: c_uint,
ColumnNo: c_uint)
-> DITemplateTypeParameter;
pub fn LLVMDIBuilderCreateOpDeref() -> i64;
pub fn LLVMDIBuilderCreateOpPlus() -> i64;
pub fn LLVMDIBuilderCreateNameSpace(Builder: DIBuilderRef,
Scope: DIScope,
Name: *const c_char,
File: DIFile,
LineNo: c_uint)
-> DINameSpace;
pub fn LLVMDIBuilderCreateDebugLocation(Context: ContextRef,
Line: c_uint,
Column: c_uint,
Scope: DIScope,
InlinedAt: MetadataRef)
-> ValueRef;
pub fn LLVMDICompositeTypeSetTypeArray(Builder: DIBuilderRef,
CompositeType: DIType,
TypeArray: DIArray);
pub fn LLVMWriteTypeToString(Type: TypeRef, s: RustStringRef);
pub fn LLVMWriteValueToString(value_ref: ValueRef, s: RustStringRef);
pub fn LLVMIsAArgument(value_ref: ValueRef) -> ValueRef;
pub fn LLVMIsAAllocaInst(value_ref: ValueRef) -> ValueRef;
pub fn LLVMIsAConstantInt(value_ref: ValueRef) -> ValueRef;
pub fn LLVMInitializeX86TargetInfo();
pub fn LLVMInitializeX86Target();
pub fn LLVMInitializeX86TargetMC();
pub fn LLVMInitializeX86AsmPrinter();
pub fn LLVMInitializeX86AsmParser();
pub fn LLVMInitializeARMTargetInfo();
pub fn LLVMInitializeARMTarget();
pub fn LLVMInitializeARMTargetMC();
pub fn LLVMInitializeARMAsmPrinter();
pub fn LLVMInitializeARMAsmParser();
pub fn LLVMInitializeAArch64TargetInfo();
pub fn LLVMInitializeAArch64Target();
pub fn LLVMInitializeAArch64TargetMC();
pub fn LLVMInitializeAArch64AsmPrinter();
pub fn LLVMInitializeAArch64AsmParser();
pub fn LLVMInitializeMipsTargetInfo();
pub fn LLVMInitializeMipsTarget();
pub fn LLVMInitializeMipsTargetMC();
pub fn LLVMInitializeMipsAsmPrinter();
pub fn LLVMInitializeMipsAsmParser();
pub fn LLVMInitializePowerPCTargetInfo();
pub fn LLVMInitializePowerPCTarget();
pub fn LLVMInitializePowerPCTargetMC();
pub fn LLVMInitializePowerPCAsmPrinter();
pub fn LLVMInitializePowerPCAsmParser();
pub fn LLVMRustAddPass(PM: PassManagerRef, Pass: *const c_char) -> bool;
pub fn LLVMRustCreateTargetMachine(Triple: *const c_char,
CPU: *const c_char,
Features: *const c_char,
Model: CodeGenModel,
Reloc: RelocMode,
Level: CodeGenOptLevel,
EnableSegstk: bool,
UseSoftFP: bool,
NoFramePointerElim: bool,
PositionIndependentExecutable: bool,
FunctionSections: bool,
DataSections: bool) -> TargetMachineRef;
pub fn LLVMRustDisposeTargetMachine(T: TargetMachineRef);
pub fn LLVMRustAddAnalysisPasses(T: TargetMachineRef,
PM: PassManagerRef,
M: ModuleRef);
pub fn LLVMRustAddBuilderLibraryInfo(PMB: PassManagerBuilderRef,
M: ModuleRef,
DisableSimplifyLibCalls: bool);
pub fn LLVMRustAddLibraryInfo(PM: PassManagerRef, M: ModuleRef,
DisableSimplifyLibCalls: bool);
pub fn LLVMRustRunFunctionPassManager(PM: PassManagerRef, M: ModuleRef);
pub fn LLVMRustWriteOutputFile(T: TargetMachineRef,
PM: PassManagerRef,
M: ModuleRef,
Output: *const c_char,
FileType: FileType) -> bool;
pub fn LLVMRustPrintModule(PM: PassManagerRef,
M: ModuleRef,
Output: *const c_char);
pub fn LLVMRustSetLLVMOptions(Argc: c_int, Argv: *const *const c_char);
pub fn LLVMRustPrintPasses();
pub fn LLVMRustSetNormalizedTarget(M: ModuleRef, triple: *const c_char);
pub fn LLVMRustAddAlwaysInlinePass(P: PassManagerBuilderRef,
AddLifetimes: bool);
pub fn LLVMRustLinkInExternalBitcode(M: ModuleRef,
bc: *const c_char,
len: size_t) -> bool;
pub fn LLVMRustRunRestrictionPass(M: ModuleRef,
syms: *const *const c_char,
len: size_t);
pub fn LLVMRustMarkAllFunctionsNounwind(M: ModuleRef);
pub fn LLVMRustOpenArchive(path: *const c_char) -> ArchiveRef;
pub fn LLVMRustArchiveIteratorNew(AR: ArchiveRef) -> ArchiveIteratorRef;
pub fn LLVMRustArchiveIteratorNext(AIR: ArchiveIteratorRef);
pub fn LLVMRustArchiveIteratorCurrent(AIR: ArchiveIteratorRef) -> ArchiveChildRef;
pub fn LLVMRustArchiveChildName(ACR: ArchiveChildRef,
size: *mut size_t) -> *const c_char;
pub fn LLVMRustArchiveChildData(ACR: ArchiveChildRef,
size: *mut size_t) -> *const c_char;
pub fn LLVMRustArchiveIteratorFree(AIR: ArchiveIteratorRef);
pub fn LLVMRustDestroyArchive(AR: ArchiveRef);
pub fn LLVMRustSetDLLExportStorageClass(V: ValueRef);
pub fn LLVMRustGetSectionName(SI: SectionIteratorRef,
data: *mut *const c_char) -> c_int;
pub fn LLVMWriteTwineToString(T: TwineRef, s: RustStringRef);
pub fn LLVMContextSetDiagnosticHandler(C: ContextRef,
Handler: DiagnosticHandler,
DiagnosticContext: *mut c_void);
pub fn LLVMUnpackOptimizationDiagnostic(DI: DiagnosticInfoRef,
pass_name_out: *mut *const c_char,
function_out: *mut ValueRef,
debugloc_out: *mut DebugLocRef,
message_out: *mut TwineRef);
pub fn LLVMUnpackInlineAsmDiagnostic(DI: DiagnosticInfoRef,
cookie_out: *mut c_uint,
message_out: *mut TwineRef,
instruction_out: *mut ValueRef);
pub fn LLVMWriteDiagnosticInfoToString(DI: DiagnosticInfoRef, s: RustStringRef);
pub fn LLVMGetDiagInfoSeverity(DI: DiagnosticInfoRef) -> DiagnosticSeverity;
pub fn LLVMGetDiagInfoKind(DI: DiagnosticInfoRef) -> DiagnosticKind;
pub fn LLVMWriteDebugLocToString(C: ContextRef, DL: DebugLocRef, s: RustStringRef);
pub fn LLVMSetInlineAsmDiagnosticHandler(C: ContextRef,
H: InlineAsmDiagHandler,
CX: *mut c_void);
pub fn LLVMWriteSMDiagnosticToString(d: SMDiagnosticRef, s: RustStringRef);
}
pub fn SetInstructionCallConv(instr: ValueRef, cc: CallConv) {
unsafe {
LLVMSetInstructionCallConv(instr, cc as c_uint);
}
}
pub fn SetFunctionCallConv(fn_: ValueRef, cc: CallConv) {
unsafe {
LLVMSetFunctionCallConv(fn_, cc as c_uint);
}
}
pub fn SetLinkage(global: ValueRef, link: Linkage) {
unsafe {
LLVMSetLinkage(global, link as c_uint);
}
}
pub fn SetUnnamedAddr(global: ValueRef, unnamed: bool) {
unsafe {
LLVMSetUnnamedAddr(global, unnamed as Bool);
}
}
pub fn set_thread_local(global: ValueRef, is_thread_local: bool) {
unsafe {
LLVMSetThreadLocal(global, is_thread_local as Bool);
}
}
pub fn ConstICmp(pred: IntPredicate, v1: ValueRef, v2: ValueRef) -> ValueRef {
unsafe {
LLVMConstICmp(pred as c_ushort, v1, v2)
}
}
pub fn ConstFCmp(pred: RealPredicate, v1: ValueRef, v2: ValueRef) -> ValueRef {
unsafe {
LLVMConstFCmp(pred as c_ushort, v1, v2)
}
}
pub fn SetFunctionAttribute(fn_: ValueRef, attr: Attribute) {
unsafe {
LLVMAddFunctionAttribute(fn_, FunctionIndex as c_uint, attr.bits() as uint64_t)
}
}
/* Memory-managed interface to target data. */
pub struct TargetData {
pub lltd: TargetDataRef
}
impl Drop for TargetData {
fn drop(&mut self) {
unsafe {
LLVMDisposeTargetData(self.lltd);
}
}
}
pub fn mk_target_data(string_rep: &str) -> TargetData {
let string_rep = CString::new(string_rep).unwrap();
TargetData {
lltd: unsafe { LLVMCreateTargetData(string_rep.as_ptr()) }
}
}
/* Memory-managed interface to object files. */
pub struct ObjectFile {
pub llof: ObjectFileRef,
}
impl ObjectFile {
// This will take ownership of llmb
pub fn new(llmb: MemoryBufferRef) -> Option<ObjectFile> {
unsafe {
let llof = LLVMCreateObjectFile(llmb);
if llof as isize == 0 {
// LLVMCreateObjectFile took ownership of llmb
return None
}
Some(ObjectFile {
llof: llof,
})
}
}
}
impl Drop for ObjectFile {
fn drop(&mut self) {
unsafe {
LLVMDisposeObjectFile(self.llof);
}
}
}
/* Memory-managed interface to section iterators. */
pub struct SectionIter {
pub llsi: SectionIteratorRef
}
impl Drop for SectionIter {
fn drop(&mut self) {
unsafe {
LLVMDisposeSectionIterator(self.llsi);
}
}
}
pub fn mk_section_iter(llof: ObjectFileRef) -> SectionIter {
unsafe {
SectionIter {
llsi: LLVMGetSections(llof)
}
}
}
/// Safe wrapper around `LLVMGetParam`, because segfaults are no fun.
pub fn get_param(llfn: ValueRef, index: c_uint) -> ValueRef {
unsafe {
assert!(index < LLVMCountParams(llfn));
LLVMGetParam(llfn, index)
}
}
#[allow(missing_copy_implementations)]
pub enum RustString_opaque {}
pub type RustStringRef = *mut RustString_opaque;
type RustStringRepr = *mut RefCell<Vec<u8>>;
/// Appending to a Rust string -- used by raw_rust_string_ostream.
#[no_mangle]
pub unsafe extern "C" fn rust_llvm_string_write_impl(sr: RustStringRef,
ptr: *const c_char,
size: size_t) {
let slice = slice::from_raw_parts(ptr as *const u8, size as usize);
let sr: RustStringRepr = mem::transmute(sr);
(*sr).borrow_mut().push_all(slice);
}
pub fn build_string<F>(f: F) -> Option<String> where F: FnOnce(RustStringRef){
let mut buf = RefCell::new(Vec::new());
f(&mut buf as RustStringRepr as RustStringRef);
String::from_utf8(buf.into_inner()).ok()
}
pub unsafe fn twine_to_string(tr: TwineRef) -> String {
build_string(|s| LLVMWriteTwineToString(tr, s))
.expect("got a non-UTF8 Twine from LLVM")
}
pub unsafe fn debug_loc_to_string(c: ContextRef, tr: DebugLocRef) -> String {
build_string(|s| LLVMWriteDebugLocToString(c, tr, s))
.expect("got a non-UTF8 DebugLoc from LLVM")
}
// The module containing the native LLVM dependencies, generated by the build system
// Note that this must come after the rustllvm extern declaration so that
// parts of LLVM that rustllvm depends on aren't thrown away by the linker.
// Works to the above fix for #15460 to ensure LLVM dependencies that
// are only used by rustllvm don't get stripped by the linker.
mod llvmdeps {
include! { env!("CFG_LLVM_LINKAGE_FILE") }
}
| 41.891619 | 100 | 0.534696 |
bb7c63d5f5943e0bbce6009b70f6f3b1a02cf6cb
| 1,341 |
use std::sync::mpsc;
use std::{thread, time};
use actix_web::{dev::Server, middleware, rt, web, App, HttpRequest, HttpServer};
async fn index(req: HttpRequest) -> &'static str {
println!("REQ: {:?}", req);
"Hello world!"
}
fn run_app(tx: mpsc::Sender<Server>) -> std::io::Result<()> {
let mut sys = rt::System::new("test");
// srv is server controller type, `dev::Server`
let srv = HttpServer::new(|| {
App::new()
// enable logger
.wrap(middleware::Logger::default())
.service(web::resource("/index.html").to(|| async { "Hello world!" }))
.service(web::resource("/").to(index))
})
.bind("127.0.0.1:8080")?
.run();
// send server controller to main thread
let _ = tx.send(srv.clone());
// run future
sys.block_on(srv)
}
fn main() {
std::env::set_var("RUST_LOG", "actix_web=info,actix_server=trace");
env_logger::init();
let (tx, rx) = mpsc::channel();
println!("START SERVER");
thread::spawn(move || {
let _ = run_app(tx);
});
let srv = rx.recv().unwrap();
println!("WAITING 10 SECONDS");
thread::sleep(time::Duration::from_secs(10));
println!("STOPPING SERVER");
// init stop server and wait until server gracefully exit
rt::System::new("").block_on(srv.stop(true));
}
| 25.788462 | 82 | 0.577181 |
f7ded06ade9b31f8f7e5562e948d75e8671b6177
| 7,825 |
use crate::direction::Direction;
use crate::event::{AnyCb, Event, EventResult};
use crate::rect::Rect;
use crate::vec::Vec2;
use crate::view::{Selector, View};
use crate::Printer;
use crate::With;
// Define this type separately to appease the Clippy god
type CallOnAny<T> = Box<dyn for<'a> FnMut(&mut T, &Selector, AnyCb<'a>)>;
/// A blank view that forwards calls to closures.
///
/// You can use this view to easily draw your own interface.
pub struct Canvas<T> {
state: T,
draw: Box<dyn Fn(&T, &Printer)>,
on_event: Box<dyn FnMut(&mut T, Event) -> EventResult>,
required_size: Box<dyn FnMut(&mut T, Vec2) -> Vec2>,
layout: Box<dyn FnMut(&mut T, Vec2)>,
take_focus: Box<dyn FnMut(&mut T, Direction) -> bool>,
needs_relayout: Box<dyn Fn(&T) -> bool>,
focus_view: Box<dyn FnMut(&mut T, &Selector) -> Result<(), ()>>,
call_on_any: CallOnAny<T>,
important_area: Box<dyn Fn(&T, Vec2) -> Rect>,
}
impl<T: 'static + View> Canvas<T> {
/// Creates a new Canvas around the given view.
///
/// By default, forwards all calls to the inner view.
pub fn wrap(view: T) -> Self {
Canvas::new(view)
.with_draw(T::draw)
.with_on_event(T::on_event)
.with_required_size(T::required_size)
.with_layout(T::layout)
.with_take_focus(T::take_focus)
.with_needs_relayout(T::needs_relayout)
.with_focus_view(T::focus_view)
.with_call_on_any(T::call_on_any)
.with_important_area(T::important_area)
}
}
impl<T> Canvas<T> {
/// Creates a new, empty Canvas.
///
/// # Examples
///
/// ```rust
/// # use cursive::views::Canvas;
/// let canvas = Canvas::new(())
/// .with_draw(|printer, _| {
/// // Print the view
/// });
/// ```
pub fn new(state: T) -> Self {
Canvas {
state,
draw: Box::new(|_, _| ()),
on_event: Box::new(|_, _| EventResult::Ignored),
required_size: Box::new(|_, _| Vec2::new(1, 1)),
layout: Box::new(|_, _| ()),
take_focus: Box::new(|_, _| false),
needs_relayout: Box::new(|_| true),
focus_view: Box::new(|_, _| Err(())),
call_on_any: Box::new(|_, _, _| ()),
important_area: Box::new(|_, size| {
Rect::from_corners((0, 0), size)
}),
}
}
/// Gets a mutable reference to the inner state.
pub fn state_mut(&mut self) -> &mut T {
&mut self.state
}
/// Sets the closure for `draw(&Printer)`.
pub fn set_draw<F>(&mut self, f: F)
where
F: 'static + Fn(&T, &Printer<'_, '_>),
{
self.draw = Box::new(f);
}
/// Sets the closure for `draw(&Printer)`.
///
/// Chainable variant.
pub fn with_draw<F>(self, f: F) -> Self
where
F: 'static + Fn(&T, &Printer<'_, '_>),
{
self.with(|s| s.set_draw(f))
}
/// Sets the closure for `on_event(Event)`.
pub fn set_on_event<F>(&mut self, f: F)
where
F: 'static + FnMut(&mut T, Event) -> EventResult,
{
self.on_event = Box::new(f);
}
/// Sets the closure for `on_event(Event)`.
///
/// Chainable variant.
pub fn with_on_event<F>(self, f: F) -> Self
where
F: 'static + FnMut(&mut T, Event) -> EventResult,
{
self.with(|s| s.set_on_event(f))
}
/// Sets the closure for `required_size(Vec2)`.
pub fn set_required_size<F>(&mut self, f: F)
where
F: 'static + FnMut(&mut T, Vec2) -> Vec2,
{
self.required_size = Box::new(f);
}
/// Sets the closure for `required_size(Vec2)`.
///
/// Chainable variant.
pub fn with_required_size<F>(self, f: F) -> Self
where
F: 'static + FnMut(&mut T, Vec2) -> Vec2,
{
self.with(|s| s.set_required_size(f))
}
/// Sets the closure for `layout(Vec2)`.
pub fn set_layout<F>(&mut self, f: F)
where
F: 'static + FnMut(&mut T, Vec2),
{
self.layout = Box::new(f);
}
/// Sets the closure for `layout(Vec2)`.
///
/// Chainable variant.
pub fn with_layout<F>(self, f: F) -> Self
where
F: 'static + FnMut(&mut T, Vec2),
{
self.with(|s| s.set_layout(f))
}
/// Sets the closure for `take_focus(Direction)`.
pub fn set_take_focus<F>(&mut self, f: F)
where
F: 'static + FnMut(&mut T, Direction) -> bool,
{
self.take_focus = Box::new(f);
}
/// Sets the closure for `take_focus(Direction)`.
///
/// Chainable variant.
pub fn with_take_focus<F>(self, f: F) -> Self
where
F: 'static + FnMut(&mut T, Direction) -> bool,
{
self.with(|s| s.set_take_focus(f))
}
/// Sets the closure for `needs_relayout()`.
pub fn set_needs_relayout<F>(&mut self, f: F)
where
F: 'static + Fn(&T) -> bool,
{
self.needs_relayout = Box::new(f);
}
/// Sets the closure for `needs_relayout()`.
///
/// Chainable variant.
pub fn with_needs_relayout<F>(self, f: F) -> Self
where
F: 'static + Fn(&T) -> bool,
{
self.with(|s| s.set_needs_relayout(f))
}
/// Sets the closure for `call_on_any()`.
pub fn set_call_on_any<F>(&mut self, f: F)
where
F: 'static + for<'a> FnMut(&mut T, &Selector<'_>, AnyCb<'a>),
{
self.call_on_any = Box::new(f);
}
/// Sets the closure for `call_on_any()`.
///
/// Chainable variant.
pub fn with_call_on_any<F>(self, f: F) -> Self
where
F: 'static + for<'a> FnMut(&mut T, &Selector<'_>, AnyCb<'a>),
{
self.with(|s| s.set_call_on_any(f))
}
/// Sets the closure for `important_area()`.
pub fn set_important_area<F>(&mut self, f: F)
where
F: 'static + Fn(&T, Vec2) -> Rect,
{
self.important_area = Box::new(f);
}
/// Sets the closure for `important_area()`.
///
/// Chainable variant.
pub fn with_important_area<F>(self, f: F) -> Self
where
F: 'static + Fn(&T, Vec2) -> Rect,
{
self.with(|s| s.set_important_area(f))
}
/// Sets the closure for `focus_view()`.
pub fn set_focus_view<F>(&mut self, f: F)
where
F: 'static + FnMut(&mut T, &Selector<'_>) -> Result<(), ()>,
{
self.focus_view = Box::new(f);
}
/// Sets the closure for `focus_view()`.
///
/// Chainable variant.
pub fn with_focus_view<F>(self, f: F) -> Self
where
F: 'static + FnMut(&mut T, &Selector<'_>) -> Result<(), ()>,
{
self.with(|s| s.set_focus_view(f))
}
}
impl<T: 'static> View for Canvas<T> {
fn draw(&self, printer: &Printer<'_, '_>) {
(self.draw)(&self.state, printer);
}
fn on_event(&mut self, event: Event) -> EventResult {
(self.on_event)(&mut self.state, event)
}
fn required_size(&mut self, constraint: Vec2) -> Vec2 {
(self.required_size)(&mut self.state, constraint)
}
fn layout(&mut self, size: Vec2) {
(self.layout)(&mut self.state, size);
}
fn take_focus(&mut self, source: Direction) -> bool {
(self.take_focus)(&mut self.state, source)
}
fn needs_relayout(&self) -> bool {
(self.needs_relayout)(&self.state)
}
fn focus_view(&mut self, selector: &Selector<'_>) -> Result<(), ()> {
(self.focus_view)(&mut self.state, selector)
}
fn important_area(&self, view_size: Vec2) -> Rect {
(self.important_area)(&self.state, view_size)
}
fn call_on_any<'a>(&mut self, selector: &Selector<'_>, cb: AnyCb<'a>) {
(self.call_on_any)(&mut self.state, selector, cb);
}
}
| 27.846975 | 75 | 0.538786 |
22f6a34a181fb249d5a3ad75097087c0a8a5eb39
| 693 |
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern:mismatched types: expected `char` but found
// Issue #876
#[no_core];
extern mod core;
fn last<T>(v: ~[&T]) -> core::option::Option<T> {
fail!();
}
fn main() {
let y;
let x : char = last(y);
}
| 26.653846 | 68 | 0.686869 |
91d22b46400f614b761d8a637ce0b279e7767212
| 44 |
mod file_listener;
pub use file_listener::*;
| 22 | 25 | 0.795455 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.